dataminer-pool-manager/src/main/java/org/gcube/dataanalysis/dataminer/poolmanager/util/SendMail.java

295 lines
11 KiB
Java

package org.gcube.dataanalysis.dataminer.poolmanager.util;
import static org.gcube.common.authorization.client.Constants.authorizationService;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
***REMOVED***
***REMOVED***
***REMOVED***
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
***REMOVED***
import java.net.URLConnection;
import java.net.URLEncoder;
***REMOVED***
***REMOVED***
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
***REMOVED***
import org.gcube.common.authorization.library.AuthorizationEntry;
***REMOVED***
import org.gcube.common.resources.gcore.GCoreEndpoint;
***REMOVED***
import org.gcube.dataanalysis.dataminer.poolmanager.clients.configuration.DMPMClientConfiguratorManager;
import org.gcube.dataanalysis.dataminer.poolmanager.util.exception.EMailException;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.json.JSONArray;
import org.json.JSONObject;
***REMOVED***
***REMOVED***
public class SendMail {
***REMOVED***
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() {
this.logger = LoggerFactory.getLogger(SendMail.class);
***REMOVED***
private String getRequestMessage (String addressPath)
{
String serviceAddress = this.getSocialService();
StringBuilder requestMessageBuilder = new StringBuilder(serviceAddress);
if (!serviceAddress.endsWith("/")) requestMessageBuilder.append('/');
requestMessageBuilder.append(addressPath).append(SecurityTokenProvider.instance.get());
String requestForMessage = requestMessageBuilder.toString();
this.logger.debug("Request "+requestForMessage);
return requestForMessage;
***REMOVED***
public void sendNotification(String subject, String body) throws EMailException
{
this.logger.debug("Sending mail notification for "+subject);
this.logger.debug("Body "+body);
***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
{
subject = URLEncoder.encode(subject, ENCODING);
body = URLEncoder.encode(body, ENCODING);
***REMOVED***
catch (UnsupportedEncodingException e)
{
throw new EMailException(e);
***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*** public void notifySubmitter(String a, String b) throws Exception {
***REMOVED*** NotificationHelper nh = new NotificationHelper();
***REMOVED*** super.sendNotification(nh.getSubject(),
***REMOVED*** nh.getBody());
***REMOVED*** ***REMOVED***
public String username(String token) throws ObjectNotFound, Exception {
AuthorizationEntry entry = authorizationService().get(token);
this.logger.debug(entry.getClientInfo().getId());
return entry.getClientInfo().getId();
***REMOVED***
***REMOVED*** public String retrieveAdminRole() throws Exception {
***REMOVED*** String serviceAddress = InfraRetrieval.findEmailingSystemAddress(ScopeProvider.instance.get());
***REMOVED***
***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*** Exception e = new Exception("Error in querying the recipient");
***REMOVED*** throw e;
***REMOVED*** ***REMOVED***
***REMOVED*** return response;
***REMOVED***
***REMOVED******REMOVED***
public String getSocialService() {
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) {
this.logger.debug("Sending post request");
***REMOVED*** Build parameter string
String data = requestParameters;
try {
***REMOVED*** Send the request
URL url = new URL(endpoint);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
***REMOVED*** write parameters
writer.write(data);
writer.flush();
***REMOVED*** Get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
***REMOVED***
writer.close();
reader.close();
this.logger.debug("Operation completed");
String response = answer.toString();
this.logger.debug("Response "+response);
***REMOVED*** Output the response
return response;
***REMOVED*** catch (MalformedURLException ex) {
this.logger.error("Invalid URL",ex);
***REMOVED*** catch (IOException ex) {
this.logger.error("Error in the IO process",ex);
***REMOVED***
return null;
***REMOVED***
public String getAdminRoles() throws Exception{
***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();
HttpGet getReq = new HttpGet(serviceAddress);
getReq.setHeader("accept", JSON_MIME_TYPE);
getReq.setHeader("content-type", JSON_MIME_TYPE);
this.logger.info(EntityUtils.toString(client.execute(getReq).getEntity()));
return EntityUtils.toString(client.execute(getReq).getEntity());
***REMOVED***
public String getAdmins(){
try{
List<String> s = new LinkedList<String>();
JSONObject obj = new JSONObject(this.getAdminRoles());
JSONArray data = obj.getJSONArray("result");
if (data != null) {
String[] names = new String[data.length()];
for (int i = 0; i < data.length(); i++) {
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){return DMPMClientConfiguratorManager.getInstance().getDefaultAdmins(); ***REMOVED***
***REMOVED***
***REMOVED*** public String getRootToken() throws Exception {
***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*** 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***ScopeProvider.instance.set("/d4science.research-infrastructures.eu/gCubeApps/RPrototypingLab");
***REMOVED***SecurityTokenProvider.instance.set("3a23bfa4-4dfe-44fc-988f-194b91071dd2-843339462");
***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("708e7eb8-11a7-4e9a-816b-c9ed7e7e99fe-98187548");
***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***