Merge pull request 'ref 19081: DM Pool Manager uses a deprecated social networking api' (#1) from Feature/19081 into master

This commit is contained in:
Giancarlo Panichi 2020-04-16 16:34:14 +02:00
commit 9b22a80c87
10 changed files with 299 additions and 296 deletions

View File

@ -17,7 +17,11 @@
<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/resources"/> <classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes> <attributes>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>

View File

@ -2,4 +2,5 @@ eclipse.preferences.version=1
encoding***REMOVED***src/main/java=UTF-8 encoding***REMOVED***src/main/java=UTF-8
encoding***REMOVED***src/main/resources=UTF-8 encoding***REMOVED***src/main/resources=UTF-8
encoding***REMOVED***src/test/java=UTF-8 encoding***REMOVED***src/test/java=UTF-8
encoding***REMOVED***src/test/resources=UTF-8
encoding/<project>=UTF-8 encoding/<project>=UTF-8

View File

@ -1,5 +1,5 @@
<?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="dataminer-pool-manager-2.6.0-SNAPSHOT"> <wb-module deploy-name="dataminer-pool-manager-2.7.0-SNAPSHOT">
<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"/>

View File

@ -1,4 +1,7 @@
<ReleaseNotes> <ReleaseNotes>
<Changeset component="org.gcube.dataanalysis.dataminer-pool-manager.2-7-0" date="2020-04-16">
<Change>Updated to new Social Networking API [ticket #19081]</Change>
</Changeset>
<Changeset component="org.gcube.dataanalysis.dataminer-pool-manager.2-6-0" date="2019-12-11"> <Changeset component="org.gcube.dataanalysis.dataminer-pool-manager.2-6-0" date="2019-12-11">
<Change>Updated to Git and Jenkins</Change> <Change>Updated to Git and Jenkins</Change>
<Change>Knime 4.1 added [ticket #18190]</Change> <Change>Knime 4.1 added [ticket #18190]</Change>

View File

@ -12,7 +12,7 @@
<groupId>org.gcube.dataanalysis</groupId> <groupId>org.gcube.dataanalysis</groupId>
<artifactId>dataminer-pool-manager</artifactId> <artifactId>dataminer-pool-manager</artifactId>
<packaging>war</packaging> <packaging>war</packaging>
<version>2.6.0</version> <version>2.7.0-SNAPSHOT</version>
<name>dataminer-pool-manager</name> <name>dataminer-pool-manager</name>
<description>DataMiner Pool Manager is a service to support the integration of algorithms in D4Science Infrastructure</description> <description>DataMiner Pool Manager is a service to support the integration of algorithms in D4Science Infrastructure</description>

View File

@ -1,7 +1,9 @@
package org.gcube.dataanalysis.dataminer.poolmanager.clients.configuration; package org.gcube.dataanalysis.dataminer.poolmanager.clients.configuration;
***REMOVED*** ***REMOVED***
import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
***REMOVED***
import java.util.Properties; import java.util.Properties;
***REMOVED*** ***REMOVED***
@ -11,105 +13,90 @@ import org.gcube.dataanalysis.dataminer.poolmanager.clients.configuration.Config
***REMOVED*** ***REMOVED***
***REMOVED*** ***REMOVED***
public class DMPMClientConfiguratorManager public class DMPMClientConfiguratorManager ***REMOVED***
***REMOVED*** ***REMOVED***
private final Logger logger;
private Properties defaultAdmins; private Properties defaultAdmins;
private String admins;
static DMPMClientConfiguratorManager instance; static DMPMClientConfiguratorManager instance;
private ScopedCacheMap cacheMap; private ScopedCacheMap cacheMap;
private DMPMClientConfiguratorManager () private DMPMClientConfiguratorManager() ***REMOVED***
***REMOVED***
this.admins = null;
this.cacheMap = new ScopedCacheMap(); this.cacheMap = new ScopedCacheMap();
this.logger = LoggerFactory.getLogger(DMPMClientConfiguratorManager.class); this.logger = LoggerFactory.getLogger(DMPMClientConfiguratorManager.class);
this.defaultAdmins = new Properties(); this.defaultAdmins = new Properties();
try try ***REMOVED***
***REMOVED***
this.defaultAdmins.load(this.getClass().getResourceAsStream("/default.admins")); this.defaultAdmins.load(this.getClass().getResourceAsStream("/default.admins"));
this.logger.debug("Default users successfully loaded"); this.logger.debug("Default users successfully loaded");
***REMOVED*** catch (Exception e) ***REMOVED*** catch (Exception e) ***REMOVED***
***REMOVED*** this.logger.error("Unable to get default users", e);
this.logger.error("Unable to get default users",e);
***REMOVED*** ***REMOVED***
***REMOVED*** ***REMOVED***
private ClientConfigurationCache getCurrentCache () private ClientConfigurationCache getCurrentCache() ***REMOVED***
***REMOVED***
String currentScope = ScopeProvider.instance.get(); String currentScope = ScopeProvider.instance.get();
this.logger.debug("Current scope = "+currentScope); this.logger.debug("Current scope = " + currentScope);
this.logger.debug("Getting current configuration cache"); this.logger.debug("Getting current configuration cache");
ClientConfigurationCache cache = this.cacheMap.get(currentScope); ClientConfigurationCache cache = this.cacheMap.get(currentScope);
if (cache == null) if (cache == null) ***REMOVED***
***REMOVED***
this.logger.debug("Cache not created yet, creating..."); this.logger.debug("Cache not created yet, creating...");
cache = new ClientConfigurationCache (); cache = new ClientConfigurationCache();
this.cacheMap.put(currentScope, cache); this.cacheMap.put(currentScope, cache);
***REMOVED*** ***REMOVED***
return cache; return cache;
***REMOVED*** ***REMOVED***
public static DMPMClientConfiguratorManager getInstance() ***REMOVED***
public static DMPMClientConfiguratorManager getInstance () if (instance == null)
***REMOVED*** instance = new DMPMClientConfiguratorManager();
if (instance == null) instance = new DMPMClientConfiguratorManager();
return instance; return instance;
***REMOVED*** ***REMOVED***
public Configuration getProductionConfiguration () public Configuration getProductionConfiguration() ***REMOVED***
***REMOVED***
return new ConfigurationImpl(CONFIGURATIONS.PROD, getCurrentCache()); return new ConfigurationImpl(CONFIGURATIONS.PROD, getCurrentCache());
***REMOVED*** ***REMOVED***
public Configuration getStagingConfiguration () public Configuration getStagingConfiguration() ***REMOVED***
***REMOVED***
return new ConfigurationImpl(CONFIGURATIONS.STAGE, getCurrentCache()); return new ConfigurationImpl(CONFIGURATIONS.STAGE, getCurrentCache());
***REMOVED*** ***REMOVED***
public String getDefaultAdmins () public List<String> getDefaultAdmins() ***REMOVED***
***REMOVED*** List<String> admins = new ArrayList<String>();
if (this.admins == null && this.defaultAdmins.isEmpty()) this.admins= "ciro.formisano";
else if (admins == null) if (defaultAdmins == null || defaultAdmins.isEmpty()) ***REMOVED***
admins.add("statistical.manager");
***REMOVED*** else ***REMOVED***
Iterator<Object> keys = this.defaultAdmins.keySet().iterator();
while (keys.hasNext()) ***REMOVED***
String key = (String) keys.next();
admins.add(defaultAdmins.getProperty(key));
***REMOVED*** ***REMOVED***
Iterator<Object> keys = this.defaultAdmins.keySet().iterator();
StringBuilder response = new StringBuilder();
while (keys.hasNext())
***REMOVED***
String key = (String) keys.next();
response.append(this.defaultAdmins.getProperty(key)).append(", ");
***REMOVED***
this.admins = response.substring(0, response.length()-2);
***REMOVED*** ***REMOVED***
this.logger.debug("Default admins list "+this.admins); this.logger.debug("Default admins list: " + admins);
return this.admins; return admins;
***REMOVED*** ***REMOVED***
public static void main(String[] args) throws IOException, SVNException ***REMOVED*** public static void main(String[] args) throws IOException, SVNException ***REMOVED***
DMPMClientConfiguratorManager a = new DMPMClientConfiguratorManager(); DMPMClientConfiguratorManager a = new DMPMClientConfiguratorManager();
ScopeProvider.instance.set("/gcube/devNext/NextNext"); ScopeProvider.instance.set("/gcube/devNext/NextNext");
***REMOVED***SecurityTokenProvider.instance.set("***REMOVED***"); ***REMOVED*** SecurityTokenProvider.instance.set("***REMOVED***");
System.out.println("RESULT 1"+a.getStagingConfiguration().getSVNCRANDepsList()); System.out.println("RESULT 1" + a.getStagingConfiguration().getSVNCRANDepsList());
System.out.println("RESULT 2"+a.getProductionConfiguration().getRepository()); System.out.println("RESULT 2" + a.getProductionConfiguration().getRepository());
System.out.println("RESULT 3"+a.getStagingConfiguration().getSVNRepository().getPath()); System.out.println("RESULT 3" + a.getStagingConfiguration().getSVNRepository().getPath());
***REMOVED***System.out.println(a.getRepo()); ***REMOVED*** System.out.println(a.getRepo());
***REMOVED***System.out.println(a.getAlgoRepo()); ***REMOVED*** System.out.println(a.getAlgoRepo());
***REMOVED***System.out.println(a.getSVNRepo()); ***REMOVED*** System.out.println(a.getSVNRepo());
***REMOVED*** ***REMOVED***
***REMOVED*** ***REMOVED***

View File

@ -8,12 +8,10 @@ import java.io.BufferedReader;
***REMOVED*** ***REMOVED***
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
***REMOVED*** ***REMOVED***
***REMOVED*** ***REMOVED***
import java.net.URLConnection; import java.net.URLConnection;
import java.net.URLEncoder; import java.util.ArrayList;
import java.util.LinkedList;
***REMOVED*** ***REMOVED***
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -24,140 +22,134 @@ import org.apache.http.util.EntityUtils;
import org.gcube.common.authorization.library.AuthorizationEntry; import org.gcube.common.authorization.library.AuthorizationEntry;
***REMOVED*** ***REMOVED***
import org.gcube.common.resources.gcore.GCoreEndpoint; import org.gcube.common.resources.gcore.GCoreEndpoint;
***REMOVED***
import org.gcube.dataanalysis.dataminer.poolmanager.clients.configuration.DMPMClientConfiguratorManager; import org.gcube.dataanalysis.dataminer.poolmanager.clients.configuration.DMPMClientConfiguratorManager;
import org.gcube.dataanalysis.dataminer.poolmanager.util.exception.EMailException; import org.gcube.dataanalysis.dataminer.poolmanager.util.exception.EMailException;
import org.gcube.resources.discovery.client.api.DiscoveryClient; import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery; import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
***REMOVED*** ***REMOVED***
***REMOVED*** ***REMOVED***
public class SendMail ***REMOVED***
public class SendMail ***REMOVED*** private Logger logger = LoggerFactory.getLogger(SendMail.class);
private final String WRITE_MESSAGE_ADDRESS_PATH = "2/messages/write-message?gcube-token=",
USER_ROLES_ADDRESS_PATH = "2/users/get-usernames-by-role?role-name=DataMiner-Manager&gcube-token=",
SOCIAL_SERVICE_QUERY_CONDITION = "$resource/Profile/ServiceName/text() eq 'SocialNetworking'",
SOCIAL_SERVICE_URI = "jersey-servlet", JSON_MIME_TYPE = "application/json";
private Logger logger; private String socialServiceAddress;
private final String WRITE_MESSAGE_ADDRESS_PATH ="messages/writeMessageToUsers?gcube-token=",
USER_ROLES_ADDRESS_PATH ="2/users/get-usernames-by-role?role-name=DataMiner-Manager&gcube-token=",
ENCODING = "UTF-8",
SENDER_PARAMETER_FORMAT = "&sender=dataminer&recipients=%s&subject=%s&body=%s",
SOCIAL_SERVICE_QUERY_CONDITION ="$resource/Profile/ServiceName/text() eq 'SocialNetworking'",
SOCIAL_SERVICE_URI="jersey-servlet",
JSON_MIME_TYPE = "application/json";
public SendMail() ***REMOVED*** public SendMail() ***REMOVED***
this.logger = LoggerFactory.getLogger(SendMail.class);
***REMOVED*** ***REMOVED***
private String getRequestMessage (String addressPath) public void sendNotification(String subject, String body) throws EMailException ***REMOVED***
***REMOVED*** logger.debug("SendNotification");
String serviceAddress = this.getSocialService(); logger.debug("Notification Subject: " + subject);
StringBuilder requestMessageBuilder = new StringBuilder(serviceAddress); logger.debug("Notification Body: " + body);
if (!serviceAddress.endsWith("/")) requestMessageBuilder.append('/'); retrieveSocialService();
String postBody = createPostBody(subject, body);
String requestForMessage = getRequestMessage(WRITE_MESSAGE_ADDRESS_PATH);
sendPostRequest(requestForMessage, postBody);
requestMessageBuilder.append(addressPath).append(SecurityTokenProvider.instance.get());
String requestForMessage = requestMessageBuilder.toString();
this.logger.debug("Request "+requestForMessage);
return requestForMessage;
***REMOVED*** ***REMOVED***
public void sendNotification(String subject, String body) throws EMailException private String createPostBody(String subject, String body) throws EMailException ***REMOVED***
***REMOVED*** try ***REMOVED***
this.logger.debug("Sending mail notification for "+subject); List<String> recipientsList = getRecipients();
this.logger.debug("Body "+body); if (recipientsList == null || recipientsList.isEmpty()) ***REMOVED***
logger.error("Invalid recipient list: " + recipientsList);
throw new EMailException("Unable to send email notification. Invalid recipient list:" + recipientsList);
***REMOVED***AnalysisLogger.getLogger().debug("Emailing System->Request url is going to be " + requestForMessage);
***REMOVED*** put the sender, the recipients, subject and body of the mail here
try
***REMOVED*** ***REMOVED***
subject = URLEncoder.encode(subject, ENCODING);
body = URLEncoder.encode(body, ENCODING); ***REMOVED*** ***REMOVED***"subject": "subject-content", "body": "body-content",
***REMOVED*** ***REMOVED*** "recipients":[***REMOVED***"id":"userid"***REMOVED***]***REMOVED***
catch (UnsupportedEncodingException e)
JSONObject data = new JSONObject();
data.put("subject", subject);
data.put("body", body);
JSONArray recipients = new JSONArray();
for (String recipient : recipientsList) ***REMOVED***
JSONObject d = new JSONObject();
d.put("id", recipient);
recipients.put(d);
***REMOVED*** ***REMOVED***
data.put("recipients", recipients);
logger.info("Post Body: " + data);
return data.toString();
***REMOVED*** catch (EMailException e) ***REMOVED***
throw e;
***REMOVED*** catch (Throwable e) ***REMOVED***
logger.error("Error creating the notification body: " + e.getLocalizedMessage(), e);
throw new EMailException(e);
***REMOVED***
***REMOVED***
private void retrieveSocialService() throws EMailException ***REMOVED***
try ***REMOVED***
SimpleQuery query = queryFor(GCoreEndpoint.class);
query.addCondition(SOCIAL_SERVICE_QUERY_CONDITION);
DiscoveryClient<GCoreEndpoint> client = clientFor(GCoreEndpoint.class);
List<GCoreEndpoint> resources = client.submit(query);
socialServiceAddress = resources.get(0).profile().endpointMap().get(SOCIAL_SERVICE_URI).uri().toString();
logger.info("Retrieved Social Service Address: " + socialServiceAddress);
if (socialServiceAddress == null || socialServiceAddress.isEmpty()) ***REMOVED***
throw new EMailException(
"Unable to send email notification. Invalid address in GCoreEndpoint resource on IS.");
***REMOVED***
***REMOVED*** catch (EMailException e) ***REMOVED***
logger.error(e.getLocalizedMessage(), e);
throw e;
***REMOVED*** catch (Throwable e) ***REMOVED***
logger.error(e.getLocalizedMessage(), e);
throw new EMailException(e); throw new EMailException(e);
***REMOVED*** ***REMOVED***
String requestForMessage = getRequestMessage(WRITE_MESSAGE_ADDRESS_PATH);
requestForMessage = requestForMessage.replace("http:***REMOVED***", "https:***REMOVED***").replace(":80", "");
String requestParameters = String.format(SENDER_PARAMETER_FORMAT, this.getAdmins(), subject , body);
String response = this.sendPostRequest(requestForMessage, requestParameters);
***REMOVED***AnalysisLogger.getLogger().debug("Emailing System->Emailing response OK ");
if (response == null) throw new EMailException();
***REMOVED*** ***REMOVED***
***REMOVED*** public void notifySubmitter(String a, String b) throws Exception ***REMOVED*** private String getRequestMessage(String addressPath) ***REMOVED***
***REMOVED*** NotificationHelper nh = new NotificationHelper(); StringBuilder requestMessageBuilder = new StringBuilder(socialServiceAddress);
***REMOVED*** super.sendNotification(nh.getSubject(),
***REMOVED*** nh.getBody());
***REMOVED*** ***REMOVED***
public String username(String token) throws ObjectNotFound, Exception ***REMOVED*** if (!socialServiceAddress.endsWith("/"))
requestMessageBuilder.append('/');
requestMessageBuilder.append(addressPath).append(SecurityTokenProvider.instance.get());
String requestForMessage = requestMessageBuilder.toString();
logger.debug("Request " + requestForMessage);
return requestForMessage;
***REMOVED***
private String username(String token) throws ObjectNotFound, Exception ***REMOVED***
AuthorizationEntry entry = authorizationService().get(token); AuthorizationEntry entry = authorizationService().get(token);
this.logger.debug(entry.getClientInfo().getId()); logger.debug(entry.getClientInfo().getId());
return entry.getClientInfo().getId(); return entry.getClientInfo().getId();
***REMOVED*** ***REMOVED***
***REMOVED*** public String retrieveAdminRole() throws Exception ***REMOVED*** private void sendPostRequest(String endpoint, String postBody) throws EMailException ***REMOVED***
***REMOVED*** String serviceAddress = InfraRetrieval.findEmailingSystemAddress(ScopeProvider.instance.get()); logger.info("Execute Post:" + endpoint);
***REMOVED*** logger.info("Post Body:" + postBody);
***REMOVED*** if (!serviceAddress.endsWith("/"))
***REMOVED*** serviceAddress = serviceAddress + "/";
***REMOVED***
***REMOVED*** String requestForMessage = serviceAddress + "2/users/get-usernames-by-global-role";
***REMOVED*** requestForMessage = requestForMessage.replace("https:***REMOVED***", "http:***REMOVED***").replace(":80", "");
***REMOVED*** String requestParameters = "&role-name=Administrator" + "&gcube-token=" + SecurityTokenProvider.instance.get();
***REMOVED***
***REMOVED*** String response = HttpRequest.sendGetRequest(requestForMessage, requestParameters);
***REMOVED*** System.out.println(response.toString());
***REMOVED***
***REMOVED*** if (response == null) ***REMOVED***
***REMOVED*** Exception e = new Exception("Error in querying the recipient");
***REMOVED*** throw e;
***REMOVED*** ***REMOVED***
***REMOVED*** return response;
***REMOVED***
***REMOVED******REMOVED***
public String getSocialService() ***REMOVED***
SimpleQuery query = queryFor(GCoreEndpoint.class);
query.addCondition(SOCIAL_SERVICE_QUERY_CONDITION);
DiscoveryClient<GCoreEndpoint> client = clientFor(GCoreEndpoint.class);
List<GCoreEndpoint> resources = client.submit(query);
String a = resources.get(0).profile().endpointMap().get(SOCIAL_SERVICE_URI).uri().toString();
return a;
***REMOVED***
public String sendPostRequest(String endpoint, String requestParameters) ***REMOVED***
this.logger.debug("Sending post request");
***REMOVED*** Build parameter string
String data = requestParameters;
try ***REMOVED*** try ***REMOVED***
***REMOVED*** Send the request ***REMOVED*** Send the request
URL url = new URL(endpoint); URL url = new URL(endpoint);
URLConnection conn = url.openConnection(); URLConnection conn = url.openConnection();
conn.setRequestProperty("Accept", JSON_MIME_TYPE);
conn.setRequestProperty("Content-Type", JSON_MIME_TYPE);
conn.setDoOutput(true); conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
***REMOVED*** write parameters OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data); writer.write(postBody);
writer.flush(); writer.flush();
***REMOVED*** Get the response ***REMOVED*** Get the response
@ -170,125 +162,94 @@ public class SendMail ***REMOVED***
writer.close(); writer.close();
reader.close(); reader.close();
this.logger.debug("Operation completed"); logger.debug("Operation completed");
String response = answer.toString(); String response = answer.toString();
this.logger.debug("Response "+response); logger.info("Notification Response: " + response);
***REMOVED*** Output the response checkResponse(response);
return response;
***REMOVED*** catch (MalformedURLException ex) ***REMOVED*** ***REMOVED*** catch (EMailException e) ***REMOVED***
this.logger.error("Invalid URL",ex); throw e;
***REMOVED*** catch (IOException ex) ***REMOVED*** ***REMOVED*** catch (MalformedURLException e) ***REMOVED***
logger.error("Invalid URL: " + e.getLocalizedMessage(), e);
throw new EMailException(e);
***REMOVED*** catch (IOException e) ***REMOVED***
logger.error("Error in the IO process: " + e.getLocalizedMessage(), e);
throw new EMailException(e);
***REMOVED*** catch (Throwable e) ***REMOVED***
logger.error("Error executing post:" + e.getLocalizedMessage(), e);
throw new EMailException(e);
***REMOVED***
***REMOVED***
private void checkResponse(String response) throws EMailException ***REMOVED***
if (response == null) ***REMOVED***
logger.error("Invalid notification response: " + response);
throw new EMailException();***REMOVED*** TODO
***REMOVED*** else ***REMOVED***
try ***REMOVED***
JSONObject res = new JSONObject(response);
boolean success = res.getBoolean("success");
if (!success) ***REMOVED***
String message = res.getString("message");
logger.error("Error in send email notification: " + message);
throw new EMailException("Error in send email notification: "+message);
***REMOVED***
***REMOVED*** catch (JSONException e) ***REMOVED***
logger.error("Invalid notification response: " + response);
throw new EMailException(e);
***REMOVED***
this.logger.error("Error in the IO process",ex);
***REMOVED*** ***REMOVED***
***REMOVED*** ***REMOVED***
private List<String> getRecipients() ***REMOVED***
try ***REMOVED***
List<String> recipients = new ArrayList<String>();
String dataMinerManagers = retrieveDataMinerManagers();
logger.debug("Retrieved DataMiner Managers: " + dataMinerManagers);
if (dataMinerManagers != null && !dataMinerManagers.isEmpty()) ***REMOVED***
JSONObject obj = new JSONObject(dataMinerManagers);
JSONArray data = obj.getJSONArray("result");
if (data != null) ***REMOVED***
for (int i = 0; i < data.length(); i++) ***REMOVED***
recipients.add(data.getString(i));
***REMOVED***
***REMOVED***
***REMOVED*** else ***REMOVED***
logger.info("Use the default admins how workaround ");
List<String> defaultManagers = DMPMClientConfiguratorManager.getInstance().getDefaultAdmins();
recipients.addAll(defaultManagers);
***REMOVED***
recipients.add(this.username(SecurityTokenProvider.instance.get()));
logger.info("Retrieved Recipients: " + recipients);
return recipients;
***REMOVED*** catch (Exception e) ***REMOVED***
logger.error("Error retrieving recipients: " + e.getLocalizedMessage(), e);
logger.info("Use the default admins how workaround ");
return DMPMClientConfiguratorManager.getInstance().getDefaultAdmins();
***REMOVED***
***REMOVED*** ***REMOVED***
private String retrieveDataMinerManagers() throws Exception ***REMOVED***
***REMOVED*** Try to retrieve a url like this:
***REMOVED*** https:***REMOVED***api.d4science.org/social-networking-library-ws/rest/2/users/get-usernames-by-role?role-name=DataMiner-Manager&gcube-token=xxx-xxxx-xxxx-xxx
String requestAdminsUrl = getRequestMessage(USER_ROLES_ADDRESS_PATH);
logger.info("Request Admins Url: " + requestAdminsUrl);
public String getAdminRoles() throws Exception***REMOVED***
***REMOVED*** discover social gcore endpoint
***REMOVED***GcoreEndpointReader ep = new GcoreEndpointReader(ScopeProvider.instance.get());
String serviceAddress = getRequestMessage(USER_ROLES_ADDRESS_PATH);
***REMOVED***String serviceAddress = InfraRetrieval.findEmailingSystemAddress(ScopeProvider.instance.get());
***REMOVED***String serviceAddress = ep.getResourceEntyName();***REMOVED***"https:***REMOVED***socialnetworking1.d4science.org/social-networking-library-ws/rest/";
***REMOVED*** serviceAddress = serviceAddress.endsWith("/") ? serviceAddress : serviceAddress + "/";
***REMOVED*** serviceAddress+= "2/users/get-usernames-by-role?role-name=DataMiner-Manager&gcube-token=" + SecurityTokenProvider.instance.get();
this.logger.debug("Admin roles url is " + serviceAddress);
CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet getReq = new HttpGet(serviceAddress); HttpGet getReq = new HttpGet(requestAdminsUrl);
getReq.setHeader("accept", JSON_MIME_TYPE); getReq.setHeader("accept", JSON_MIME_TYPE);
getReq.setHeader("content-type", JSON_MIME_TYPE); getReq.setHeader("content-type", JSON_MIME_TYPE);
this.logger.info(EntityUtils.toString(client.execute(getReq).getEntity())); logger.info("Response: " + EntityUtils.toString(client.execute(getReq).getEntity()));
return EntityUtils.toString(client.execute(getReq).getEntity()); return EntityUtils.toString(client.execute(getReq).getEntity());
***REMOVED*** ***REMOVED***
public String getAdmins()***REMOVED***
try***REMOVED***
List<String> s = new LinkedList<String>();
JSONObject obj = new JSONObject(this.getAdminRoles());
JSONArray data = obj.getJSONArray("result");
if (data != null) ***REMOVED***
String[] names = new String[data.length()];
for (int i = 0; i < data.length(); i++) ***REMOVED***
names[i] = data.getString(i);
s.add(names[i]);
***REMOVED***
s.add(this.username(SecurityTokenProvider.instance.get()));
***REMOVED***
return s.toString().replace("[", "").replace("]", "");
***REMOVED***
catch(Exception a)***REMOVED***return DMPMClientConfiguratorManager.getInstance().getDefaultAdmins(); ***REMOVED***
***REMOVED***
***REMOVED*** public String getRootToken() throws Exception ***REMOVED***
***REMOVED***
***REMOVED*** ***REMOVED***ApplicationContext ctx = ContextProvider.get(); ***REMOVED*** get this info from
***REMOVED*** ***REMOVED*** SmartGears
***REMOVED*** ***REMOVED***System.out.println(ctx.container().configuration().infrastructure());
***REMOVED*** String a = "";
***REMOVED*** SimpleQuery query2 = queryFor(ServiceEndpoint.class);
***REMOVED*** query2.addCondition("$resource/Profile/Name/text() eq 'SAIService'").setResult("$resource");
***REMOVED***
***REMOVED*** DiscoveryClient<ServiceEndpoint> client2 = clientFor(ServiceEndpoint.class);
***REMOVED*** List<ServiceEndpoint> df = client2.submit(query2);
***REMOVED***
***REMOVED*** for (ServiceEndpoint b : df) ***REMOVED***
***REMOVED*** a = StringEncrypter.getEncrypter().decrypt(b.profile().accessPoints().iterator().next().password());
***REMOVED*** ***REMOVED***
***REMOVED*** return a;
***REMOVED******REMOVED***
public static void main(String[] args) throws Exception ***REMOVED***
***REMOVED***ScopeProvider.instance.set("/d4science.research-infrastructures.eu/gCubeApps/RPrototypingLab");
***REMOVED***SecurityTokenProvider.instance.set("***REMOVED***");
***REMOVED***ScopeProvider.instance.set("/gcube/devNext");
***REMOVED***SecurityTokenProvider.instance.set("aa6eec71-fe07-43ab-bd1c-f03df293e430-98187548");
***REMOVED***NotificationHelper nh = new NotificationHelper();
SendMail sm = new SendMail();
***REMOVED***ScopeProvider.instance.set("/gcube/devNext/NextNext");
***REMOVED***SecurityTokenProvider.instance.set("***REMOVED***");
***REMOVED***System.out.println(sm.getRootToken());
***REMOVED***sm.getGenericResourceByName("");
ScopeProvider.instance.set("/gcube/preprod/preVRE");
SecurityTokenProvider.instance.set("2eceaf27-0e22-4dbe-8075-e09eff199bf9-98187548");
***REMOVED***sm.sendNotification(nh.getFailedSubject(), nh.getFailedBody("test failed"));
***REMOVED*** sm.username(SecurityTokenProvider.instance.get());
***REMOVED***sm.retrieveAdminRole();
***REMOVED***sm.getAdminRoles();
System.out.println(sm.getAdmins());
***REMOVED***System.out.println(sm.getAdmins());
***REMOVED***sm.sendNotification("test", "test");
***REMOVED***System.out.println(sm.getSocialService());
***REMOVED***
***REMOVED*** ***REMOVED***

View File

@ -2,7 +2,6 @@ package org.gcube.dataanalysis.dataminer.poolmanager.util.exception;
public class EMailException extends Exception ***REMOVED*** public class EMailException extends Exception ***REMOVED***
private static final String MESSAGE = "Unable to send email notification"; private static final String MESSAGE = "Unable to send email notification";
***REMOVED**** ***REMOVED****
@ -11,14 +10,19 @@ public class EMailException extends Exception ***REMOVED***
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public EMailException() ***REMOVED*** public EMailException() ***REMOVED***
super (MESSAGE); super(MESSAGE);
***REMOVED*** ***REMOVED***
public EMailException(Throwable cause) ***REMOVED*** public EMailException(String message) ***REMOVED***
super (MESSAGE,cause); super(message);
***REMOVED*** ***REMOVED***
public EMailException(String message, Throwable e) ***REMOVED***
super(message, e);
***REMOVED***
public EMailException(Throwable e) ***REMOVED***
super(MESSAGE, e);
***REMOVED***
***REMOVED*** ***REMOVED***

5
src/main/webapp/WEB-INF/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
/LICENSE.md
/README.md
/changelog.xml
/gcube-app.xml
/profile.xml

View File

@ -0,0 +1,38 @@
package org.gcube.dataanalysis.dataminerpoolmanager;
***REMOVED***
***REMOVED***
import org.gcube.dataanalysis.dataminer.poolmanager.util.SendMail;
public class SendMailTest ***REMOVED***
public static void main(String[] args) ***REMOVED***
try ***REMOVED***
***REMOVED*** NotificationHelper nh = new NotificationHelper();
SendMail sm = new SendMail();
ScopeProvider.instance.set("/gcube/devNext/NextNext");
SecurityTokenProvider.instance.set("xxxx-xxxx-xxx");
***REMOVED*** System.out.println(sm.getRootToken());
***REMOVED*** sm.getGenericResourceByName("");
***REMOVED***ScopeProvider.instance.set("/gcube/devsec/devVRE");
***REMOVED***SecurityTokenProvider.instance.set("xxxx-xxxx-xxxx");
***REMOVED*** sm.sendNotification(nh.getFailedSubject(), nh.getFailedBody("test
***REMOVED*** failed"));
***REMOVED*** sm.username(SecurityTokenProvider.instance.get());
***REMOVED*** sm.retrieveAdminRole();
***REMOVED*** sm.getAdminRoles();
sm.sendNotification("Test DMPoolManager Notification", "This is only a test please cancel this message.");
***REMOVED*** System.out.println(sm.getAdmins());
***REMOVED*** sm.sendNotification("test", "test");
***REMOVED*** System.out.println(sm.getSocialService());
***REMOVED*** catch (Exception e) ***REMOVED***
System.out.println("Error in sent mail: "+e.getLocalizedMessage());
e.printStackTrace();
***REMOVED***
***REMOVED***
***REMOVED***