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

256 lines
9.7 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;
import java.io.BufferedReader;
***REMOVED***
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
***REMOVED***
***REMOVED***
import java.net.URLConnection;
import java.util.ArrayList;
***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;
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.JSONException;
import org.json.JSONObject;
***REMOVED***
***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 String socialServiceAddress;
public SendMail() ***REMOVED***
***REMOVED***
public void sendNotification(String subject, String body) throws EMailException ***REMOVED***
logger.debug("SendNotification");
logger.debug("Notification Subject: " + subject);
logger.debug("Notification Body: " + body);
retrieveSocialService();
String postBody = createPostBody(subject, body);
String requestForMessage = getRequestMessage(WRITE_MESSAGE_ADDRESS_PATH);
sendPostRequest(requestForMessage, postBody);
***REMOVED***
private String createPostBody(String subject, String body) throws EMailException ***REMOVED***
try ***REMOVED***
List<String> recipientsList = getRecipients();
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***
***REMOVED*** ***REMOVED***"subject": "subject-content", "body": "body-content",
***REMOVED*** "recipients":[***REMOVED***"id":"userid"***REMOVED***]***REMOVED***
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***
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);
***REMOVED***
***REMOVED***
private String getRequestMessage(String addressPath) ***REMOVED***
StringBuilder requestMessageBuilder = new StringBuilder(socialServiceAddress);
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);
logger.debug(entry.getClientInfo().getId());
return entry.getClientInfo().getId();
***REMOVED***
private void sendPostRequest(String endpoint, String postBody) throws EMailException ***REMOVED***
logger.info("Execute Post:" + endpoint);
logger.info("Post Body:" + postBody);
try ***REMOVED***
***REMOVED*** Send the request
URL url = new URL(endpoint);
URLConnection conn = url.openConnection();
conn.setRequestProperty("Accept", JSON_MIME_TYPE);
conn.setRequestProperty("Content-Type", JSON_MIME_TYPE);
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(postBody);
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) ***REMOVED***
answer.append(line);
***REMOVED***
writer.close();
reader.close();
logger.debug("Operation completed");
String response = answer.toString();
logger.info("Notification Response: " + response);
checkResponse(response);
***REMOVED*** catch (EMailException e) ***REMOVED***
throw e;
***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***
***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***
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);
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet getReq = new HttpGet(requestAdminsUrl);
getReq.setHeader("accept", JSON_MIME_TYPE);
getReq.setHeader("content-type", JSON_MIME_TYPE);
logger.info("Response: " + EntityUtils.toString(client.execute(getReq).getEntity()));
return EntityUtils.toString(client.execute(getReq).getEntity());
***REMOVED***
***REMOVED***