Compare commits

..

2 Commits

8 changed files with 315 additions and 380 deletions

View File

@ -4,21 +4,7 @@
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.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
## [v1.6.0-SNAPSHOT] - 2022-05-25
#### Bug fixes

10
pom.xml
View File

@ -13,7 +13,7 @@
<groupId>org.gcube.portlets.widgets</groupId>
<artifactId>grsf-manage-widget</artifactId>
<version>1.7.0</version>
<version>1.6.0-SNAPSHOT</version>
<name>gCube GRSF Manage widget</name>
<scm>
@ -24,12 +24,12 @@
<properties>
<!-- Convenience property to set the GWT version -->
<gwtVersion>2.9.0</gwtVersion>
<gwtVersion>2.7.0</gwtVersion>
<!-- <webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory> -->
<distroDirectory>distro</distroDirectory>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
@ -38,7 +38,7 @@
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>maven-portal-bom</artifactId>
<version>3.6.4</version>
<version>3.6.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -78,7 +78,7 @@
<dependency>
<groupId>org.gcube.data-catalogue</groupId>
<artifactId>grsf-common-library</artifactId>
<version>[2-0-0-SNAPSHOT, 3-0-0-SNAPSHOT)</version>
<version>[1-0-0, 2-0-0-SNAPSHOT)</version>
<scope>compile</scope>
</dependency>
<dependency>

View File

