Compare commits
9 Commits
Author | SHA1 | Date |
---|---|---|
|
5c8e230e70 | |
|
e47733cae8 | |
|
a883893490 | |
|
8d9e63b560 | |
|
12c1a42138 | |
|
72fd24fc61 | |
|
0335ac8b9c | |
|
e17a1cb46d | |
|
1a3a3d6b14 |
14
.classpath
14
.classpath
|
@ -11,13 +11,6 @@
|
||||||
<attribute name="maven.pomderived" value="true"/>
|
<attribute name="maven.pomderived" value="true"/>
|
||||||
</attributes>
|
</attributes>
|
||||||
</classpathentry>
|
</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">
|
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
|
||||||
<attributes>
|
<attributes>
|
||||||
<attribute name="test" value="true"/>
|
<attribute name="test" value="true"/>
|
||||||
|
@ -34,5 +27,12 @@
|
||||||
<attribute name="maven.pomderived" value="true"/>
|
<attribute name="maven.pomderived" value="true"/>
|
||||||
</attributes>
|
</attributes>
|
||||||
</classpathentry>
|
</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"/>
|
<classpathentry kind="output" path="target/classes"/>
|
||||||
</classpath>
|
</classpath>
|
||||||
|
|
|
@ -1,13 +1,26 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
|
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
|
||||||
|
|
||||||
<wb-module deploy-name="grsf-manage-widget">
|
<wb-module deploy-name="grsf-manage-widget">
|
||||||
|
|
||||||
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
|
<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="/" 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/java"/>
|
||||||
|
|
||||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
|
<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">
|
<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>
|
<dependency-type>uses</dependency-type>
|
||||||
|
|
||||||
</dependent-module>
|
</dependent-module>
|
||||||
|
|
||||||
<property name="context-root" value="grsf-manage-widget"/>
|
<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"/>
|
<property name="java-output-path" value="/grsf-manage-widget/target/grsf-manage-widget-1.0.0-SNAPSHOT/WEB-INF/classes"/>
|
||||||
|
|
||||||
</wb-module>
|
</wb-module>
|
||||||
|
|
||||||
</project-modules>
|
</project-modules>
|
||||||
|
|
|
@ -0,0 +1,7 @@
|
||||||
|
<root>
|
||||||
|
<facet id="jst.jaxrs">
|
||||||
|
<node name="libprov">
|
||||||
|
<attribute name="provider-id" value="jaxrs-no-op-library-provider"/>
|
||||||
|
</node>
|
||||||
|
</facet>
|
||||||
|
</root>
|
|
@ -4,4 +4,5 @@
|
||||||
<installed facet="jst.web" version="2.3"/>
|
<installed facet="jst.web" version="2.3"/>
|
||||||
<installed facet="wst.jsdt.web" version="1.0"/>
|
<installed facet="wst.jsdt.web" version="1.0"/>
|
||||||
<installed facet="java" version="1.7"/>
|
<installed facet="java" version="1.7"/>
|
||||||
|
<installed facet="jst.jaxrs" version="2.0"/>
|
||||||
</faceted-project>
|
</faceted-project>
|
||||||
|
|
24
CHANGELOG.md
24
CHANGELOG.md
|
@ -4,6 +4,30 @@
|
||||||
All notable changes to this project will be documented in this file.
|
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).
|
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [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
|
## [v1.5.0] - 2021-04-12
|
||||||
|
|
||||||
[#21153] Upgrade the maven-portal-bom to 3.6.1 version
|
[#21153] Upgrade the maven-portal-bom to 3.6.1 version
|
||||||
|
|
10
pom.xml
10
pom.xml
|
@ -13,7 +13,7 @@
|
||||||
|
|
||||||
<groupId>org.gcube.portlets.widgets</groupId>
|
<groupId>org.gcube.portlets.widgets</groupId>
|
||||||
<artifactId>grsf-manage-widget</artifactId>
|
<artifactId>grsf-manage-widget</artifactId>
|
||||||
<version>1.5.0</version>
|
<version>1.7.0</version>
|
||||||
<name>gCube GRSF Manage widget</name>
|
<name>gCube GRSF Manage widget</name>
|
||||||
|
|
||||||
<scm>
|
<scm>
|
||||||
|
@ -24,12 +24,12 @@
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- Convenience property to set the GWT version -->
|
<!-- 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> -->
|
<!-- <webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory> -->
|
||||||
<distroDirectory>distro</distroDirectory>
|
<distroDirectory>distro</distroDirectory>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
<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>
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -38,7 +38,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.gcube.distribution</groupId>
|
<groupId>org.gcube.distribution</groupId>
|
||||||
<artifactId>maven-portal-bom</artifactId>
|
<artifactId>maven-portal-bom</artifactId>
|
||||||
<version>3.6.1</version>
|
<version>3.6.4</version>
|
||||||
<type>pom</type>
|
<type>pom</type>
|
||||||
<scope>import</scope>
|
<scope>import</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
@ -78,7 +78,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.gcube.data-catalogue</groupId>
|
<groupId>org.gcube.data-catalogue</groupId>
|
||||||
<artifactId>grsf-common-library</artifactId>
|
<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>
|
<scope>compile</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|
|
@ -673,7 +673,7 @@ public class ManageProductWidget extends Composite{
|
||||||
for(SimilarGRSFRecord sR: bean.getSimilarGrsfRecords()){
|
for(SimilarGRSFRecord sR: bean.getSimilarGrsfRecords()){
|
||||||
if(sR.isSuggestedMerge()){
|
if(sR.isSuggestedMerge()){
|
||||||
bean.setMergesInvolved(true);
|
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- GRSF Name '" + sR.getTitle() + "' ;";
|
||||||
report += "\n\t \t- Short Name '" + sR.getShortName() + "' ;";
|
report += "\n\t \t- Short Name '" + sR.getShortName() + "' ;";
|
||||||
report += "\n\t \t- URL '" + sR.getUrl() + "' ;";
|
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.
|
* Endpoint for sending update records information to GRSF KnowledgeBase.
|
||||||
|
*
|
||||||
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
* @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 long serialVersionUID = -4534905087994875893L;
|
||||||
private static final Log logger = LogFactoryUtil.getLog(GRSFNotificationService.class);
|
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.
|
* Instanciate the ckan util library. Since it needs the scope, we need to check
|
||||||
* Since it needs the scope, we need to check if it is null or not
|
* if it is null or not
|
||||||
* @param discoverScope if you want to the discover the utils library in this specified scope
|
*
|
||||||
|
* @param discoverScope if you want to the discover the utils library in this
|
||||||
|
* specified scope
|
||||||
* @return DataCatalogue object
|
* @return DataCatalogue object
|
||||||
* @throws Exception
|
* @throws Exception
|
||||||
*/
|
*/
|
||||||
public DataCatalogue getCatalogue(String discoverScope) throws Exception{
|
public DataCatalogue getCatalogue(String discoverScope) throws Exception {
|
||||||
String currentScope = Utils.getCurrentContext(getThreadLocalRequest(), true);
|
String currentScope = Utils.getCurrentContext(getThreadLocalRequest(), true);
|
||||||
DataCatalogue instance = null;
|
DataCatalogue instance = null;
|
||||||
try{
|
try {
|
||||||
String scopeInWhichDiscover = discoverScope != null && !discoverScope.isEmpty() ? discoverScope : currentScope;
|
String scopeInWhichDiscover = discoverScope != null && !discoverScope.isEmpty() ? discoverScope
|
||||||
|
: currentScope;
|
||||||
logger.debug("Discovering ckan utils library into scope " + scopeInWhichDiscover);
|
logger.debug("Discovering ckan utils library into scope " + scopeInWhichDiscover);
|
||||||
instance = DataCatalogueFactory.getFactory().getUtilsPerScope(scopeInWhichDiscover);
|
instance = DataCatalogueFactory.getFactory().getUtilsPerScope(scopeInWhichDiscover);
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Unable to retrieve ckan utils. Error was ", e);
|
logger.error("Unable to retrieve ckan utils. Error was ", e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
@ -74,241 +79,258 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ManageProductBean getProductBeanById(String productIdentifier, boolean requestForRevertingMerge) throws Exception {
|
public ManageProductBean getProductBeanById(String productIdentifier, boolean requestForRevertingMerge)
|
||||||
|
throws Exception {
|
||||||
|
|
||||||
ManageProductBean toReturn = null;
|
ManageProductBean toReturn = null;
|
||||||
|
|
||||||
// check into user's session first
|
// check into user's session first
|
||||||
HttpSession httpSession = getThreadLocalRequest().getSession();
|
HttpSession httpSession = getThreadLocalRequest().getSession();
|
||||||
|
|
||||||
// testing case...
|
// // testing case...
|
||||||
if(!Utils.isIntoPortal()){
|
// 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();
|
// it cannot be enabled in this case ...
|
||||||
toReturn.setCatalogueIdentifier(UUID.randomUUID().toString());
|
if (record == null)
|
||||||
List<ConnectedBean> connectTo = new ArrayList<>();
|
throw new Exception("Unable to retrieve information for the selected record, sorry");
|
||||||
// these are the records alread connected
|
else {
|
||||||
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"
|
logger.debug("Trying to fetch the record....");
|
||||||
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{
|
// check it is a grsf record (Source records have a different System Type)
|
||||||
|
Map<String, String> extrasAsMap = record.getExtrasAsHashMap();
|
||||||
|
|
||||||
String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
String systemType = extrasAsMap.get(Constants.SYSTEM_TYPE_CUSTOM_KEY);
|
||||||
DataCatalogue catalogue = getCatalogue(scopePerCurrentUrl);
|
if (systemType == null || systemType.isEmpty() || systemType.equals(Constants.SYSTEM_TYPE_LEGACY_RECORD))
|
||||||
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
throw new NoGRSFRecordException("This is not a GRSF Record");
|
||||||
CkanDataset record = catalogue.getDataset(productIdentifier,username);
|
|
||||||
|
|
||||||
// it cannot be enabled in this case ...
|
boolean isStock = record.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY)
|
||||||
if(record == null)
|
.contains(Product_Type.STOCK.getOrigName());
|
||||||
throw new Exception("Unable to retrieve information for the selected record, sorry");
|
|
||||||
else{
|
|
||||||
|
|
||||||
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)
|
// get extras as pairs
|
||||||
Map<String, String> extrasAsMap = record.getExtrasAsHashMap();
|
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 (status.equals(Status.To_be_Merged) && !requestForRevertingMerge)
|
||||||
if(systemType == null || systemType.isEmpty() || systemType.equals(Constants.SYSTEM_TYPE_FOR_SOURCES_VALUE))
|
throw new GRSFRecordAlreadyManagedStatusException(Status.To_be_Merged,
|
||||||
throw new NoGRSFRecordException("This is not a GRSF Record");
|
"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
|
boolean sdgFlag = false;
|
||||||
Map<String, String> fieldsNamespacesMap =
|
try {
|
||||||
Utils.getFieldToFieldNameSpaceMapping(httpSession, isStock ?
|
sdgFlag = extrasWithoutNamespaces.get(Constants.SDG_FLAG_CUSTOM_KEY).get(0).equalsIgnoreCase("true");
|
||||||
Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK : Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
|
} catch (Exception e) {
|
||||||
|
logger.warn("Unable to fetch sdg flag. Setting it to false", e);
|
||||||
|
}
|
||||||
|
|
||||||
// get extras as pairs
|
// Get similar GRSF records, if any (each of which should have name,
|
||||||
List<CkanPair> extrasAsPairs = record.getExtras();
|
// description, url and id(i.e semantic identifier))
|
||||||
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(extrasAsPairs, fieldsNamespacesMap);
|
List<String> similarGrsfRecordsAsStrings = extrasWithoutNamespaces
|
||||||
String catalogueIdentifier = record.getId();
|
.containsKey(Constants.SIMILAR_GRSF_RECORDS_CUSTOM_KEY)
|
||||||
String description = record.getNotes();
|
? extrasWithoutNamespaces.get(Constants.SIMILAR_GRSF_RECORDS_CUSTOM_KEY)
|
||||||
Status status = Status.fromString(extrasWithoutNamespaces.get(Constants.STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY).get(0));
|
: null;
|
||||||
|
|
||||||
if(status.equals(Status.To_be_Merged) && !requestForRevertingMerge)
|
List<SimilarGRSFRecord> similarRecords = new ArrayList<SimilarGRSFRecord>(0);
|
||||||
throw new GRSFRecordAlreadyManagedStatusException(Status.To_be_Merged, "The record is locked due to a merge request in progress!");
|
if (similarGrsfRecordsAsStrings != null && !similarGrsfRecordsAsStrings.isEmpty()) {
|
||||||
|
if (!similarGrsfRecordsAsStrings.get(0).equals(Constants.NO_SIMILAR_GRSF_RECORDS)) {
|
||||||
String uuidKB = extrasWithoutNamespaces.get(Constants.UUID_KB_CUSTOM_KEY).get(0);
|
for (String similarGRSFRecord : similarGrsfRecordsAsStrings) {
|
||||||
String grsfDomain = extrasWithoutNamespaces.get(Constants.DOMAIN_CUSTOM_KEY).get(0);
|
similarRecords.add(
|
||||||
String semanticId = extrasWithoutNamespaces.get(Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY).get(0);
|
Utils.similarGRSFRecordFromJson(similarGRSFRecord, catalogue, username, httpSession));
|
||||||
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));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
logger.debug("Returning item bean " + toReturn);
|
||||||
return toReturn;
|
return toReturn;
|
||||||
|
@ -316,19 +338,20 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isAdminUser() {
|
public boolean isAdminUser() {
|
||||||
try{
|
try {
|
||||||
Boolean inSession = (Boolean)getThreadLocalRequest().getSession().getAttribute(Constants.GRSF_ADMIN_SESSION_KEY);
|
Boolean inSession = (Boolean) getThreadLocalRequest().getSession()
|
||||||
if(inSession != null)
|
.getAttribute(Constants.GRSF_ADMIN_SESSION_KEY);
|
||||||
|
if (inSession != null)
|
||||||
return inSession;
|
return inSession;
|
||||||
else{
|
else {
|
||||||
|
|
||||||
boolean toSetInSession = false;
|
boolean toSetInSession = false;
|
||||||
if(!Utils.isIntoPortal()){
|
if (!Utils.isIntoPortal()) {
|
||||||
toSetInSession = true;
|
toSetInSession = true;
|
||||||
}else{
|
} else {
|
||||||
PortalContext pContext = PortalContext.getConfiguration();
|
PortalContext pContext = PortalContext.getConfiguration();
|
||||||
RoleManager roleManager = new LiferayRoleManager();
|
RoleManager roleManager = new LiferayRoleManager();
|
||||||
String username = pContext.getCurrentUser(getThreadLocalRequest()).getUsername();
|
String username = pContext.getCurrentUser(getThreadLocalRequest()).getUsername();
|
||||||
long userId = pContext.getCurrentUser(getThreadLocalRequest()).getUserId();
|
long userId = pContext.getCurrentUser(getThreadLocalRequest()).getUserId();
|
||||||
long groupId = pContext.getCurrentGroupId(getThreadLocalRequest());
|
long groupId = pContext.getCurrentGroupId(getThreadLocalRequest());
|
||||||
List<GCubeTeam> teamRolesByUser = roleManager.listTeamsByUserAndGroup(userId, groupId);
|
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);
|
getThreadLocalRequest().getSession().setAttribute(Constants.GRSF_ADMIN_SESSION_KEY, toSetInSession);
|
||||||
return toSetInSession;
|
return toSetInSession;
|
||||||
}
|
}
|
||||||
}catch(Exception 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);
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@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");
|
logger.info("Creating notification for the bean " + bean + " to send to the knowledge base");
|
||||||
if(!Utils.isIntoPortal()){
|
if (!Utils.isIntoPortal()) {
|
||||||
Thread.sleep(2500);
|
Thread.sleep(2500);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try{
|
try {
|
||||||
|
|
||||||
String context = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
String context = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
||||||
String token = SecurityTokenProvider.instance.get();
|
String token = SecurityTokenProvider.instance.get();
|
||||||
|
@ -360,10 +384,11 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
||||||
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
||||||
|
|
||||||
// check if the base url of the service is in session
|
// 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();
|
HttpServletRequest threadRequest = getThreadLocalRequest();
|
||||||
String baseUrl = (String)threadRequest.getSession().getAttribute(keyPerContext);
|
String baseUrl = (String) threadRequest.getSession().getAttribute(keyPerContext);
|
||||||
if(baseUrl == null || baseUrl.isEmpty()){
|
if (baseUrl == null || baseUrl.isEmpty()) {
|
||||||
baseUrl = GRSFUpdaterServiceClient.discoverEndPoint(context);
|
baseUrl = GRSFUpdaterServiceClient.discoverEndPoint(context);
|
||||||
threadRequest.getSession().setAttribute(keyPerContext, baseUrl);
|
threadRequest.getSession().setAttribute(keyPerContext, baseUrl);
|
||||||
}
|
}
|
||||||
|
@ -375,7 +400,7 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
||||||
Utils.updateRecord(baseUrl, bean, catalogue, username, administratorFullName, threadRequest,
|
Utils.updateRecord(baseUrl, bean, catalogue, username, administratorFullName, threadRequest,
|
||||||
PortalContext.getConfiguration().getCurrentGroupId(threadRequest), context, token);
|
PortalContext.getConfiguration().getCurrentGroupId(threadRequest), context, token);
|
||||||
|
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Unable to update the product", e);
|
logger.error("Unable to update the product", e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
@ -384,13 +409,13 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
||||||
@Override
|
@Override
|
||||||
public RevertableOperationInfo validateRevertOperation(String encryptedUrl) throws Exception {
|
public RevertableOperationInfo validateRevertOperation(String encryptedUrl) throws Exception {
|
||||||
|
|
||||||
if(!Utils.isIntoPortal()){
|
if (!Utils.isIntoPortal()) {
|
||||||
Thread.sleep(2000);
|
Thread.sleep(2000);
|
||||||
|
|
||||||
// random result
|
// random result
|
||||||
boolean throwException = Math.random() > 0.5;
|
boolean throwException = Math.random() > 0.5;
|
||||||
|
|
||||||
if(throwException)
|
if (throwException)
|
||||||
throw new Exception("Unable to parse the inserted url");
|
throw new Exception("Unable to parse the inserted url");
|
||||||
|
|
||||||
String baseUrl = "url of the record here";
|
String baseUrl = "url of the record here";
|
||||||
|
@ -399,15 +424,15 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
String adminInUrl = "costantino.perciante";
|
String adminInUrl = "costantino.perciante";
|
||||||
String adminInUrlFullName = "Costantino Perciante";
|
String adminInUrlFullName = "Costantino Perciante";
|
||||||
long timestamp = System.currentTimeMillis() - 1000 * (long)(Math.random() * 10 * 60 * 60);
|
long timestamp = System.currentTimeMillis() - 1000 * (long) (Math.random() * 10 * 60 * 60);
|
||||||
return new RevertableOperationInfo(
|
return new RevertableOperationInfo(baseUrl, fullName, usernameCurrent, uuid, adminInUrlFullName, adminInUrl,
|
||||||
baseUrl, fullName, usernameCurrent, uuid, adminInUrlFullName, adminInUrl, timestamp, RevertableOperations.MERGE);
|
timestamp, RevertableOperations.MERGE);
|
||||||
}
|
}
|
||||||
|
|
||||||
PortalContext pContext = PortalContext.getConfiguration();
|
PortalContext pContext = PortalContext.getConfiguration();
|
||||||
String context = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
String context = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
||||||
RoleManager roleManager = new LiferayRoleManager();
|
RoleManager roleManager = new LiferayRoleManager();
|
||||||
GCubeUser user = pContext.getCurrentUser(getThreadLocalRequest());
|
GCubeUser user = pContext.getCurrentUser(getThreadLocalRequest());
|
||||||
String username = user.getUsername();
|
String username = user.getUsername();
|
||||||
String fullName = user.getFullname();
|
String fullName = user.getFullname();
|
||||||
long userId = pContext.getCurrentUser(getThreadLocalRequest()).getUserId();
|
long userId = pContext.getCurrentUser(getThreadLocalRequest()).getUserId();
|
||||||
|
@ -417,21 +442,25 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
||||||
boolean isEditor = isEditor(username, teamRolesByUser);
|
boolean isEditor = isEditor(username, teamRolesByUser);
|
||||||
boolean isReviewer = isReviewer(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!");
|
throw new Exception("You are not allowed to perform this operation. You must be an editor or a reviewer!");
|
||||||
|
|
||||||
// decrypt the url
|
// decrypt the url
|
||||||
RevertOperationUrl decryptedUrl = new RevertOperationUrl(encryptedUrl);
|
RevertOperationUrl decryptedUrl = new RevertOperationUrl(encryptedUrl);
|
||||||
String userNameadminInUrl = decryptedUrl.getAdmin(); // this is the username
|
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();
|
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)
|
// we need to check the timestamp (it has 24h validity)
|
||||||
boolean isValidTimestamp = decryptedUrl.isTimestampValid();
|
boolean isValidTimestamp = decryptedUrl.isTimestampValid();
|
||||||
|
|
||||||
if(!isValidTimestamp)
|
if (!isValidTimestamp)
|
||||||
throw new Exception("This operation can no longer be reverted (link expired)!");
|
throw new Exception("This operation can no longer be reverted (link expired)!");
|
||||||
|
|
||||||
DataCatalogue catalogue = getCatalogue(context);
|
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);
|
String currentStatus = extras.get(Constants.STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY);
|
||||||
|
|
||||||
// check current record status
|
// check current record status
|
||||||
if(!currentStatus.equals(Status.To_be_Merged.getOrigName()))
|
if (!currentStatus.equals(Status.To_be_Merged.getOrigName()))
|
||||||
throw new Exception("Record '" + dataset.getTitle() + "' (" + recordUrl + ") is no longer involved in a merge operation!");
|
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)
|
// check if it is a reviewer, than he can do what he wants (no matter the admin)
|
||||||
if(isReviewer){
|
if (isReviewer) {
|
||||||
return new RevertableOperationInfo(recordUrl,
|
return new RevertableOperationInfo(recordUrl, fullName, username, uuid, fullNameadminInUrl,
|
||||||
fullName, username, uuid, fullNameadminInUrl, userNameadminInUrl, decryptedUrl.getTimestamp(), decryptedUrl.getOperation());
|
userNameadminInUrl, decryptedUrl.getTimestamp(), decryptedUrl.getOperation());
|
||||||
}else{
|
} else {
|
||||||
|
|
||||||
if(!username.equals(userNameadminInUrl))
|
if (!username.equals(userNameadminInUrl))
|
||||||
throw new Exception("You are not the editor allowed to perform this operation!");
|
throw new Exception("You are not the editor allowed to perform this operation!");
|
||||||
else
|
else
|
||||||
return new RevertableOperationInfo(recordUrl,
|
return new RevertableOperationInfo(recordUrl, fullName, username, uuid, fullNameadminInUrl,
|
||||||
fullName, username, uuid, fullNameadminInUrl, userNameadminInUrl, decryptedUrl.getTimestamp(), decryptedUrl.getOperation());
|
userNameadminInUrl, decryptedUrl.getTimestamp(), decryptedUrl.getOperation());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Boolean performRevertOperation(RevertableOperationInfo rInfo)
|
public Boolean performRevertOperation(RevertableOperationInfo rInfo) throws Exception {
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
if(!Utils.isIntoPortal()){
|
if (!Utils.isIntoPortal()) {
|
||||||
// random result
|
// random result
|
||||||
boolean toReturn = Math.random() > 0.5;
|
boolean toReturn = Math.random() > 0.5;
|
||||||
|
|
||||||
if(toReturn){
|
if (toReturn) {
|
||||||
|
|
||||||
boolean throwException = Math.random() > 0.5;
|
boolean throwException = Math.random() > 0.5;
|
||||||
if(throwException)
|
if (throwException)
|
||||||
throw new Exception("Unable to execute request for XYZ");
|
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 context = Utils.getScopeFromClientUrl(threadRequest);
|
||||||
String token = SecurityTokenProvider.instance.get();
|
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 keyPerContext = CatalogueUtilMethods.concatenateSessionKeyScope(Constants.GRSF_UPDATER_SERVICE,
|
||||||
String baseUrl = (String)getThreadLocalRequest().getSession().getAttribute(keyPerContext);
|
context);
|
||||||
if(baseUrl == null || baseUrl.isEmpty()){
|
String baseUrl = (String) getThreadLocalRequest().getSession().getAttribute(keyPerContext);
|
||||||
|
if (baseUrl == null || baseUrl.isEmpty()) {
|
||||||
baseUrl = GRSFUpdaterServiceClient.discoverEndPoint(context);
|
baseUrl = GRSFUpdaterServiceClient.discoverEndPoint(context);
|
||||||
getThreadLocalRequest().getSession().setAttribute(keyPerContext, baseUrl);
|
getThreadLocalRequest().getSession().setAttribute(keyPerContext, baseUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(baseUrl == null || baseUrl.isEmpty())
|
if (baseUrl == null || baseUrl.isEmpty())
|
||||||
throw new Exception("Unable to discover grsf-updater service!");
|
throw new Exception("Unable to discover grsf-updater service!");
|
||||||
|
|
||||||
Utils.revertOperation(httpClient, baseUrl, threadRequest, rInfo, token, context,
|
Utils.revertOperation(httpClient, baseUrl, threadRequest, rInfo, token, context,
|
||||||
PortalContext.getConfiguration().getCurrentGroupId(threadRequest));
|
PortalContext.getConfiguration().getCurrentGroupId(threadRequest));
|
||||||
|
|
||||||
}
|
} catch (Exception e) {
|
||||||
catch(Exception e){
|
|
||||||
logger.error("Unable to revert operation ", e);
|
logger.error("Unable to revert operation ", e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
@ -506,14 +535,15 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if the current user is an editor
|
* Check if the current user is an editor
|
||||||
|
*
|
||||||
* @param username
|
* @param username
|
||||||
* @param teamRoles
|
* @param teamRoles
|
||||||
* @return true if he/she is an editor, false otherwise
|
* @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) {
|
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");
|
logger.info("User " + username + " is allowed to modify GRSF records as editor");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -523,14 +553,15 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if the current user is a reviewer
|
* Check if the current user is a reviewer
|
||||||
|
*
|
||||||
* @param username
|
* @param username
|
||||||
* @param teamRoles
|
* @param teamRoles
|
||||||
* @return true if he/she is an reviewer, false otherwise
|
* @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) {
|
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");
|
logger.info("User " + username + " is allowed to modify GRSF records as reviewer");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -539,55 +570,54 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String checkIdentifierExists(String id)
|
public String checkIdentifierExists(String id) throws Exception {
|
||||||
throws Exception {
|
|
||||||
String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
||||||
DataCatalogue catalogue = getCatalogue(scopePerCurrentUrl);
|
DataCatalogue catalogue = getCatalogue(scopePerCurrentUrl);
|
||||||
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
||||||
CkanDataset dataset = catalogue.getDataset(id,username);
|
CkanDataset dataset = catalogue.getDataset(id, username);
|
||||||
if(dataset == null)
|
if (dataset == null)
|
||||||
throw new Exception("A GRSF record with id " + id + " doesn't exist");
|
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");
|
throw new Exception("The suggested record is not a GRSF record");
|
||||||
|
|
||||||
return dataset.getExtrasAsHashMap().get(Constants.ITEM_URL_FIELD);
|
return dataset.getExtrasAsHashMap().get(Constants.ITEM_URL_FIELD);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String checkIdentifierExistsInDomain(String id,
|
public String checkIdentifierExistsInDomain(String id, String acceptedDomain) throws Exception {
|
||||||
String acceptedDomain) throws Exception {
|
|
||||||
|
|
||||||
if(!Utils.isIntoPortal()){
|
// if (!Utils.isIntoPortal()) {
|
||||||
boolean throwException = Math.random() > 0.5;
|
// boolean throwException = Math.random() > 0.5;
|
||||||
|
//
|
||||||
// simulate some delay...
|
// // simulate some delay...
|
||||||
Thread.sleep(2500);
|
// Thread.sleep(2500);
|
||||||
|
//
|
||||||
if(throwException)
|
// if (throwException)
|
||||||
throw new Exception("The suggested record is not a GRSF record");
|
// throw new Exception("The suggested record is not a GRSF record");
|
||||||
|
//
|
||||||
return "http://data.d4science.org/catalogue/grsf_admin/" + id;
|
// return "http://data.d4science.org/catalogue/grsf_admin/" + id;
|
||||||
}
|
// }
|
||||||
|
|
||||||
String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
||||||
DataCatalogue catalogue = getCatalogue(scopePerCurrentUrl);
|
DataCatalogue catalogue = getCatalogue(scopePerCurrentUrl);
|
||||||
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
||||||
CkanDataset dataset = catalogue.getDataset(id, username);
|
CkanDataset dataset = catalogue.getDataset(id, username);
|
||||||
|
|
||||||
if(dataset == null)
|
if (dataset == null)
|
||||||
throw new Exception("A record with id " + id + " doesn't exist");
|
throw new Exception("A record with id " + id + " doesn't exist");
|
||||||
|
|
||||||
Map<String, String> extras = dataset.getExtrasAsHashMap();
|
Map<String, String> extras = dataset.getExtrasAsHashMap();
|
||||||
String systemType = extras.get(Constants.SYSTEM_TYPE_CUSTOM_KEY);
|
String systemType = extras.get(Constants.SYSTEM_TYPE_CUSTOM_KEY);
|
||||||
String domain = extras.get(Constants.DOMAIN_CUSTOM_KEY);
|
String domain = extras.get(Constants.DOMAIN_CUSTOM_KEY);
|
||||||
String url = extras.get(Constants.ITEM_URL_FIELD);
|
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!");
|
throw new Exception("This record is not a GRSF record!");
|
||||||
|
|
||||||
if(!acceptedDomain.equalsIgnoreCase(domain))
|
if (!acceptedDomain.equalsIgnoreCase(domain))
|
||||||
throw new Exception("You are suggesting a " + domain + " record instead of a " + acceptedDomain + " record!");
|
throw new Exception(
|
||||||
|
"You are suggesting a " + domain + " record instead of a " + acceptedDomain + " record!");
|
||||||
|
|
||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
|
@ -41,9 +41,10 @@ import org.json.simple.JSONObject;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
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)
|
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
||||||
*/
|
*/
|
||||||
public class SocialCommunications {
|
public class SocialCommunications {
|
||||||
|
@ -64,9 +65,10 @@ public class SocialCommunications {
|
||||||
private static final String MEDIATYPE_JSON = "application/json";
|
private static final String MEDIATYPE_JSON = "application/json";
|
||||||
|
|
||||||
// for writing a post in the GRSF admin context
|
// 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,"
|
private static final String POST_MESSAGE = "Dear members,"
|
||||||
+ "\nThe record 'PRODUCT_TITLE' has been just updated by USER_FULLNAME."
|
+ "\nThe record 'PRODUCT_TITLE' has been just updated by USER_FULLNAME."
|
||||||
+ "\nYou can inspect it here: LINK_RECORD.";
|
+ "\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>";
|
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.";
|
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
|
// 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.";
|
+ "<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,"
|
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
|
// post on revert
|
||||||
private static final String POST_ON_REVERT = "Dear members,"
|
private static final String POST_ON_REVERT = "Dear members,"
|
||||||
|
@ -99,39 +101,42 @@ public class SocialCommunications {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param httpServletRequest
|
* @param httpServletRequest
|
||||||
* @param context
|
* @param context
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public static String getBaseUrlSocialService(HttpServletRequest httpServletRequest){
|
public static String getBaseUrlSocialService(HttpServletRequest httpServletRequest) {
|
||||||
|
|
||||||
String context = ScopeProvider.instance.get();
|
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);
|
String basePath = (String) httpServletRequest.getSession().getAttribute(keyPerContext);
|
||||||
|
|
||||||
if(basePath == null){
|
if (basePath == null) {
|
||||||
try{
|
try {
|
||||||
|
|
||||||
SimpleQuery query = queryFor(GCoreEndpoint.class);
|
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("$resource/Profile/DeploymentData/Status/text() eq 'ready'");
|
||||||
query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'",serviceName));
|
query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'", serviceName));
|
||||||
query.setResult("$resource/Profile/AccessPoint/RunningInstanceInterfaces//Endpoint[@EntryName/string() eq \""+resource+"\"]/text()");
|
query.setResult(
|
||||||
|
"$resource/Profile/AccessPoint/RunningInstanceInterfaces//Endpoint[@EntryName/string() eq \""
|
||||||
|
+ resource + "\"]/text()");
|
||||||
|
|
||||||
DiscoveryClient<String> client = client();
|
DiscoveryClient<String> client = client();
|
||||||
List<String> endpoints = client.submit(query);
|
List<String> endpoints = client.submit(query);
|
||||||
if (endpoints == null || endpoints.isEmpty())
|
if (endpoints == null || endpoints.isEmpty())
|
||||||
throw new Exception("Cannot retrieve the GCoreEndpoint serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+context);
|
throw new Exception("Cannot retrieve the GCoreEndpoint serviceName: " + serviceName
|
||||||
|
+ ", serviceClass: " + serviceClass + ", in scope: " + context);
|
||||||
|
|
||||||
basePath = endpoints.get(0);
|
basePath = endpoints.get(0);
|
||||||
if(basePath==null)
|
if (basePath == null)
|
||||||
throw new Exception("Endpoint:"+resource+", is null for serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+context);
|
throw new Exception("Endpoint:" + resource + ", is null for serviceName: " + serviceName
|
||||||
|
+ ", serviceClass: " + serviceClass + ", in scope: " + context);
|
||||||
|
|
||||||
httpServletRequest.getSession().setAttribute(keyPerContext, basePath);
|
httpServletRequest.getSession().setAttribute(keyPerContext, basePath);
|
||||||
|
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Unable to retrieve such service endpoint information!", 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.
|
* Require a proper application token for writing a post and send messages.
|
||||||
|
*
|
||||||
* @return
|
* @return
|
||||||
* @throws Exception
|
* @throws Exception
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static String requireApplicationToken(String serviceUrl) throws Exception{
|
private static String requireApplicationToken(String serviceUrl) throws Exception {
|
||||||
|
|
||||||
String currentScope = ScopeProvider.instance.get();
|
String currentScope = ScopeProvider.instance.get();
|
||||||
String tokenUser = SecurityTokenProvider.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;
|
String basePath = serviceUrl;
|
||||||
|
|
||||||
if(basePath == null){
|
if (basePath == null) {
|
||||||
|
|
||||||
logger.error("Unable to write a post because there is no social networking service available");
|
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");
|
throw new Exception("Unable to discover the social networking service");
|
||||||
|
|
||||||
}else{
|
} else {
|
||||||
|
|
||||||
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
|
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
|
// 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();
|
JSONObject requestToken = new JSONObject();
|
||||||
requestToken.put("app_id", APPLICATION_ID_CATALOGUE_MANAGER);
|
requestToken.put("app_id", APPLICATION_ID_CATALOGUE_MANAGER);
|
||||||
StringEntity input = new StringEntity(requestToken.toJSONString());
|
StringEntity input = new StringEntity(requestToken.toJSONString());
|
||||||
|
@ -178,21 +187,21 @@ public class SocialCommunications {
|
||||||
if (response.getStatusLine().getStatusCode() != 201) {
|
if (response.getStatusLine().getStatusCode() != 201) {
|
||||||
throw new RuntimeException("Failed to retrieve application token : HTTP error code : "
|
throw new RuntimeException("Failed to retrieve application token : HTTP error code : "
|
||||||
+ response.getStatusLine().getStatusCode());
|
+ response.getStatusLine().getStatusCode());
|
||||||
}else{
|
} else {
|
||||||
|
|
||||||
Map<String, Object> mapResponseGeneratedToken = getResponseEntityAsJSON(response);
|
Map<String, Object> mapResponseGeneratedToken = getResponseEntityAsJSON(response);
|
||||||
boolean successGeneratedToken = (boolean)mapResponseGeneratedToken.get("success");
|
boolean successGeneratedToken = (boolean) mapResponseGeneratedToken.get("success");
|
||||||
if(!successGeneratedToken){
|
if (!successGeneratedToken) {
|
||||||
|
|
||||||
throw new RuntimeException("Failed to generate the token for the application!"
|
throw new RuntimeException("Failed to generate the token for the application!"
|
||||||
+ " Error message is " + mapResponseGeneratedToken.get("message"));
|
+ " Error message is " + mapResponseGeneratedToken.get("message"));
|
||||||
|
|
||||||
}else{
|
} else {
|
||||||
return (String)mapResponseGeneratedToken.get("result");
|
return (String) mapResponseGeneratedToken.get("result");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Failed to create a post", e);
|
logger.error("Failed to create a post", e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
@ -201,63 +210,76 @@ public class SocialCommunications {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Notify the users about the required changes.
|
* Notify the users about the required changes.
|
||||||
|
*
|
||||||
* @param bean
|
* @param bean
|
||||||
* @param url
|
* @param url
|
||||||
* @param username
|
* @param username
|
||||||
* @param fullName
|
* @param fullName
|
||||||
* @param hashtags
|
* @param hashtags
|
||||||
* @param enablePostNotification
|
* @param enablePostNotification
|
||||||
* @throws Exception
|
* @throws Exception
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@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
|
// discover service endpoint for the social networking library
|
||||||
String currentScope = ScopeProvider.instance.get();
|
String currentScope = ScopeProvider.instance.get();
|
||||||
String tokenUser = SecurityTokenProvider.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;
|
String basePath = serviceUrl;
|
||||||
|
|
||||||
if(basePath == null){
|
if (basePath == null) {
|
||||||
|
|
||||||
logger.error("Unable to write a post because there is no social networking service available");
|
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");
|
throw new Exception("Unable to discover the social networking service");
|
||||||
|
|
||||||
}else{
|
} else {
|
||||||
|
|
||||||
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
|
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
|
// require url
|
||||||
String applicationToken = requireApplicationToken(serviceUrl);
|
String applicationToken = requireApplicationToken(serviceUrl);
|
||||||
|
|
||||||
//see Feature #17576 updated by Francesco
|
// 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 + "?"+
|
* final String profilePageURL = GCubePortalConstants.PREFIX_GROUP_URL +
|
||||||
Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
* extractOrgFriendlyURL(userCurrentUrl) +
|
||||||
Base64.getEncoder().encodeToString(rInfo.getUserNameCurrentAdmin().getBytes())+"\">"+rInfo.getFullNameCurrentAdmin()+
|
* GCubePortalConstants.USER_PROFILE_FRIENDLY_URL; String
|
||||||
"</a> ";
|
* userFullNameHighlightedCurrent = "<a class=\"link\" href=\"" + profilePageURL
|
||||||
*/
|
* + "?"+ Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
||||||
|
* Base64.getEncoder().encodeToString(rInfo.getUserNameCurrentAdmin().getBytes()
|
||||||
String userFullNameHighlightedCurrent = "@"+rInfo.getUserNameCurrentAdmin();
|
* )+"\">"+rInfo.getFullNameCurrentAdmin()+ "</a> ";
|
||||||
|
*/
|
||||||
|
|
||||||
/*String userFullNameHighlightedOriginal = "<a class=\"link\" href=\"" + profilePageURL + "?"+
|
String userFullNameHighlightedCurrent = "@" + rInfo.getUserNameCurrentAdmin();
|
||||||
Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
|
||||||
Base64.getEncoder().encodeToString(rInfo.getUserNameOriginalAdmin().getBytes())+"\">"+rInfo.getFullNameOriginalAdmin()+
|
/*
|
||||||
"</a> ";*/
|
* String userFullNameHighlightedOriginal = "<a class=\"link\" href=\"" +
|
||||||
|
* profilePageURL + "?"+
|
||||||
String userFullNameHighlightedOriginal = "@"+rInfo.getUserNameOriginalAdmin();
|
* Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
||||||
|
* Base64.getEncoder().encodeToString(rInfo.getUserNameOriginalAdmin().getBytes(
|
||||||
|
* ))+"\">"+rInfo.getFullNameOriginalAdmin()+ "</a> ";
|
||||||
|
*/
|
||||||
|
|
||||||
|
String userFullNameHighlightedOriginal = "@" + rInfo.getUserNameOriginalAdmin();
|
||||||
// replace
|
// 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
|
// add hashtag
|
||||||
message +="\n\n";
|
message += "\n\n";
|
||||||
message += " #" + HashTagsOnUpdate.REVERTED_MERGE.getString();
|
message += " #" + HashTagsOnUpdate.REVERTED_MERGE.getString();
|
||||||
|
|
||||||
logger.info("The post that is going to be written is -> " + message);
|
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();
|
JSONObject object = new JSONObject();
|
||||||
object.put("text", message);
|
object.put("text", message);
|
||||||
object.put("enable_notification", enablePostNotification);
|
object.put("enable_notification", enablePostNotification);
|
||||||
|
@ -272,7 +294,7 @@ public class SocialCommunications {
|
||||||
throw new RuntimeException("Failed to write application post : HTTP error code : "
|
throw new RuntimeException("Failed to write application post : HTTP error code : "
|
||||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||||
|
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Failed to create a post", e);
|
logger.error("Failed to create a post", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -280,69 +302,77 @@ public class SocialCommunications {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Notify the users about the required changes.
|
* Notify the users about the required changes.
|
||||||
|
*
|
||||||
* @param bean
|
* @param bean
|
||||||
* @param url
|
* @param url
|
||||||
* @param username
|
* @param username
|
||||||
* @param fullName
|
* @param fullName
|
||||||
* @param hashtags
|
* @param hashtags
|
||||||
* @param enablePostNotification
|
* @param enablePostNotification
|
||||||
* @throws Exception
|
* @throws Exception
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@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
|
// discover service endpoint for the social networking library
|
||||||
String currentScope = ScopeProvider.instance.get();
|
String currentScope = ScopeProvider.instance.get();
|
||||||
String tokenUser = SecurityTokenProvider.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;
|
String basePath = serviceUrl;
|
||||||
|
|
||||||
if(basePath == null){
|
if (basePath == null) {
|
||||||
|
|
||||||
logger.error("Unable to write a post because there is no social networking service available");
|
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");
|
throw new Exception("Unable to discover the social networking service");
|
||||||
|
|
||||||
}else{
|
} else {
|
||||||
|
|
||||||
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
|
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
|
// require url
|
||||||
String applicationToken = requireApplicationToken(serviceUrl);
|
String applicationToken = requireApplicationToken(serviceUrl);
|
||||||
|
|
||||||
//see Feature #17576 Updated by Francesco
|
// 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 + "?"+
|
* final String profilePageURL = GCubePortalConstants.PREFIX_GROUP_URL +
|
||||||
Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
* extractOrgFriendlyURL(userCurrentUrl) +
|
||||||
Base64.getEncoder().encodeToString(username.getBytes())+"\">"+fullName+
|
* GCubePortalConstants.USER_PROFILE_FRIENDLY_URL; String
|
||||||
"</a> ";
|
* userFullNameHighlighted = "<a class=\"link\" href=\"" + profilePageURL + "?"+
|
||||||
*/
|
* Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
||||||
|
* Base64.getEncoder().encodeToString(username.getBytes())+"\">"+fullName+
|
||||||
String userFullNameHighlighted = "@"+username;
|
* "</a> ";
|
||||||
|
*/
|
||||||
|
|
||||||
|
String userFullNameHighlighted = "@" + username;
|
||||||
|
|
||||||
// replace
|
// replace
|
||||||
String message = POST_MESSAGE.replace("PRODUCT_TITLE", bean.getTitle()).replace("LINK_RECORD", bean.getUrl()).
|
String message = POST_MESSAGE.replace("PRODUCT_TITLE", bean.getTitle())
|
||||||
replace("USER_FULLNAME", userFullNameHighlighted);
|
.replace("LINK_RECORD", bean.getUrl()).replace("USER_FULLNAME", userFullNameHighlighted);
|
||||||
|
|
||||||
if(bean.getReport() != null && !bean.getReport().isEmpty())
|
if (bean.getReport() != null && !bean.getReport().isEmpty())
|
||||||
message += ADD_REPORT.replace("REPORT_UPDATE", bean.getReport());
|
message += ADD_REPORT.replace("<br>", "").replace("REPORT_UPDATE", bean.getReport());
|
||||||
|
|
||||||
Set<String> hashtags = bean.getHashtags();
|
Set<String> hashtags = bean.getHashtags();
|
||||||
logger.debug("Hashtags are " + hashtags);
|
logger.debug("Hashtags are " + hashtags);
|
||||||
if(hashtags != null && !hashtags.isEmpty()){
|
if (hashtags != null && !hashtags.isEmpty()) {
|
||||||
message +="\n\n";
|
message += "\n\n";
|
||||||
for (String hashtag : hashtags) {
|
for (String hashtag : hashtags) {
|
||||||
message += " #" + hashtag;
|
message += " #" + hashtag;
|
||||||
}
|
}
|
||||||
//Added by Francesco Mangiacrapa see at Feature #16312
|
// Added by Francesco Mangiacrapa see at Feature #16312
|
||||||
String normalizedFullName = fullName.trim().replace(" ", "_");
|
String normalizedFullName = fullName.trim().replace(" ", "_");
|
||||||
message += " #" + normalizedFullName;
|
message += " #" + normalizedFullName;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info("The post that is going to be written is -> " + message);
|
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();
|
JSONObject object = new JSONObject();
|
||||||
object.put("text", message);
|
object.put("text", message);
|
||||||
object.put("enable_notification", enablePostNotification);
|
object.put("enable_notification", enablePostNotification);
|
||||||
|
@ -356,7 +386,7 @@ public class SocialCommunications {
|
||||||
if (response.getStatusLine().getStatusCode() != 201)
|
if (response.getStatusLine().getStatusCode() != 201)
|
||||||
throw new RuntimeException("Failed to write application post : HTTP error code : "
|
throw new RuntimeException("Failed to write application post : HTTP error code : "
|
||||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Failed to create a post", e);
|
logger.error("Failed to create a post", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -372,31 +402,26 @@ public class SocialCommunications {
|
||||||
} else {
|
} else {
|
||||||
friendlyURL = friendlyURL.split("\\?")[0].split("\\#")[0];
|
friendlyURL = friendlyURL.split("\\?")[0].split("\\#")[0];
|
||||||
}
|
}
|
||||||
return "/"+friendlyURL;
|
return "/" + friendlyURL;
|
||||||
}
|
}
|
||||||
return null;
|
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 bean
|
||||||
* @param catalogue
|
* @param catalogue
|
||||||
* @param username
|
* @param username
|
||||||
* @param fullName
|
* @param fullName
|
||||||
* @param isMergeInvolved
|
* @param isMergeInvolved
|
||||||
* @param httpSession
|
* @param httpSession
|
||||||
* @throws Exceptio
|
* @throws Exceptio
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public static void sendEmailAdministrators(
|
public static void sendEmailAdministrators(String serviceUrl, ManageProductBean bean, DataCatalogue catalogue,
|
||||||
String serviceUrl,
|
String username, String fullName, long groupId, String clientCurrenturl, boolean isMergeInvolved)
|
||||||
ManageProductBean bean,
|
throws Exception {
|
||||||
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
|
// get the list of GRSF Reviewers to alert them as well
|
||||||
RoleManager roleManager = new LiferayRoleManager();
|
RoleManager roleManager = new LiferayRoleManager();
|
||||||
|
@ -406,54 +431,56 @@ public class SocialCommunications {
|
||||||
|
|
||||||
List<String> reviewers = new ArrayList<String>(reviewersGcube.size());
|
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 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());
|
reviewers.add(gU.getUsername());
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info("List of " + Constants.GRSF_CATALOGUE_REVIEWER_ROLE + " is " + reviewers);
|
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;
|
RevertableOperations operation = RevertableOperations.MERGE;
|
||||||
|
|
||||||
// discover service endpoint for the social networking library
|
// discover service endpoint for the social networking library
|
||||||
String currentScope = ScopeProvider.instance.get();
|
String currentScope = ScopeProvider.instance.get();
|
||||||
String tokenUser = SecurityTokenProvider.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;
|
String basePath = serviceUrl;
|
||||||
|
|
||||||
if(basePath == null){
|
if (basePath == null) {
|
||||||
|
|
||||||
logger.error("Unable to write a post because there is no social networking service available");
|
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");
|
throw new Exception("Unable to discover the social networking service");
|
||||||
|
|
||||||
}else{
|
} else {
|
||||||
|
|
||||||
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
|
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
|
/// require url
|
||||||
String applicationToken = requireApplicationToken(serviceUrl);
|
String applicationToken = requireApplicationToken(serviceUrl);
|
||||||
|
|
||||||
String revertUrl = "";
|
String revertUrl = "";
|
||||||
if(isMergeInvolved)
|
if (isMergeInvolved)
|
||||||
revertUrl = getEncodedUrlManage(operation, username, System.currentTimeMillis(), bean.getKnowledgeBaseId(), clientCurrenturl);
|
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 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";
|
String subject = "Update request on GRSF Record";
|
||||||
|
|
||||||
// append report
|
// append report
|
||||||
if(bean.getReport() != null){
|
if (bean.getReport() != null) {
|
||||||
messageToEditor += ADD_REPORT.replace("REPORT_UPDATE", bean.getReport());
|
messageToEditor += ADD_REPORT.replace("REPORT_UPDATE", bean.getReport());
|
||||||
messageToReviewer += 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);
|
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 : "
|
logger.error("Failed to send message to editor : HTTP error code : "
|
||||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||||
}
|
}
|
||||||
|
@ -494,7 +521,7 @@ public class SocialCommunications {
|
||||||
reqMessage.put("subject", subject);
|
reqMessage.put("subject", subject);
|
||||||
reqMessage.put("body", messageToReviewer);
|
reqMessage.put("body", messageToReviewer);
|
||||||
recipients = new JSONArray();
|
recipients = new JSONArray();
|
||||||
for(String reviewer: reviewers){
|
for (String reviewer : reviewers) {
|
||||||
JSONObject recip = new JSONObject();
|
JSONObject recip = new JSONObject();
|
||||||
recip.put("id", reviewer);
|
recip.put("id", reviewer);
|
||||||
recipients.add(recip);
|
recipients.add(recip);
|
||||||
|
@ -509,12 +536,12 @@ public class SocialCommunications {
|
||||||
response = client.execute(postRequest);
|
response = client.execute(postRequest);
|
||||||
mapResponseWritePost = getResponseEntityAsJSON(response);
|
mapResponseWritePost = getResponseEntityAsJSON(response);
|
||||||
|
|
||||||
if (response.getStatusLine().getStatusCode() != 201){
|
if (response.getStatusLine().getStatusCode() != 201) {
|
||||||
logger.error("Failed to send message to reviewers : HTTP error code : "
|
logger.error("Failed to send message to reviewers : HTTP error code : "
|
||||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||||
}
|
}
|
||||||
|
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Failed to send messages", e);
|
logger.error("Failed to send messages", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -522,11 +549,8 @@ public class SocialCommunications {
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public static void sendEmailAdministratorsOnOperationReverted(
|
public static void sendEmailAdministratorsOnOperationReverted(String serviceUrl, RevertableOperationInfo rInfo,
|
||||||
String serviceUrl,
|
long groupId) throws Exception {
|
||||||
RevertableOperationInfo rInfo,
|
|
||||||
long groupId
|
|
||||||
) throws Exception {
|
|
||||||
|
|
||||||
// get the list of GRSF Reviewers to alert them as well
|
// get the list of GRSF Reviewers to alert them as well
|
||||||
RoleManager roleManager = new LiferayRoleManager();
|
RoleManager roleManager = new LiferayRoleManager();
|
||||||
|
@ -536,9 +560,9 @@ public class SocialCommunications {
|
||||||
|
|
||||||
List<String> reviewers = new ArrayList<String>(reviewersGcube.size());
|
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 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());
|
reviewers.add(gU.getUsername());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -548,26 +572,31 @@ public class SocialCommunications {
|
||||||
String currentScope = ScopeProvider.instance.get();
|
String currentScope = ScopeProvider.instance.get();
|
||||||
String tokenUser = SecurityTokenProvider.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;
|
String basePath = serviceUrl;
|
||||||
|
|
||||||
if(basePath == null){
|
if (basePath == null) {
|
||||||
|
|
||||||
logger.error("Unable to write a post because there is no social networking service available");
|
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");
|
throw new Exception("Unable to discover the social networking service");
|
||||||
|
|
||||||
}else{
|
} else {
|
||||||
|
|
||||||
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
|
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 applicationToken = requireApplicationToken(serviceUrl);
|
||||||
|
|
||||||
String messageToEditor = EMAIL_EDITOR_REVERT.replace("RECORD_URL", rInfo.getRecordUrl()).replace("ORIGINAL_USER", rInfo.getFullNameOriginalAdmin()).
|
String messageToEditor = EMAIL_EDITOR_REVERT.replace("RECORD_URL", rInfo.getRecordUrl())
|
||||||
replace("ADMIN_WHO_CHANGED", rInfo.getFullNameCurrentAdmin());
|
.replace("ORIGINAL_USER", rInfo.getFullNameOriginalAdmin())
|
||||||
String messageToReviewer = EMAIL_REVIEWER_REVERT.replace("ADMIN_WHO_CHANGED", rInfo.getFullNameCurrentAdmin()).replace("RECORD_URL", rInfo.getRecordUrl()).
|
.replace("ADMIN_WHO_CHANGED", rInfo.getFullNameCurrentAdmin());
|
||||||
replace("ORIGINAL_USER", rInfo.getFullNameOriginalAdmin());
|
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";
|
String subject = "Revert merge request on GRSF Record";
|
||||||
|
|
||||||
messageToEditor = messageToEditor.replace("<br>", "\n");
|
messageToEditor = messageToEditor.replace("<br>", "\n");
|
||||||
|
@ -591,7 +620,7 @@ public class SocialCommunications {
|
||||||
|
|
||||||
Map<String, Object> mapResponseWritePost = getResponseEntityAsJSON(response);
|
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 : "
|
logger.error("Failed to send message to editor : HTTP error code : "
|
||||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||||
}
|
}
|
||||||
|
@ -603,7 +632,7 @@ public class SocialCommunications {
|
||||||
reqMessage.put("subject", subject);
|
reqMessage.put("subject", subject);
|
||||||
reqMessage.put("body", messageToReviewer);
|
reqMessage.put("body", messageToReviewer);
|
||||||
recipients = new JSONArray();
|
recipients = new JSONArray();
|
||||||
for(String reviewer: reviewers){
|
for (String reviewer : reviewers) {
|
||||||
JSONObject recip = new JSONObject();
|
JSONObject recip = new JSONObject();
|
||||||
recip.put("id", reviewer);
|
recip.put("id", reviewer);
|
||||||
recipients.add(recip);
|
recipients.add(recip);
|
||||||
|
@ -615,12 +644,12 @@ public class SocialCommunications {
|
||||||
response = client.execute(postRequest);
|
response = client.execute(postRequest);
|
||||||
mapResponseWritePost = getResponseEntityAsJSON(response);
|
mapResponseWritePost = getResponseEntityAsJSON(response);
|
||||||
|
|
||||||
if (response.getStatusLine().getStatusCode() != 201){
|
if (response.getStatusLine().getStatusCode() != 201) {
|
||||||
logger.error("Failed to send message to editor : HTTP error code : "
|
logger.error("Failed to send message to editor : HTTP error code : "
|
||||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||||
}
|
}
|
||||||
|
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Failed to send messages", e);
|
logger.error("Failed to send messages", e);
|
||||||
throw new Exception(e);
|
throw new Exception(e);
|
||||||
}
|
}
|
||||||
|
@ -630,24 +659,28 @@ public class SocialCommunications {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create the url to be send for reverting the operation
|
* Create the url to be send for reverting the operation
|
||||||
* @param httpSession
|
*
|
||||||
|
* @param httpSession
|
||||||
* @return
|
* @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);
|
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();
|
String shortUrl = operationUrl.getShortUrl();
|
||||||
return shortUrl;
|
return shortUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert the json response to a map
|
* Convert the json response to a map
|
||||||
|
*
|
||||||
* @param response
|
* @param response
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public static Map<String, Object> getResponseEntityAsJSON(HttpResponse response){
|
public static Map<String, Object> getResponseEntityAsJSON(HttpResponse response) {
|
||||||
|
|
||||||
Map<String, Object> toReturn = null;
|
Map<String, Object> toReturn = null;
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
|
@ -660,7 +693,7 @@ public class SocialCommunications {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
toReturn = objectMapper.readValue(jsonString, HashMap.class);
|
toReturn = objectMapper.readValue(jsonString, HashMap.class);
|
||||||
logger.debug("Map is " + toReturn);
|
logger.debug("Map is " + toReturn);
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Failed to read json object", 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.
|
* Utility methods for GRSF Management panel widget.
|
||||||
|
*
|
||||||
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
||||||
*/
|
*/
|
||||||
public class Utils {
|
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}";
|
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.
|
* Return a map for converting a key to a namespace:key format by reading a
|
||||||
* @param httpSession
|
* generic resource.
|
||||||
|
*
|
||||||
|
* @param httpSession
|
||||||
* @return a map
|
* @return a map
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@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
|
// check if this information is available in session
|
||||||
String sessionKey = ScopeProvider.instance.get() + resourceName;
|
String sessionKey = ScopeProvider.instance.get() + resourceName;
|
||||||
if(httpSession.getAttribute(sessionKey) != null)
|
if (httpSession.getAttribute(sessionKey) != null)
|
||||||
return (Map<String, String>) httpSession.getAttribute(sessionKey);
|
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 {
|
try {
|
||||||
Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource " +
|
Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource "
|
||||||
"where $profile/Profile/SecondaryType/string() eq '"+ "ApplicationProfile" + "' and $profile/Profile/Name/string() " +
|
+ "where $profile/Profile/SecondaryType/string() eq '" + "ApplicationProfile"
|
||||||
" eq '" + resourceName + "'" +
|
+ "' and $profile/Profile/Name/string() " + " eq '" + resourceName + "'" + "return $profile");
|
||||||
"return $profile");
|
|
||||||
|
|
||||||
DiscoveryClient<String> client = client();
|
DiscoveryClient<String> client = client();
|
||||||
List<String> appProfile = client.submit(q);
|
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");
|
throw new Exception("Your applicationProfile is not registered in the infrastructure");
|
||||||
else {
|
else {
|
||||||
|
|
||||||
String elem = appProfile.get(0);
|
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();
|
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
|
||||||
XPathHelper helper = new XPathHelper(node);
|
XPathHelper helper = new XPathHelper(node);
|
||||||
|
|
||||||
|
@ -94,17 +97,18 @@ public class Utils {
|
||||||
NodeList nodeListModifiedKeys = helper.evaluateForNodes("//modifiedKey");
|
NodeList nodeListModifiedKeys = helper.evaluateForNodes("//modifiedKey");
|
||||||
int sizeKeys = nodeListKeys != null ? nodeListKeys.getLength() : 0;
|
int sizeKeys = nodeListKeys != null ? nodeListKeys.getLength() : 0;
|
||||||
int sizeKeysModifed = nodeListModifiedKeys != null ? nodeListModifiedKeys.getLength() : 0;
|
int sizeKeysModifed = nodeListModifiedKeys != null ? nodeListModifiedKeys.getLength() : 0;
|
||||||
if(sizeKeys != sizeKeysModifed)
|
if (sizeKeys != sizeKeysModifed)
|
||||||
throw new Exception("Malformed XML");
|
throw new Exception("Malformed XML");
|
||||||
logger.debug("Size is " + sizeKeys);
|
logger.debug("Size is " + sizeKeys);
|
||||||
for (int i = 0; i < sizeKeys; i++) {
|
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);
|
logger.debug("Map is " + namespacesMap);
|
||||||
|
|
||||||
// put them into session for speeding up the operations
|
// put them into session for speeding up the operations
|
||||||
httpSession.setAttribute(sessionKey, namespacesMap);
|
httpSession.setAttribute(sessionKey, namespacesMap);
|
||||||
return namespacesMap;
|
return namespacesMap;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", 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 extrasAsPairs
|
||||||
* @param namespaces
|
* @param namespaces
|
||||||
* @return a map with replaced key value pairs
|
* @return a map with replaced key value pairs
|
||||||
|
@ -129,7 +135,7 @@ public class Utils {
|
||||||
String replacedKey = namespaces.containsKey(pairKey) ? namespaces.get(pairKey) : pairKey;
|
String replacedKey = namespaces.containsKey(pairKey) ? namespaces.get(pairKey) : pairKey;
|
||||||
|
|
||||||
List<String> values = null;
|
List<String> values = null;
|
||||||
if(toReturn.containsKey(replacedKey))
|
if (toReturn.containsKey(replacedKey))
|
||||||
values = toReturn.get(replacedKey);
|
values = toReturn.get(replacedKey);
|
||||||
else
|
else
|
||||||
values = new ArrayList<String>(1);
|
values = new ArrayList<String>(1);
|
||||||
|
@ -143,10 +149,11 @@ public class Utils {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the extras of this dataset as hashmap
|
* Get the extras of this dataset as hashmap
|
||||||
|
*
|
||||||
* @param extrasAsPairs
|
* @param extrasAsPairs
|
||||||
* @return
|
* @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>>();
|
Map<String, List<String>> toReturn = new HashMap<String, List<String>>();
|
||||||
|
|
||||||
|
@ -155,7 +162,7 @@ public class Utils {
|
||||||
String pairValue = ckanPair.getValue();
|
String pairValue = ckanPair.getValue();
|
||||||
|
|
||||||
List<String> values = null;
|
List<String> values = null;
|
||||||
if(toReturn.containsKey(pairKey))
|
if (toReturn.containsKey(pairKey))
|
||||||
values = toReturn.get(pairKey);
|
values = toReturn.get(pairKey);
|
||||||
else
|
else
|
||||||
values = new ArrayList<String>(1);
|
values = new ArrayList<String>(1);
|
||||||
|
@ -169,68 +176,66 @@ public class Utils {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send an update for this bean
|
* Send an update for this bean
|
||||||
|
*
|
||||||
* @param baseUrl
|
* @param baseUrl
|
||||||
* @param bean
|
* @param bean
|
||||||
* @param username
|
* @param username
|
||||||
* @param catalogue
|
* @param catalogue
|
||||||
* @return true on success, false otherwise
|
* @return true on success, false otherwise
|
||||||
*/
|
*/
|
||||||
public static void updateRecord(
|
public static void updateRecord(String serviceUrl, final ManageProductBean bean, final DataCatalogue catalogue,
|
||||||
String serviceUrl,
|
final String username, final String fullName, final HttpServletRequest httpServletRequest,
|
||||||
final ManageProductBean bean,
|
final long groupId, final String context, final String token) throws Exception {
|
||||||
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");
|
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");
|
throw new IllegalArgumentException("Item bean to manage cannot be null");
|
||||||
|
|
||||||
try(CloseableHttpClient httpClient = HttpClientBuilder.create().build();){
|
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();) {
|
||||||
|
|
||||||
//ADDED BY FRANCESCO
|
// ADDED BY FRANCESCO
|
||||||
if(Utils.isIntoPortal()) {
|
if (Utils.isIntoPortal()) {
|
||||||
|
|
||||||
// send update to the knowledge base
|
// send update to the knowledge base
|
||||||
GRSFUpdaterServiceClient.updateKB(httpClient, serviceUrl, bean, catalogue, username, fullName);
|
GRSFUpdaterServiceClient.updateKB(httpClient, serviceUrl, bean, catalogue, username, fullName);
|
||||||
|
|
||||||
// if there are merges, update the status of the other involved records
|
// if there are merges, update the status of the other involved records
|
||||||
if(bean.isMergesInvolved())
|
if (bean.isMergesInvolved())
|
||||||
updateStatusInvolvedRecords(bean, catalogue);
|
updateStatusInvolvedRecords(bean, username, catalogue);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// require social networking url
|
// require social networking url
|
||||||
final String baseUrlSocial = SocialCommunications.getBaseUrlSocialService(httpServletRequest);
|
final String baseUrlSocial = SocialCommunications.getBaseUrlSocialService(httpServletRequest);
|
||||||
|
|
||||||
// and the user current browser url
|
// 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() {
|
Thread t = new Thread(new Runnable() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
ScopeProvider.instance.set(context);
|
ScopeProvider.instance.set(context);
|
||||||
SecurityTokenProvider.instance.set(token);
|
SecurityTokenProvider.instance.set(token);
|
||||||
try{
|
try {
|
||||||
|
|
||||||
// send email to Editors and Reviewers
|
// send email to Editors and Reviewers
|
||||||
SocialCommunications.sendEmailAdministrators(baseUrlSocial, bean, catalogue, username, fullName,
|
SocialCommunications.sendEmailAdministrators(baseUrlSocial, bean, catalogue, username, fullName,
|
||||||
groupId, currentBrowserUrl, bean.isMergesInvolved());
|
groupId, currentBrowserUrl, bean.isMergesInvolved());
|
||||||
|
|
||||||
// create a post about the operation
|
// create a post about the operation
|
||||||
SocialCommunications.writeProductPost(baseUrlSocial, bean, username, fullName, false, currentBrowserUrl);
|
SocialCommunications.writeProductPost(baseUrlSocial, bean, username, fullName, false,
|
||||||
|
currentBrowserUrl);
|
||||||
|
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Something failed while alerting editors/reviewers", e);
|
logger.error("Something failed while alerting editors/reviewers", e);
|
||||||
}finally{
|
} finally {
|
||||||
ScopeProvider.instance.reset();
|
ScopeProvider.instance.reset();
|
||||||
SecurityTokenProvider.instance.reset();
|
SecurityTokenProvider.instance.reset();
|
||||||
}
|
}
|
||||||
|
@ -238,7 +243,7 @@ public class Utils {
|
||||||
});
|
});
|
||||||
t.start();
|
t.start();
|
||||||
|
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Unable to update this Item ", e);
|
logger.error("Unable to update this Item ", e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
@ -246,14 +251,16 @@ public class Utils {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Revert operation and alert admins/vre users
|
* Revert operation and alert admins/vre users
|
||||||
|
*
|
||||||
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
||||||
* @param httpClient
|
* @param httpClient
|
||||||
* @param baseUrl
|
* @param baseUrl
|
||||||
* @param fullName
|
* @param fullName
|
||||||
* @param uuid
|
* @param uuid
|
||||||
*/
|
*/
|
||||||
public static void revertOperation(CloseableHttpClient httpClient, String baseUrl, HttpServletRequest httpServletRequest,
|
public static void revertOperation(CloseableHttpClient httpClient, String baseUrl,
|
||||||
final RevertableOperationInfo rInfo, final String token, final String context, final long groupId) throws Exception{
|
HttpServletRequest httpServletRequest, final RevertableOperationInfo rInfo, final String token,
|
||||||
|
final String context, final long groupId) throws Exception {
|
||||||
|
|
||||||
GRSFUpdaterServiceClient.revertOperation(httpClient, baseUrl, rInfo.getFullNameCurrentAdmin(), rInfo.getUuid());
|
GRSFUpdaterServiceClient.revertOperation(httpClient, baseUrl, rInfo.getFullNameCurrentAdmin(), rInfo.getUuid());
|
||||||
|
|
||||||
|
@ -261,16 +268,18 @@ public class Utils {
|
||||||
final String baseUrlSocial = SocialCommunications.getBaseUrlSocialService(httpServletRequest);
|
final String baseUrlSocial = SocialCommunications.getBaseUrlSocialService(httpServletRequest);
|
||||||
|
|
||||||
// and the user current browser url
|
// 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() {
|
Thread t = new Thread(new Runnable() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
ScopeProvider.instance.set(context);
|
ScopeProvider.instance.set(context);
|
||||||
SecurityTokenProvider.instance.set(token);
|
SecurityTokenProvider.instance.set(token);
|
||||||
try{
|
try {
|
||||||
|
|
||||||
// write post about this
|
// write post about this
|
||||||
SocialCommunications.writePostOnRevert(baseUrlSocial, rInfo, false, currentBrowserUrl);
|
SocialCommunications.writePostOnRevert(baseUrlSocial, rInfo, false, currentBrowserUrl);
|
||||||
|
@ -278,9 +287,9 @@ public class Utils {
|
||||||
// alert who's involved
|
// alert who's involved
|
||||||
SocialCommunications.sendEmailAdministratorsOnOperationReverted(baseUrlSocial, rInfo, groupId);
|
SocialCommunications.sendEmailAdministratorsOnOperationReverted(baseUrlSocial, rInfo, groupId);
|
||||||
|
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
logger.error("Something failed while alerting editors/reviewers", e);
|
logger.error("Something failed while alerting editors/reviewers", e);
|
||||||
}finally{
|
} finally {
|
||||||
ScopeProvider.instance.reset();
|
ScopeProvider.instance.reset();
|
||||||
SecurityTokenProvider.instance.reset();
|
SecurityTokenProvider.instance.reset();
|
||||||
}
|
}
|
||||||
|
@ -292,23 +301,26 @@ public class Utils {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update the status of the involved records to "to be merged"
|
* Update the status of the involved records to "to be merged".
|
||||||
* @param bean
|
*
|
||||||
* @param catalogue
|
* @param bean the bean
|
||||||
* @param username
|
* @param username the username
|
||||||
* @param fullName
|
* @param catalogue the catalogue
|
||||||
* @throws Exception
|
* @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 context = ScopeProvider.instance.get();
|
||||||
String sysApi = fetchSysAPI(context);
|
// String sysApi = fetchSysAPI(context);
|
||||||
for(SimilarGRSFRecord s: bean.getSimilarGrsfRecords()){
|
for (SimilarGRSFRecord s : bean.getSimilarGrsfRecords()) {
|
||||||
if(s.isSuggestedMerge()){
|
if (s.isSuggestedMerge()) {
|
||||||
String productId = s.getKnowledgeBaseId();
|
String productId = s.getKnowledgeBaseId();
|
||||||
Map<String, List<String>> updateStatus = new HashMap<String, List<String>>(1);
|
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()));
|
updateStatus.put(Constants.STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY,
|
||||||
catalogue.patchProductCustomFields(productId, sysApi, updateStatus, true);
|
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
|
* Get the scope in which ckan information needs to be discovered from the url
|
||||||
|
*
|
||||||
* @param httpServletRequest
|
* @param httpServletRequest
|
||||||
* @return
|
* @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!");
|
throw new IllegalArgumentException("HttpServletRequest is null!");
|
||||||
|
|
||||||
String scopeToReturn = null;
|
String scopeToReturn = null;
|
||||||
try{
|
try {
|
||||||
String clientUrl = getCurrentClientUrl(httpServletRequest).split("\\?")[0];
|
String clientUrl = getCurrentClientUrl(httpServletRequest).split("\\?")[0];
|
||||||
logger.debug("Client url is " + clientUrl);
|
logger.debug("Client url is " + clientUrl);
|
||||||
|
|
||||||
// check if this information is in session, otherwise set it and return
|
// check if this information is in session, otherwise set it and return
|
||||||
HttpSession session = httpServletRequest.getSession();
|
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);
|
logger.debug("Scope to return is " + scopeToReturn);
|
||||||
}else{
|
} else {
|
||||||
// ask to the ckan library and set it
|
// ask to the ckan library and set it
|
||||||
scopeToReturn = ApplicationProfileScopePerUrlReader.getScopePerUrl(clientUrl);
|
scopeToReturn = ApplicationProfileScopePerUrlReader.getScopePerUrl(clientUrl);
|
||||||
logger.debug("Scope to return is " + scopeToReturn);
|
logger.debug("Scope to return is " + scopeToReturn);
|
||||||
session.setAttribute(clientUrl, scopeToReturn);
|
session.setAttribute(clientUrl, scopeToReturn);
|
||||||
}
|
}
|
||||||
}catch(Exception e){
|
} catch (Exception e) {
|
||||||
scopeToReturn = getCurrentContext(httpServletRequest, true);
|
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;
|
return scopeToReturn;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Needed to get the url of the client
|
* Needed to get the url of the client
|
||||||
|
*
|
||||||
* @param httpServletRequest the httpServletRequest object
|
* @param httpServletRequest the httpServletRequest object
|
||||||
* @return the instance of the user
|
* @return the instance of the user
|
||||||
* @see the url at client side
|
* @see the url at client side
|
||||||
*/
|
*/
|
||||||
public static String getCurrentClientUrl(HttpServletRequest httpServletRequest) {
|
public static String getCurrentClientUrl(HttpServletRequest httpServletRequest) {
|
||||||
if(httpServletRequest == null)
|
if (httpServletRequest == null)
|
||||||
throw new IllegalArgumentException("HttpServletRequest is null!");
|
throw new IllegalArgumentException("HttpServletRequest is null!");
|
||||||
|
|
||||||
return httpServletRequest.getHeader(Constants.GCUBE_REQUEST_URL);
|
return httpServletRequest.getHeader(Constants.GCUBE_REQUEST_URL);
|
||||||
|
@ -362,19 +377,20 @@ public class Utils {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the current scope by using the portal manager
|
* Retrieve the current scope by using the portal manager
|
||||||
* @param b
|
*
|
||||||
|
* @param b
|
||||||
* @return a GcubeUser object
|
* @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!");
|
throw new IllegalArgumentException("HttpServletRequest is null!");
|
||||||
|
|
||||||
PortalContext pContext = PortalContext.getConfiguration();
|
PortalContext pContext = PortalContext.getConfiguration();
|
||||||
String context = pContext.getCurrentScope(request);
|
String context = pContext.getCurrentScope(request);
|
||||||
logger.debug("Returning context " + context);
|
logger.debug("Returning context " + context);
|
||||||
|
|
||||||
if(context != null && setInThread)
|
if (context != null && setInThread)
|
||||||
ScopeProvider.instance.set(context);
|
ScopeProvider.instance.set(context);
|
||||||
|
|
||||||
return context;
|
return context;
|
||||||
|
@ -382,11 +398,12 @@ public class Utils {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the current user by using the portal manager
|
* Retrieve the current user by using the portal manager
|
||||||
|
*
|
||||||
* @return a GcubeUser object
|
* @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!");
|
throw new IllegalArgumentException("HttpServletRequest is null!");
|
||||||
|
|
||||||
PortalContext pContext = PortalContext.getConfiguration();
|
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 url the url
|
||||||
* @param clg the clg
|
* @param clg the clg
|
||||||
* @param username the username
|
* @param username the username
|
||||||
* @return the dataset from url
|
* @return the dataset from url
|
||||||
* @throws Exception the exception
|
* @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;
|
return null;
|
||||||
|
|
||||||
// Parse url
|
// 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 url
|
||||||
* @param clg
|
* @param clg
|
||||||
* @return
|
* @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;
|
return null;
|
||||||
|
|
||||||
// Parse url
|
// Parse url
|
||||||
|
@ -450,39 +470,38 @@ public class Utils {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a {@link SimilarGRSFRecord} from a json string
|
* Get a {@link SimilarGRSFRecord} from a json string
|
||||||
|
*
|
||||||
* @param json
|
* @param json
|
||||||
* @return {@link SimilarGRSFRecord}
|
* @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;
|
return null;
|
||||||
|
|
||||||
JSONParser parser = new JSONParser();
|
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));
|
String uuid = getDatasetKnowledgeBaseIdFromUrl((String) object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_URL));
|
||||||
CkanDataset dataset = ctl.getDataset(uuid,username);
|
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);
|
|
||||||
|
|
||||||
return new SimilarGRSFRecord(
|
boolean isStock = dataset.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY)
|
||||||
uuid,
|
.contains(Product_Type.STOCK.getOrigName());
|
||||||
(String)object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_DESCRIPTION),
|
Map<String, String> fieldsNamespacesMap = Utils.getFieldToFieldNameSpaceMapping(httpSession,
|
||||||
(String)object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_NAME),
|
isStock ? Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK
|
||||||
dataset.getTitle(),
|
: Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
|
||||||
(String)object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_URL),
|
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.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 {
|
try {
|
||||||
UserLocalServiceUtil.getService();
|
UserLocalServiceUtil.getService();
|
||||||
return true;
|
return true;
|
||||||
}catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
logger.debug("Development Mode ON");
|
logger.debug("Development Mode ON");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
@ -504,53 +523,45 @@ public class Utils {
|
||||||
/**
|
/**
|
||||||
* Get Connected bean from record.
|
* Get Connected bean from record.
|
||||||
*
|
*
|
||||||
* @param destUrl the dest url
|
* @param destUrl the dest url
|
||||||
* @param clg the clg
|
* @param clg the clg
|
||||||
* @param username the username
|
* @param username the username
|
||||||
* @param httpSession the http session
|
* @param httpSession the http session
|
||||||
* @return the connected bean
|
* @return the connected bean
|
||||||
* @throws ParseException the parse exception
|
* @throws ParseException the parse exception
|
||||||
*/
|
*/
|
||||||
public static ConnectedBean connectedBeanRecordFromUrl(
|
public static ConnectedBean connectedBeanRecordFromUrl(String destUrl, DataCatalogue clg, String username,
|
||||||
String destUrl,
|
HttpSession httpSession) throws ParseException {
|
||||||
DataCatalogue clg,
|
|
||||||
String username,
|
|
||||||
HttpSession httpSession
|
|
||||||
) throws ParseException {
|
|
||||||
|
|
||||||
if(destUrl == null)
|
if (destUrl == null)
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
String connectedBeanUuid = getDatasetKnowledgeBaseIdFromUrl(destUrl);
|
String connectedBeanUuid = getDatasetKnowledgeBaseIdFromUrl(destUrl);
|
||||||
CkanDataset destDataset = clg.getDataset(connectedBeanUuid,username);
|
CkanDataset destDataset = clg.getDataset(connectedBeanUuid, username);
|
||||||
boolean isStock = destDataset.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY).contains(Product_Type.STOCK.getOrigName());
|
boolean isStock = destDataset.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY)
|
||||||
Map<String, String> fieldsNamespacesMap =
|
.contains(Product_Type.STOCK.getOrigName());
|
||||||
Utils.getFieldToFieldNameSpaceMapping(httpSession, isStock ?
|
Map<String, String> fieldsNamespacesMap = Utils.getFieldToFieldNameSpaceMapping(httpSession,
|
||||||
Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK : Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
|
isStock ? Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK
|
||||||
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(destDataset.getExtras(), fieldsNamespacesMap);
|
: 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 semanticId = extrasWithoutNamespaces.get(Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY).get(0);
|
||||||
String destDomain = extrasWithoutNamespaces.get(Constants.DOMAIN_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 shortName = extrasWithoutNamespaces.get(Constants.SHORT_NAME_CUSTOM_KEY).get(0);
|
||||||
String description = destDataset.getNotes();
|
String description = destDataset.getNotes();
|
||||||
|
|
||||||
return new ConnectedBean(
|
return new ConnectedBean(connectedBeanUuid, description, shortName, destDataset.getTitle(), destUrl, semanticId,
|
||||||
connectedBeanUuid,
|
destDomain);
|
||||||
description,
|
|
||||||
shortName,
|
|
||||||
destDataset.getTitle(),
|
|
||||||
destUrl,
|
|
||||||
semanticId,
|
|
||||||
destDomain
|
|
||||||
);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch the sysadmin key from the IS for this catalogue
|
* Fetch the sysadmin key from the IS for this catalogue
|
||||||
|
*
|
||||||
* @return
|
* @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);
|
DataCatalogueRunningCluster catalogueRunningInstance = new DataCatalogueRunningCluster(context);
|
||||||
return catalogueRunningInstance.getSysAdminToken();
|
return catalogueRunningInstance.getSysAdminToken();
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,35 +1,40 @@
|
||||||
package org.gcube.datacatalogue.grsf_manage_widget.shared.ex;
|
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.
|
* The Class GRSFRecordAlreadyManagedStatusException.
|
||||||
*
|
*
|
||||||
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
|
* @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 static final long serialVersionUID = -2034802685606929315L;
|
||||||
private Status status;
|
private Status status;
|
||||||
|
|
||||||
|
public GRSFRecordAlreadyManagedStatusException() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instantiates a new GRSF record already managed status exception.
|
* Instantiates a new GRSF record already managed status exception.
|
||||||
*
|
*
|
||||||
* @param theStatus the the status
|
* @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);
|
super(arg0);
|
||||||
this.status = theStatus;
|
this.status = theStatus;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the status.
|
* Gets the status.
|
||||||
*
|
*
|
||||||
|
|
|
@ -1,12 +1,14 @@
|
||||||
package org.gcube.datacatalogue.grsf_manage_widget.shared.ex;
|
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
|
* This is thrown when the Manage product is pushed on a product that has a
|
||||||
* a Record Type field of Source or none.
|
* Record Type field of Source or none.
|
||||||
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
*
|
||||||
|
* @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 static final long serialVersionUID = 721315478405659218L;
|
||||||
private String errorMessage;
|
private String errorMessage;
|
||||||
|
|
Loading…
Reference in New Issue