@ -673,7 +673,7 @@ public class ManageProductWidget extends Composite{
for(SimilarGRSFRecord sR: bean.getSimilarGrsfRecords()){
if(sR.isSuggestedMerge()){
bean.setMergesInvolved(true);
report += "\n\t - merge the current record with record '" + sR.getTitle() + "' ;";
report += "\n\t - merge the current record with record '" + sR.getTitle() + " ;";
report += "\n\t \t- GRSF Name '" + sR.getTitle() + "' ;";
report += "\n\t \t- Short Name '" + sR.getShortName() + "' ;";
report += "\n\t \t- URL '" + sR.getUrl() + "' ;";

View File

@ -320,7 +320,7 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
List<CkanResource> resources = record.getResources();
List<SourceRecord> sources = new ArrayList<SourceRecord>(3);
for (CkanResource ckanResource : resources) {
if (Sources.listNames().contains(ckanResource.getName()))
if (Sources.getListNames().contains(ckanResource.getName()))
sources.add(new SourceRecord(ckanResource.getName(), ckanResource.getUrl()));
}
@ -587,17 +587,17 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
@Override
public String checkIdentifierExistsInDomain(String id, String acceptedDomain) throws Exception {
// if (!Utils.isIntoPortal()) {
// boolean throwException = Math.random() > 0.5;
//
// // simulate some delay...
// Thread.sleep(2500);
//
// if (throwException)
// throw new Exception("The suggested record is not a GRSF record");
//
// return "http://data.d4science.org/catalogue/grsf_admin/" + id;
// }
if (!Utils.isIntoPortal()) {
boolean throwException = Math.random() > 0.5;
// simulate some delay...
Thread.sleep(2500);
if (throwException)
throw new Exception("The suggested record is not a GRSF record");
return "http://data.d4science.org/catalogue/grsf_admin/" + id;
}
String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest());
DataCatalogue catalogue = getCatalogue(scopePerCurrentUrl);

View File

@ -41,10 +41,9 @@ import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* For managing the different interactions with social channels (posts and
* mails)
*
* For managing the different interactions with social channels (posts and mails)
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class SocialCommunications {
@ -65,10 +64,9 @@ public class SocialCommunications {
private static final String MEDIATYPE_JSON = "application/json";
// for writing a post in the GRSF admin context
private static final String APPLICATION_ID_CATALOGUE_MANAGER = "org.gcube.datacatalogue.GRSFNotifier";
private static final String APPLICATION_ID_CATALOGUE_MANAGER = "org.gcube.datacatalogue.GRSFNotifier";
// emails to be sent to editors and reviewers and post to be written into the
// grsf admin vre
// emails to be sent to editors and reviewers and post to be written into the grsf admin vre
private static final String POST_MESSAGE = "Dear members,"
+ "\nThe record 'PRODUCT_TITLE' has been just updated by USER_FULLNAME."
+ "\nYou can inspect it here: LINK_RECORD.";
@ -83,7 +81,7 @@ public class SocialCommunications {
private static final String ADD_REPORT = "<br> <br>This is a summary of the actions proposed: <br>REPORT_UPDATE<br>";
// revert link
// revert link
private static final String REVERT_LINK_PIECE = "<br>The request involves a merge operation. You can reject the merge by exploiting this link LINK in the following 24 hours.";
// on revert operation
@ -91,7 +89,7 @@ public class SocialCommunications {
+ "<br>a revert operation (undo merge) has been requested on record RECORD_URL, by ADMIN_WHO_CHANGED.";
private static final String EMAIL_EDITOR_REVERT = "Dear ORIGINAL_USER,"
+ "<br>a revert operation (undo merge) has been requested on this RECORD_URL you managed by ADMIN_WHO_CHANGED.";
+"<br>a revert operation (undo merge) has been requested on this RECORD_URL you managed by ADMIN_WHO_CHANGED.";
// post on revert
private static final String POST_ON_REVERT = "Dear members,"
@ -101,42 +99,39 @@ public class SocialCommunications {
/**
*
* @param httpServletRequest
* @param httpServletRequest
* @param context
* @return
*/
public static String getBaseUrlSocialService(HttpServletRequest httpServletRequest) {
public static String getBaseUrlSocialService(HttpServletRequest httpServletRequest){
String context = ScopeProvider.instance.get();
String keyPerContext = SOCIAL_NETWORKING_BASE_URL_SESSION_KEY + context;
String keyPerContext = SOCIAL_NETWORKING_BASE_URL_SESSION_KEY + context;
String basePath = (String) httpServletRequest.getSession().getAttribute(keyPerContext);
if (basePath == null) {
try {
if(basePath == null){
try{
SimpleQuery query = queryFor(GCoreEndpoint.class);
query.addCondition(String.format("$resource/Profile/ServiceClass/text() eq '%s'", serviceClass));
query.addCondition(String.format("$resource/Profile/ServiceClass/text() eq '%s'",serviceClass));
query.addCondition("$resource/Profile/DeploymentData/Status/text() eq 'ready'");
query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'", serviceName));
query.setResult(
"$resource/Profile/AccessPoint/RunningInstanceInterfaces//Endpoint[@EntryName/string() eq \""
+ resource + "\"]/text()");
query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'",serviceName));
query.setResult("$resource/Profile/AccessPoint/RunningInstanceInterfaces//Endpoint[@EntryName/string() eq \""+resource+"\"]/text()");
DiscoveryClient<String> client = client();
List<String> endpoints = client.submit(query);
if (endpoints == null || endpoints.isEmpty())
throw new Exception("Cannot retrieve the GCoreEndpoint serviceName: " + serviceName
+ ", serviceClass: " + serviceClass + ", in scope: " + context);
if (endpoints == null || endpoints.isEmpty())
throw new Exception("Cannot retrieve the GCoreEndpoint serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+context);
basePath = endpoints.get(0);
if (basePath == null)
throw new Exception("Endpoint:" + resource + ", is null for serviceName: " + serviceName
+ ", serviceClass: " + serviceClass + ", in scope: " + context);
if(basePath==null)
throw new Exception("Endpoint:"+resource+", is null for serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+context);
httpServletRequest.getSession().setAttribute(keyPerContext, basePath);
} catch (Exception e) {
}catch(Exception e){
logger.error("Unable to retrieve such service endpoint information!", e);
}
}
@ -146,35 +141,31 @@ public class SocialCommunications {
/**
* Require a proper application token for writing a post and send messages.
*
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
private static String requireApplicationToken(String serviceUrl) throws Exception {
private static String requireApplicationToken(String serviceUrl) throws Exception{
String currentScope = ScopeProvider.instance.get();
String tokenUser = SecurityTokenProvider.instance.get();
logger.info("Current scope for requireApplicationToken is " + currentScope + " and token is "
+ tokenUser.substring(0, 10) + "***************");
logger.info("Current scope for requireApplicationToken is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
String basePath = serviceUrl;
if (basePath == null) {
if(basePath == null){
logger.error("Unable to write a post because there is no social networking service available");
throw new Exception("Unable to discover the social networking service");
} else {
}else{
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
.build();) {
try(CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();){
// ask token application
HttpPost postRequest = new HttpPost(
basePath + SOCIAL_SERVICE_APPLICATION_TOKEN + "?gcube-token=" + tokenUser);
HttpPost postRequest = new HttpPost(basePath + SOCIAL_SERVICE_APPLICATION_TOKEN + "?gcube-token=" + tokenUser);
JSONObject requestToken = new JSONObject();
requestToken.put("app_id", APPLICATION_ID_CATALOGUE_MANAGER);
StringEntity input = new StringEntity(requestToken.toJSONString());
@ -187,21 +178,21 @@ public class SocialCommunications {
if (response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed to retrieve application token : HTTP error code : "
+ response.getStatusLine().getStatusCode());
} else {
}else{
Map<String, Object> mapResponseGeneratedToken = getResponseEntityAsJSON(response);
boolean successGeneratedToken = (boolean) mapResponseGeneratedToken.get("success");
if (!successGeneratedToken) {
boolean successGeneratedToken = (boolean)mapResponseGeneratedToken.get("success");
if(!successGeneratedToken){
throw new RuntimeException("Failed to generate the token for the application!"
+ " Error message is " + mapResponseGeneratedToken.get("message"));
} else {
return (String) mapResponseGeneratedToken.get("result");
}else{
return (String)mapResponseGeneratedToken.get("result");
}
}
} catch (Exception e) {
}catch(Exception e){
logger.error("Failed to create a post", e);
throw e;
}
@ -210,76 +201,63 @@ public class SocialCommunications {
/**
* Notify the users about the required changes.
*
* @param bean
* @param url
* @param username
* @param fullName
* @param hashtags
* @param enablePostNotification
* @throws Exception
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static void writePostOnRevert(String serviceUrl, RevertableOperationInfo rInfo,
boolean enablePostNotification, String userCurrentUrl) throws Exception {
public static void writePostOnRevert(String serviceUrl, RevertableOperationInfo rInfo, boolean enablePostNotification, String userCurrentUrl) throws Exception{
// discover service endpoint for the social networking library
String currentScope = ScopeProvider.instance.get();
String tokenUser = SecurityTokenProvider.instance.get();
logger.info("Current scope for writePostOnRevert is " + currentScope + " and token is "
+ tokenUser.substring(0, 10) + "***************");
logger.info("Current scope for writePostOnRevert is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
String basePath = serviceUrl;
if (basePath == null) {
if(basePath == null){
logger.error("Unable to write a post because there is no social networking service available");
throw new Exception("Unable to discover the social networking service");
} else {
}else{
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
.build();) {
try(CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();){
// require url
String applicationToken = requireApplicationToken(serviceUrl);
// see Feature #17576 updated by Francesco
/*
* final String profilePageURL = GCubePortalConstants.PREFIX_GROUP_URL +
* extractOrgFriendlyURL(userCurrentUrl) +
* GCubePortalConstants.USER_PROFILE_FRIENDLY_URL; String
* userFullNameHighlightedCurrent = "<a class=\"link\" href=\"" + profilePageURL
* + "?"+ Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
* Base64.getEncoder().encodeToString(rInfo.getUserNameCurrentAdmin().getBytes()
* )+"\">"+rInfo.getFullNameCurrentAdmin()+ "</a> ";
*/
//see Feature #17576 updated by Francesco
/*final String profilePageURL = GCubePortalConstants.PREFIX_GROUP_URL + extractOrgFriendlyURL(userCurrentUrl) + GCubePortalConstants.USER_PROFILE_FRIENDLY_URL;
String userFullNameHighlightedCurrent = "<a class=\"link\" href=\"" + profilePageURL + "?"+
Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
Base64.getEncoder().encodeToString(rInfo.getUserNameCurrentAdmin().getBytes())+"\">"+rInfo.getFullNameCurrentAdmin()+
"</a> ";
*/
String userFullNameHighlightedCurrent = "@"+rInfo.getUserNameCurrentAdmin();
String userFullNameHighlightedCurrent = "@" + rInfo.getUserNameCurrentAdmin();
/*
* String userFullNameHighlightedOriginal = "<a class=\"link\" href=\"" +
* profilePageURL + "?"+
* Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
* Base64.getEncoder().encodeToString(rInfo.getUserNameOriginalAdmin().getBytes(
* ))+"\">"+rInfo.getFullNameOriginalAdmin()+ "</a> ";
*/
String userFullNameHighlightedOriginal = "@" + rInfo.getUserNameOriginalAdmin();
/*String userFullNameHighlightedOriginal = "<a class=\"link\" href=\"" + profilePageURL + "?"+
Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
Base64.getEncoder().encodeToString(rInfo.getUserNameOriginalAdmin().getBytes())+"\">"+rInfo.getFullNameOriginalAdmin()+
"</a> ";*/
String userFullNameHighlightedOriginal = "@"+rInfo.getUserNameOriginalAdmin();
// replace
String message = POST_ON_REVERT.replace("RECORD_URL", rInfo.getRecordUrl())
.replace("ADMIN_WHO_CHANGED", userFullNameHighlightedCurrent)
.replace("ORIGINAL_USER", userFullNameHighlightedOriginal);
String message = POST_ON_REVERT.replace("RECORD_URL", rInfo.getRecordUrl()).replace("ADMIN_WHO_CHANGED", userFullNameHighlightedCurrent).replace("ORIGINAL_USER",userFullNameHighlightedOriginal);
// add hashtag
message += "\n\n";
message +="\n\n";
message += " #" + HashTagsOnUpdate.REVERTED_MERGE.getString();
logger.info("The post that is going to be written is -> " + message);
HttpPost postRequest = new HttpPost(
basePath + SOCIAL_SERVICE_WRITE_APPLICATION_POST + "?gcube-token=" + applicationToken);
HttpPost postRequest = new HttpPost(basePath + SOCIAL_SERVICE_WRITE_APPLICATION_POST + "?gcube-token=" + applicationToken);
JSONObject object = new JSONObject();
object.put("text", message);
object.put("enable_notification", enablePostNotification);
@ -294,7 +272,7 @@ public class SocialCommunications {
throw new RuntimeException("Failed to write application post : HTTP error code : "
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
} catch (Exception e) {
}catch(Exception e){
logger.error("Failed to create a post", e);
}
}
@ -302,77 +280,69 @@ public class SocialCommunications {
/**
* Notify the users about the required changes.
*
* @param bean
* @param url
* @param username
* @param fullName
* @param hashtags
* @param enablePostNotification
* @throws Exception
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static void writeProductPost(String serviceUrl, ManageProductBean bean, String username, String fullName,
boolean enablePostNotification, String userCurrentUrl) throws Exception {
public static void writeProductPost(String serviceUrl, ManageProductBean bean, String username, String fullName, boolean enablePostNotification, String userCurrentUrl) throws Exception{
// discover service endpoint for the social networking library
String currentScope = ScopeProvider.instance.get();
String tokenUser = SecurityTokenProvider.instance.get();
logger.info("Current scope for writeProductPost is " + currentScope + " and token is "
+ tokenUser.substring(0, 10) + "***************");
logger.info("Current scope for writeProductPost is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
String basePath = serviceUrl;
if (basePath == null) {
if(basePath == null){
logger.error("Unable to write a post because there is no social networking service available");
throw new Exception("Unable to discover the social networking service");
} else {
}else{
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
.build();) {
try(CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();){
// require url
String applicationToken = requireApplicationToken(serviceUrl);
// see Feature #17576 Updated by Francesco
/*
* final String profilePageURL = GCubePortalConstants.PREFIX_GROUP_URL +
* extractOrgFriendlyURL(userCurrentUrl) +
* GCubePortalConstants.USER_PROFILE_FRIENDLY_URL; String
* userFullNameHighlighted = "<a class=\"link\" href=\"" + profilePageURL + "?"+
* Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
* Base64.getEncoder().encodeToString(username.getBytes())+"\">"+fullName+
* "</a> ";
*/
String userFullNameHighlighted = "@" + username;
//see Feature #17576 Updated by Francesco
/*final String profilePageURL = GCubePortalConstants.PREFIX_GROUP_URL + extractOrgFriendlyURL(userCurrentUrl) + GCubePortalConstants.USER_PROFILE_FRIENDLY_URL;
String userFullNameHighlighted = "<a class=\"link\" href=\"" + profilePageURL + "?"+
Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
Base64.getEncoder().encodeToString(username.getBytes())+"\">"+fullName+
"</a> ";
*/
String userFullNameHighlighted = "@"+username;
// replace
String message = POST_MESSAGE.replace("PRODUCT_TITLE", bean.getTitle())
.replace("LINK_RECORD", bean.getUrl()).replace("USER_FULLNAME", userFullNameHighlighted);
String message = POST_MESSAGE.replace("PRODUCT_TITLE", bean.getTitle()).replace("LINK_RECORD", bean.getUrl()).
replace("USER_FULLNAME", userFullNameHighlighted);
if (bean.getReport() != null && !bean.getReport().isEmpty())
message += ADD_REPORT.replace("<br>", "").replace("REPORT_UPDATE", bean.getReport());
if(bean.getReport() != null && !bean.getReport().isEmpty())
message += ADD_REPORT.replace("REPORT_UPDATE", bean.getReport());
Set<String> hashtags = bean.getHashtags();
logger.debug("Hashtags are " + hashtags);
if (hashtags != null && !hashtags.isEmpty()) {
message += "\n\n";
if(hashtags != null && !hashtags.isEmpty()){
message +="\n\n";
for (String hashtag : hashtags) {
message += " #" + hashtag;
}
// Added by Francesco Mangiacrapa see at Feature #16312
//Added by Francesco Mangiacrapa see at Feature #16312
String normalizedFullName = fullName.trim().replace(" ", "_");
message += " #" + normalizedFullName;
}
logger.info("The post that is going to be written is -> " + message);
HttpPost postRequest = new HttpPost(
basePath + SOCIAL_SERVICE_WRITE_APPLICATION_POST + "?gcube-token=" + applicationToken);
HttpPost postRequest = new HttpPost(basePath + SOCIAL_SERVICE_WRITE_APPLICATION_POST + "?gcube-token=" + applicationToken);
JSONObject object = new JSONObject();
object.put("text", message);
object.put("enable_notification", enablePostNotification);
@ -386,7 +356,7 @@ public class SocialCommunications {
if (response.getStatusLine().getStatusCode() != 201)
throw new RuntimeException("Failed to write application post : HTTP error code : "
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
} catch (Exception e) {
}catch(Exception e){
logger.error("Failed to create a post", e);
}
}
@ -402,26 +372,31 @@ public class SocialCommunications {
} else {
friendlyURL = friendlyURL.split("\\?")[0].split("\\#")[0];
}
return "/" + friendlyURL;
return "/"+friendlyURL;
}
return null;
}
/**
* Send an email to the administrator as well as the
*
* Send an email to the administrator as well as the
* @param bean
* @param catalogue
* @param username
* @param fullName
* @param isMergeInvolved
* @param httpSession
* @throws Exceptio
* @param isMergeInvolved
* @param httpSession
* @throws Exceptio
*/
@SuppressWarnings("unchecked")
public static void sendEmailAdministrators(String serviceUrl, ManageProductBean bean, DataCatalogue catalogue,
String username, String fullName, long groupId, String clientCurrenturl, boolean isMergeInvolved)
throws Exception {
public static void sendEmailAdministrators(
String serviceUrl,
ManageProductBean bean,
DataCatalogue catalogue,
String username,
String fullName,
long groupId,
String clientCurrenturl,
boolean isMergeInvolved) throws Exception {
// get the list of GRSF Reviewers to alert them as well
RoleManager roleManager = new LiferayRoleManager();
@ -431,56 +406,54 @@ public class SocialCommunications {
List<String> reviewers = new ArrayList<String>(reviewersGcube.size());
for (GCubeUser gU : reviewersGcube) {
for(GCubeUser gU: reviewersGcube){
// if the user is a reviewer, then send the email just once
if (!gU.getUsername().equals(username))
if(!gU.getUsername().equals(username))
reviewers.add(gU.getUsername());
}
logger.info("List of " + Constants.GRSF_CATALOGUE_REVIEWER_ROLE + " is " + reviewers);
// build the url that allows to revert the operation
// build the url that allows to revert the operation
RevertableOperations operation = RevertableOperations.MERGE;
// discover service endpoint for the social networking library
String currentScope = ScopeProvider.instance.get();
String tokenUser = SecurityTokenProvider.instance.get();
logger.info("Current scope for writeProductPost is " + currentScope + " and token is "
+ tokenUser.substring(0, 10) + "***************");
logger.info("Current scope for writeProductPost is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
String basePath = serviceUrl;
if (basePath == null) {
if(basePath == null){
logger.error("Unable to write a post because there is no social networking service available");
throw new Exception("Unable to discover the social networking service");
} else {
}else{
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
.build();) {
try(CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();){
/// require url
String applicationToken = requireApplicationToken(serviceUrl);
String revertUrl = "";
if (isMergeInvolved)
revertUrl = getEncodedUrlManage(operation, username, System.currentTimeMillis(),
bean.getKnowledgeBaseId(), clientCurrenturl);
if(isMergeInvolved)
revertUrl = getEncodedUrlManage(operation, username, System.currentTimeMillis(), bean.getKnowledgeBaseId(), clientCurrenturl);
String messageToEditor = (EMAIL_MESSAGE_EDITOR +
(isMergeInvolved? REVERT_LINK_PIECE : "")).replace("USER_FULLNAME", fullName).replace("PRODUCT_TITLE", bean.getTitle()).
replace("LINK_RECORD", bean.getUrl()).replace("LINK", revertUrl);
String messageToReviewer = (EMAIL_MESSAGE_REVIEWER+
(isMergeInvolved? REVERT_LINK_PIECE : "")).replace("USER_FULLNAME", fullName).replace("PRODUCT_TITLE", bean.getTitle()).
replace("LINK_RECORD", bean.getUrl()).replace("LINK", revertUrl);
String messageToEditor = (EMAIL_MESSAGE_EDITOR + (isMergeInvolved ? REVERT_LINK_PIECE : ""))
.replace("USER_FULLNAME", fullName).replace("PRODUCT_TITLE", bean.getTitle())
.replace("LINK_RECORD", bean.getUrl()).replace("LINK", revertUrl);
String messageToReviewer = (EMAIL_MESSAGE_REVIEWER + (isMergeInvolved ? REVERT_LINK_PIECE : ""))
.replace("USER_FULLNAME", fullName).replace("PRODUCT_TITLE", bean.getTitle())
.replace("LINK_RECORD", bean.getUrl()).replace("LINK", revertUrl);
String subject = "Update request on GRSF Record";
// append report
if (bean.getReport() != null) {
if(bean.getReport() != null){
messageToEditor += ADD_REPORT.replace("REPORT_UPDATE", bean.getReport());
messageToReviewer += ADD_REPORT.replace("REPORT_UPDATE", bean.getReport());
}
@ -509,7 +482,7 @@ public class SocialCommunications {
Map<String, Object> mapResponseWritePost = getResponseEntityAsJSON(response);
if (response.getStatusLine().getStatusCode() != 201) {
if (response.getStatusLine().getStatusCode() != 201){
logger.error("Failed to send message to editor : HTTP error code : "
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
}
@ -521,7 +494,7 @@ public class SocialCommunications {
reqMessage.put("subject", subject);
reqMessage.put("body", messageToReviewer);
recipients = new JSONArray();
for (String reviewer : reviewers) {
for(String reviewer: reviewers){
JSONObject recip = new JSONObject();
recip.put("id", reviewer);
recipients.add(recip);
@ -536,12 +509,12 @@ public class SocialCommunications {
response = client.execute(postRequest);
mapResponseWritePost = getResponseEntityAsJSON(response);
if (response.getStatusLine().getStatusCode() != 201) {
if (response.getStatusLine().getStatusCode() != 201){
logger.error("Failed to send message to reviewers : HTTP error code : "
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
}
} catch (Exception e) {
}catch(Exception e){
logger.error("Failed to send messages", e);
}
}
@ -549,8 +522,11 @@ public class SocialCommunications {
}
@SuppressWarnings("unchecked")
public static void sendEmailAdministratorsOnOperationReverted(String serviceUrl, RevertableOperationInfo rInfo,
long groupId) throws Exception {
public static void sendEmailAdministratorsOnOperationReverted(
String serviceUrl,
RevertableOperationInfo rInfo,
long groupId
) throws Exception {
// get the list of GRSF Reviewers to alert them as well
RoleManager roleManager = new LiferayRoleManager();
@ -560,9 +536,9 @@ public class SocialCommunications {
List<String> reviewers = new ArrayList<String>(reviewersGcube.size());
for (GCubeUser gU : reviewersGcube) {
for(GCubeUser gU: reviewersGcube){
// if the user is a reviewer, then send the email just once
if (!gU.getUsername().equals(rInfo.getUserNameOriginalAdmin()))
if(!gU.getUsername().equals(rInfo.getUserNameOriginalAdmin()))
reviewers.add(gU.getUsername());
}
@ -572,31 +548,26 @@ public class SocialCommunications {
String currentScope = ScopeProvider.instance.get();
String tokenUser = SecurityTokenProvider.instance.get();
logger.info("Current scope for writeProductPost is " + currentScope + " and token is "
+ tokenUser.substring(0, 10) + "***************");
logger.info("Current scope for writeProductPost is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
String basePath = serviceUrl;
if (basePath == null) {
if(basePath == null){
logger.error("Unable to write a post because there is no social networking service available");
throw new Exception("Unable to discover the social networking service");
} else {
}else{
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
.build();) {
try(CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();){
String applicationToken = requireApplicationToken(serviceUrl);
String messageToEditor = EMAIL_EDITOR_REVERT.replace("RECORD_URL", rInfo.getRecordUrl())
.replace("ORIGINAL_USER", rInfo.getFullNameOriginalAdmin())
.replace("ADMIN_WHO_CHANGED", rInfo.getFullNameCurrentAdmin());
String messageToReviewer = EMAIL_REVIEWER_REVERT
.replace("ADMIN_WHO_CHANGED", rInfo.getFullNameCurrentAdmin())
.replace("RECORD_URL", rInfo.getRecordUrl())
.replace("ORIGINAL_USER", rInfo.getFullNameOriginalAdmin());
String messageToEditor = EMAIL_EDITOR_REVERT.replace("RECORD_URL", rInfo.getRecordUrl()).replace("ORIGINAL_USER", rInfo.getFullNameOriginalAdmin()).
replace("ADMIN_WHO_CHANGED", rInfo.getFullNameCurrentAdmin());
String messageToReviewer = EMAIL_REVIEWER_REVERT.replace("ADMIN_WHO_CHANGED", rInfo.getFullNameCurrentAdmin()).replace("RECORD_URL", rInfo.getRecordUrl()).
replace("ORIGINAL_USER", rInfo.getFullNameOriginalAdmin());
String subject = "Revert merge request on GRSF Record";
messageToEditor = messageToEditor.replace("<br>", "\n");
@ -620,7 +591,7 @@ public class SocialCommunications {
Map<String, Object> mapResponseWritePost = getResponseEntityAsJSON(response);
if (response.getStatusLine().getStatusCode() != 201) {
if (response.getStatusLine().getStatusCode() != 201){
logger.error("Failed to send message to editor : HTTP error code : "
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
}
@ -632,7 +603,7 @@ public class SocialCommunications {
reqMessage.put("subject", subject);
reqMessage.put("body", messageToReviewer);
recipients = new JSONArray();
for (String reviewer : reviewers) {
for(String reviewer: reviewers){
JSONObject recip = new JSONObject();
recip.put("id", reviewer);
recipients.add(recip);
@ -644,12 +615,12 @@ public class SocialCommunications {
response = client.execute(postRequest);
mapResponseWritePost = getResponseEntityAsJSON(response);
if (response.getStatusLine().getStatusCode() != 201) {
if (response.getStatusLine().getStatusCode() != 201){
logger.error("Failed to send message to editor : HTTP error code : "
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
}
} catch (Exception e) {
}catch(Exception e){
logger.error("Failed to send messages", e);
throw new Exception(e);
}
@ -659,28 +630,24 @@ public class SocialCommunications {
/**
* Create the url to be send for reverting the operation
*
* @param httpSession
* @param httpSession
* @return
* @throws Exception
* @throws Exception
*/
public static String getEncodedUrlManage(RevertableOperations operation, String administrator, long timestamp,
String uuid, String clientCurrenturl) throws Exception {
public static String getEncodedUrlManage(RevertableOperations operation, String administrator, long timestamp, String uuid, String clientCurrenturl) throws Exception{
logger.info("Request for revert link. Client current url is " + clientCurrenturl);
RevertOperationUrl operationUrl = new RevertOperationUrl(clientCurrenturl, administrator, timestamp, uuid,
operation);
RevertOperationUrl operationUrl = new RevertOperationUrl(clientCurrenturl, administrator, timestamp, uuid, operation);
String shortUrl = operationUrl.getShortUrl();
return shortUrl;
}
/**
* Convert the json response to a map
*
* @param response
* @return
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> getResponseEntityAsJSON(HttpResponse response) {
public static Map<String, Object> getResponseEntityAsJSON(HttpResponse response){
Map<String, Object> toReturn = null;
HttpEntity entity = response.getEntity();
@ -693,7 +660,7 @@ public class SocialCommunications {
ObjectMapper objectMapper = new ObjectMapper();
toReturn = objectMapper.readValue(jsonString, HashMap.class);
logger.debug("Map is " + toReturn);
} catch (Exception e) {
}catch(Exception e){
logger.error("Failed to read json object", e);
}
}

View File

@ -51,7 +51,6 @@ import com.liferay.portal.service.UserLocalServiceUtil;
/**
* Utility methods for GRSF Management panel widget.
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class Utils {
@ -60,36 +59,34 @@ public class Utils {
private static final String REGEX_UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
/**
* Return a map for converting a key to a namespace:key format by reading a
* generic resource.
*
* @param httpSession
* Return a map for converting a key to a namespace:key format by reading a generic resource.
* @param httpSession
* @return a map
*/
@SuppressWarnings("unchecked")
public static Map<String, String> getFieldToFieldNameSpaceMapping(HttpSession httpSession, String resourceName) {
public static Map<String, String> getFieldToFieldNameSpaceMapping(HttpSession httpSession, String resourceName){
// check if this information is available in session
String sessionKey = ScopeProvider.instance.get() + resourceName;
if (httpSession.getAttribute(sessionKey) != null)
if(httpSession.getAttribute(sessionKey) != null)
return (Map<String, String>) httpSession.getAttribute(sessionKey);
Map<String, String> namespacesMap = new HashMap<String, String>(); // e.g. fishery_identity:Short Title -> Short
// Title
Map<String, String> namespacesMap = new HashMap<String, String>(); // e.g. fishery_identity:Short Title -> Short Title
try {
Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource "
+ "where $profile/Profile/SecondaryType/string() eq '" + "ApplicationProfile"
+ "' and $profile/Profile/Name/string() " + " eq '" + resourceName + "'" + "return $profile");
Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource " +
"where $profile/Profile/SecondaryType/string() eq '"+ "ApplicationProfile" + "' and $profile/Profile/Name/string() " +
" eq '" + resourceName + "'" +
"return $profile");
DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q);
if (appProfile == null || appProfile.size() == 0)
if (appProfile == null || appProfile.size() == 0)
throw new Exception("Your applicationProfile is not registered in the infrastructure");
else {
String elem = appProfile.get(0);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
XPathHelper helper = new XPathHelper(node);
@ -97,18 +94,17 @@ public class Utils {
NodeList nodeListModifiedKeys = helper.evaluateForNodes("//modifiedKey");
int sizeKeys = nodeListKeys != null ? nodeListKeys.getLength() : 0;
int sizeKeysModifed = nodeListModifiedKeys != null ? nodeListModifiedKeys.getLength() : 0;
if (sizeKeys != sizeKeysModifed)
if(sizeKeys != sizeKeysModifed)
throw new Exception("Malformed XML");
logger.debug("Size is " + sizeKeys);
for (int i = 0; i < sizeKeys; i++) {
namespacesMap.put(nodeListModifiedKeys.item(i).getTextContent(),
nodeListKeys.item(i).getTextContent());
namespacesMap.put(nodeListModifiedKeys.item(i).getTextContent(), nodeListKeys.item(i).getTextContent());
}
}
logger.debug("Map is " + namespacesMap);
// put them into session for speeding up the operations
httpSession.setAttribute(sessionKey, namespacesMap);
httpSession.setAttribute(sessionKey, namespacesMap);
return namespacesMap;
} catch (Exception e) {
logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", e);
@ -117,9 +113,7 @@ public class Utils {
}
/**
* Replace the extras' keys if needed, e.g. fishery_identity:Short Title ->
* Short Title
*
* Replace the extras' keys if needed, e.g. fishery_identity:Short Title -> Short Title
* @param extrasAsPairs
* @param namespaces
* @return a map with replaced key value pairs
@ -135,7 +129,7 @@ public class Utils {
String replacedKey = namespaces.containsKey(pairKey) ? namespaces.get(pairKey) : pairKey;
List<String> values = null;
if (toReturn.containsKey(replacedKey))
if(toReturn.containsKey(replacedKey))
values = toReturn.get(replacedKey);
else
values = new ArrayList<String>(1);
@ -149,11 +143,10 @@ public class Utils {
/**
* Get the extras of this dataset as hashmap
*
* @param extrasAsPairs
* @return
*/
public static Map<String, List<String>> getExtrasAsHashMap(List<CkanPair> extrasAsPairs) {
public static Map<String, List<String>> getExtrasAsHashMap(List<CkanPair> extrasAsPairs){
Map<String, List<String>> toReturn = new HashMap<String, List<String>>();
@ -162,7 +155,7 @@ public class Utils {
String pairValue = ckanPair.getValue();
List<String> values = null;
if (toReturn.containsKey(pairKey))
if(toReturn.containsKey(pairKey))
values = toReturn.get(pairKey);
else
values = new ArrayList<String>(1);
@ -176,66 +169,68 @@ public class Utils {
/**
* Send an update for this bean
*
* @param baseUrl
* @param bean
* @param username
* @param catalogue
* @param username
* @param catalogue
* @return true on success, false otherwise
*/
public static void updateRecord(String serviceUrl, final ManageProductBean bean, final DataCatalogue catalogue,
final String username, final String fullName, final HttpServletRequest httpServletRequest,
final long groupId, final String context, final String token) throws Exception {
public static void updateRecord(
String serviceUrl,
final ManageProductBean bean,
final DataCatalogue catalogue,
final String username,
final String fullName,
final HttpServletRequest httpServletRequest,
final long groupId,
final String context,
final String token) throws Exception{
if (serviceUrl == null)
if(serviceUrl == null)
throw new IllegalArgumentException("GRSF Updater service url cannot be null");
if (bean == null)
if(bean == null)
throw new IllegalArgumentException("Item bean to manage cannot be null");
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();) {
// ADDED BY FRANCESCO
if (Utils.isIntoPortal()) {
try(CloseableHttpClient httpClient = HttpClientBuilder.create().build();){
//ADDED BY FRANCESCO
if(Utils.isIntoPortal()) {
// send update to the knowledge base
GRSFUpdaterServiceClient.updateKB(httpClient, serviceUrl, bean, catalogue, username, fullName);
// if there are merges, update the status of the other involved records
if (bean.isMergesInvolved())
updateStatusInvolvedRecords(bean, username, catalogue);
if(bean.isMergesInvolved())
updateStatusInvolvedRecords(bean, catalogue);
}
// require social networking url
final String baseUrlSocial = SocialCommunications.getBaseUrlSocialService(httpServletRequest);
// and the user current browser url
final String currentBrowserUrl = Utils.getCurrentClientUrl(httpServletRequest).split("\\?")[0]; // ignore
// other
// parameters
final String currentBrowserUrl = Utils.getCurrentClientUrl(httpServletRequest).split("\\?")[0]; // ignore other parameters
// manage interactions through a separated thread but set there security token
// and context (and then reset them)
// manage interactions through a separated thread but set there security token and context (and then reset them)
Thread t = new Thread(new Runnable() {
@Override
public void run() {
ScopeProvider.instance.set(context);
SecurityTokenProvider.instance.set(token);
try {
try{
// send email to Editors and Reviewers
SocialCommunications.sendEmailAdministrators(baseUrlSocial, bean, catalogue, username, fullName,
SocialCommunications.sendEmailAdministrators(baseUrlSocial, bean, catalogue, username, fullName,
groupId, currentBrowserUrl, bean.isMergesInvolved());
// create a post about the operation
SocialCommunications.writeProductPost(baseUrlSocial, bean, username, fullName, false,
currentBrowserUrl);
// create a post about the operation
SocialCommunications.writeProductPost(baseUrlSocial, bean, username, fullName, false, currentBrowserUrl);
} catch (Exception e) {
}catch(Exception e){
logger.error("Something failed while alerting editors/reviewers", e);
} finally {
}finally{
ScopeProvider.instance.reset();
SecurityTokenProvider.instance.reset();
}
@ -243,7 +238,7 @@ public class Utils {
});
t.start();
} catch (Exception e) {
}catch(Exception e){
logger.error("Unable to update this Item ", e);
throw e;
}
@ -251,16 +246,14 @@ public class Utils {
/**
* Revert operation and alert admins/vre users
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
* @param httpClient
* @param baseUrl
* @param fullName
* @param uuid
*/
public static void revertOperation(CloseableHttpClient httpClient, String baseUrl,
HttpServletRequest httpServletRequest, final RevertableOperationInfo rInfo, final String token,
final String context, final long groupId) throws Exception {
public static void revertOperation(CloseableHttpClient httpClient, String baseUrl, HttpServletRequest httpServletRequest,
final RevertableOperationInfo rInfo, final String token, final String context, final long groupId) throws Exception{
GRSFUpdaterServiceClient.revertOperation(httpClient, baseUrl, rInfo.getFullNameCurrentAdmin(), rInfo.getUuid());
@ -268,18 +261,16 @@ public class Utils {
final String baseUrlSocial = SocialCommunications.getBaseUrlSocialService(httpServletRequest);
// and the user current browser url
final String currentBrowserUrl = Utils.getCurrentClientUrl(httpServletRequest).split("\\?")[0]; // ignore other
// parameters
// manage interactions through a separated thread but set there security token
// and context (and then reset them)
final String currentBrowserUrl = Utils.getCurrentClientUrl(httpServletRequest).split("\\?")[0]; // ignore other parameters
// manage interactions through a separated thread but set there security token and context (and then reset them)
Thread t = new Thread(new Runnable() {
@Override
public void run() {
ScopeProvider.instance.set(context);
SecurityTokenProvider.instance.set(token);
try {
try{
// write post about this
SocialCommunications.writePostOnRevert(baseUrlSocial, rInfo, false, currentBrowserUrl);
@ -287,9 +278,9 @@ public class Utils {
// alert who's involved
SocialCommunications.sendEmailAdministratorsOnOperationReverted(baseUrlSocial, rInfo, groupId);
} catch (Exception e) {
}catch(Exception e){
logger.error("Something failed while alerting editors/reviewers", e);
} finally {
}finally{
ScopeProvider.instance.reset();
SecurityTokenProvider.instance.reset();
}
@ -301,26 +292,23 @@ public class Utils {
}
/**
* Update the status of the involved records to "to be merged".
*
* @param bean the bean
* @param username the username
* @param catalogue the catalogue
* @throws Exception the exception
* Update the status of the involved records to "to be merged"
* @param bean
* @param catalogue
* @param username
* @param fullName
* @throws Exception
*/
private static void updateStatusInvolvedRecords(ManageProductBean bean, String username, DataCatalogue catalogue)
throws Exception {
private static void updateStatusInvolvedRecords(ManageProductBean bean, DataCatalogue catalogue) throws Exception {
// String context = ScopeProvider.instance.get();
// String sysApi = fetchSysAPI(context);
for (SimilarGRSFRecord s : bean.getSimilarGrsfRecords()) {
if (s.isSuggestedMerge()) {
String context = ScopeProvider.instance.get();
String sysApi = fetchSysAPI(context);
for(SimilarGRSFRecord s: bean.getSimilarGrsfRecords()){
if(s.isSuggestedMerge()){
String productId = s.getKnowledgeBaseId();
Map<String, List<String>> updateStatus = new HashMap<String, List<String>>(1);
updateStatus.put(Constants.STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY,
Arrays.asList(Status.To_be_Merged.getOrigName()));
// Fixing bug #23561, passing username (instead of sysAPI)
catalogue.patchProductCustomFields(productId, username, updateStatus, true);
updateStatus.put(Constants.STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY, Arrays.asList(Status.To_be_Merged.getOrigName()));
catalogue.patchProductCustomFields(productId, sysApi, updateStatus, true);
}
}
@ -328,48 +316,45 @@ public class Utils {
/**
* Get the scope in which ckan information needs to be discovered from the url
*
* @param httpServletRequest
* @return
*/
public static String getScopeFromClientUrl(HttpServletRequest httpServletRequest) {
public static String getScopeFromClientUrl(HttpServletRequest httpServletRequest){
if (httpServletRequest == null)
if(httpServletRequest == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
String scopeToReturn = null;
try {
try{
String clientUrl = getCurrentClientUrl(httpServletRequest).split("\\?")[0];
logger.debug("Client url is " + clientUrl);
// check if this information is in session, otherwise set it and return
HttpSession session = httpServletRequest.getSession();
if ((scopeToReturn = (String) session.getAttribute(clientUrl)) != null) {
if((scopeToReturn = (String) session.getAttribute(clientUrl)) != null){
logger.debug("Scope to return is " + scopeToReturn);
} else {
}else{
// ask to the ckan library and set it
scopeToReturn = ApplicationProfileScopePerUrlReader.getScopePerUrl(clientUrl);
logger.debug("Scope to return is " + scopeToReturn);
session.setAttribute(clientUrl, scopeToReturn);
}
} catch (Exception e) {
}catch(Exception e){
scopeToReturn = getCurrentContext(httpServletRequest, true);
logger.warn(
"Failed to determine the scope from the client url, returning the current one: " + scopeToReturn);
logger.warn("Failed to determine the scope from the client url, returning the current one: " + scopeToReturn);
}
return scopeToReturn;
}
/**
* Needed to get the url of the client
*
* @param httpServletRequest the httpServletRequest object
* @return the instance of the user
* @return the instance of the user
* @see the url at client side
*/
public static String getCurrentClientUrl(HttpServletRequest httpServletRequest) {
if (httpServletRequest == null)
if(httpServletRequest == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
return httpServletRequest.getHeader(Constants.GCUBE_REQUEST_URL);
@ -377,20 +362,19 @@ public class Utils {
/**
* Retrieve the current scope by using the portal manager
*
* @param b
* @param b
* @return a GcubeUser object
*/
public static String getCurrentContext(HttpServletRequest request, boolean setInThread) {
public static String getCurrentContext(HttpServletRequest request, boolean setInThread){
if (request == null)
if(request == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
PortalContext pContext = PortalContext.getConfiguration();
String context = pContext.getCurrentScope(request);
logger.debug("Returning context " + context);
if (context != null && setInThread)
if(context != null && setInThread)
ScopeProvider.instance.set(context);
return context;
@ -398,12 +382,11 @@ public class Utils {
/**
* Retrieve the current user by using the portal manager
*
* @return a GcubeUser object
*/
public static GCubeUser getCurrentUser(HttpServletRequest request) {
public static GCubeUser getCurrentUser(HttpServletRequest request){
if (request == null)
if(request == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
PortalContext pContext = PortalContext.getConfiguration();
@ -413,18 +396,17 @@ public class Utils {
}
/**
* Exploits the fact that in GRSF the url of a record contains the name (which
* is unique) of the record itself.
* Exploits the fact that in GRSF the url of a record contains the name (which is unique) of the record itself.
*
* @param url the url
* @param clg the clg
* @param url the url
* @param clg the clg
* @param username the username
* @return the dataset from url
* @throws Exception the exception
*/
public static CkanDataset getDatasetFromUrl(String url, DataCatalogue clg, String username) throws Exception {
public static CkanDataset getDatasetFromUrl(String url, DataCatalogue clg, String username) throws Exception{
if (url == null || url.isEmpty())
if(url == null || url.isEmpty())
return null;
// Parse url
@ -443,16 +425,14 @@ public class Utils {
}
/**
* Exploits the fact that in GRSF the url of a record contains the name (which
* is unique) of the record itself
*
* Exploits the fact that in GRSF the url of a record contains the name (which is unique) of the record itself
* @param url
* @param clg
* @return
*/
public static String getDatasetKnowledgeBaseIdFromUrl(String url) {
public static String getDatasetKnowledgeBaseIdFromUrl(String url){
if (url == null || url.isEmpty())
if(url == null || url.isEmpty())
return null;
// Parse url
@ -470,38 +450,39 @@ public class Utils {
return null;
}
/**
* Get a {@link SimilarGRSFRecord} from a json string
*
* @param json
* @return {@link SimilarGRSFRecord}
* @throws ParseException
* @throws ParseException
*/
public static SimilarGRSFRecord similarGRSFRecordFromJson(String json, DataCatalogue ctl, String username,
HttpSession httpSession) throws ParseException {
public static SimilarGRSFRecord similarGRSFRecordFromJson(String json, DataCatalogue ctl, String username, HttpSession httpSession) throws ParseException{
if (json == null)
if(json == null)
return null;
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(json);
JSONObject object = (JSONObject)parser.parse(json);
String uuid = getDatasetKnowledgeBaseIdFromUrl((String) object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_URL));
CkanDataset dataset = ctl.getDataset(uuid, username);
String uuid = getDatasetKnowledgeBaseIdFromUrl((String)object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_URL));
CkanDataset dataset = ctl.getDataset(uuid,username);
boolean isStock = dataset.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY).contains(Product_Type.STOCK.getOrigName());
Map<String, String> fieldsNamespacesMap =
Utils.getFieldToFieldNameSpaceMapping(httpSession, isStock ?
Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK : Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(dataset.getExtras(), fieldsNamespacesMap);
boolean isStock = dataset.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY)
.contains(Product_Type.STOCK.getOrigName());
Map<String, String> fieldsNamespacesMap = Utils.getFieldToFieldNameSpaceMapping(httpSession,
isStock ? Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK
: Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(dataset.getExtras(),
fieldsNamespacesMap);
return new SimilarGRSFRecord(uuid, (String) object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_DESCRIPTION),
(String) object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_NAME), dataset.getTitle(),
(String) object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_URL),
return new SimilarGRSFRecord(
uuid,
(String)object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_DESCRIPTION),
(String)object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_NAME),
dataset.getTitle(),
(String)object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_URL),
extrasWithoutNamespaces.get(Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY).get(0),
extrasWithoutNamespaces.get(Constants.DOMAIN_CUSTOM_KEY).get(0));
extrasWithoutNamespaces.get(Constants.DOMAIN_CUSTOM_KEY).get(0)
);
}
@ -514,7 +495,7 @@ public class Utils {
try {
UserLocalServiceUtil.getService();
return true;
} catch (Exception ex) {
}catch (Exception ex) {
logger.debug("Development Mode ON");
return false;
}
@ -523,45 +504,53 @@ public class Utils {
/**
* Get Connected bean from record.
*
* @param destUrl the dest url
* @param clg the clg
* @param username the username
* @param destUrl the dest url
* @param clg the clg
* @param username the username
* @param httpSession the http session
* @return the connected bean
* @throws ParseException the parse exception
*/
public static ConnectedBean connectedBeanRecordFromUrl(String destUrl, DataCatalogue clg, String username,
HttpSession httpSession) throws ParseException {
public static ConnectedBean connectedBeanRecordFromUrl(
String destUrl,
DataCatalogue clg,
String username,
HttpSession httpSession
) throws ParseException {
if (destUrl == null)
if(destUrl == null)
return null;
String connectedBeanUuid = getDatasetKnowledgeBaseIdFromUrl(destUrl);
CkanDataset destDataset = clg.getDataset(connectedBeanUuid, username);
boolean isStock = destDataset.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY)
.contains(Product_Type.STOCK.getOrigName());
Map<String, String> fieldsNamespacesMap = Utils.getFieldToFieldNameSpaceMapping(httpSession,
isStock ? Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK
: Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(destDataset.getExtras(),
fieldsNamespacesMap);
CkanDataset destDataset = clg.getDataset(connectedBeanUuid,username);
boolean isStock = destDataset.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY).contains(Product_Type.STOCK.getOrigName());
Map<String, String> fieldsNamespacesMap =
Utils.getFieldToFieldNameSpaceMapping(httpSession, isStock ?
Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK : Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(destDataset.getExtras(), fieldsNamespacesMap);
String semanticId = extrasWithoutNamespaces.get(Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY).get(0);
String destDomain = extrasWithoutNamespaces.get(Constants.DOMAIN_CUSTOM_KEY).get(0);
String shortName = extrasWithoutNamespaces.get(Constants.SHORT_NAME_CUSTOM_KEY).get(0);
String description = destDataset.getNotes();
return new ConnectedBean(connectedBeanUuid, description, shortName, destDataset.getTitle(), destUrl, semanticId,
destDomain);
return new ConnectedBean(
connectedBeanUuid,
description,
shortName,
destDataset.getTitle(),
destUrl,
semanticId,
destDomain
);
}
/**
* Fetch the sysadmin key from the IS for this catalogue
*
* @return
* @throws Exception
* @throws Exception
*/
public static String fetchSysAPI(String context) throws Exception {
public static String fetchSysAPI(String context) throws Exception{
DataCatalogueRunningCluster catalogueRunningInstance = new DataCatalogueRunningCluster(context);
return catalogueRunningInstance.getSysAdminToken();
}

View File

@ -1,40 +1,35 @@
package org.gcube.datacatalogue.grsf_manage_widget.shared.ex;
import java.io.Serializable;
import org.gcube.datacatalogue.common.enums.Status;
/**
* The Class GRSFRecordAlreadyManagedStatusException.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
*
* Mar 21, 2019
* Mar 21, 2019
*/
public class GRSFRecordAlreadyManagedStatusException extends Exception implements Serializable {
public class GRSFRecordAlreadyManagedStatusException extends Exception{
/**
*
*/
private static final long serialVersionUID = -2034802685606929315L;
private Status status;
public GRSFRecordAlreadyManagedStatusException() {
}
/**
* Instantiates a new GRSF record already managed status exception.
*
* @param theStatus the the status
* @param arg0 the arg 0
* @param arg0 the arg 0
*/
public GRSFRecordAlreadyManagedStatusException(Status theStatus, String arg0) {
public GRSFRecordAlreadyManagedStatusException(Status theStatus, String arg0){
super(arg0);
this.status = theStatus;
}
/**
* Gets the status.
*

View File

@ -1,14 +1,12 @@
package org.gcube.datacatalogue.grsf_manage_widget.shared.ex;
import java.io.Serializable;
/**
* This is thrown when the Manage product is pushed on a product that has a
* Record Type field of Source or none.
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
* This is thrown when the Manage product is pushed on a product that has
* a Record Type field of Source or none.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class NoGRSFRecordException extends Exception implements Serializable {
public class NoGRSFRecordException extends Exception {
private static final long serialVersionUID = 721315478405659218L;
private String errorMessage;