send email almost ready

git-svn-id: http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/portlets/user/invite-friends-vre@114591 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Massimiliano Assante 2015-04-29 16:00:30 +00:00
parent d7eecbf6e3
commit 65ec7559b0
6 changed files with 194 additions and 136 deletions

View File

@ -5,9 +5,6 @@
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/target/generated-sources/gwt"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<dependent-module archiveName="session-checker-0.3.0-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/session-checker/session-checker">
<dependency-type>uses</dependency-type>
</dependent-module>
<property name="context-root" value="invite-friends-vre"/>
<property name="java-output-path" value="/invite-friends-vre/target/invite-friends-vre-0.0.1-SNAPSHOT/WEB-INF/classes"/>
</wb-module>

59
pom.xml
View File

@ -85,71 +85,16 @@
<artifactId>custom-portal-handler</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-encryption</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope-maps</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.dvos</groupId>
<artifactId>usermanagement-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>net.eliasbalasis</groupId>
<artifactId>tibcopagebus4gwt</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.gcube.applicationsupportlayer</groupId>
<artifactId>aslcore</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.applicationsupportlayer</groupId>
<artifactId>aslsocial</artifactId>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google</groupId>
<artifactId>gwt-jsonmaker</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>social-networking-library</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.portlets.widgets</groupId>
<artifactId>wsmail-widget</artifactId>
<version>[1.4.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.portlets.widgets</groupId>
<artifactId>workspace-light-tree</artifactId>
<version>[2.13.0-SNAPSHOT, 3.0.0-SNAPSHOT)</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>portal-service</artifactId>

View File

@ -8,5 +8,5 @@ import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
*/
@RemoteServiceRelativePath("greet")
public interface InviteService extends RemoteService {
String greetServer(String name) throws IllegalArgumentException;
Boolean sendInviteEmail(String name, String lastName, String email) throws IllegalArgumentException;
}

View File

@ -3,6 +3,9 @@
*/
package org.gcube.portlets.user.invitefriends.client.validation;
import org.gcube.portlets.user.invitefriends.client.InviteService;
import org.gcube.portlets.user.invitefriends.client.InviteServiceAsync;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.ControlGroup;
import com.github.gwtbootstrap.client.ui.HelpBlock;
@ -17,6 +20,8 @@ import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
@ -27,6 +32,11 @@ import com.google.gwt.user.client.ui.Widget;
*/
public class FormViewImpl extends Composite implements FormView, Editor<FormView.UserDetails> {
/**
* Create a remote service proxy to talk to the server-side service
*/
private final InviteServiceAsync service = GWT.create(InviteService.class);
interface Binder extends UiBinder<Widget, FormViewImpl> {}
private static Binder uiBinder = GWT.create(Binder.class);
@ -75,6 +85,19 @@ public class FormViewImpl extends Composite implements FormView, Editor<FormView
} else {
nameGroup.setType(ControlGroupType.SUCCESS);
nameErrors.setText("");
service.sendInviteEmail(name.getText(), lastName.getText(), email.getText(), new AsyncCallback<Boolean>() {
@Override
public void onSuccess(Boolean result) {
helpBlock.setText("Send OK");
}
@Override
public void onFailure(Throwable caught) {
helpBlock.setText("Message send error");
}
});
}
}

View File

@ -1,48 +1,183 @@
package org.gcube.portlets.user.invitefriends.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.gcube.application.framework.core.session.ASLSession;
import org.gcube.application.framework.core.session.SessionManager;
import org.gcube.portal.custom.communitymanager.OrganizationsUtil;
import org.gcube.portal.custom.scopemanager.scopehelper.ScopeHelper;
import org.gcube.portlets.user.invitefriends.client.InviteService;
import org.gcube.portlets.user.invitefriends.shared.FieldVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
/**
* The server side implementation of the RPC service.
*/
@SuppressWarnings("serial")
public class InviteServiceImpl extends RemoteServiceServlet implements
InviteService {
public class InviteServiceImpl extends RemoteServiceServlet implements InviteService {
public String greetServer(String input) throws IllegalArgumentException {
// Verify that the input is valid.
if (!FieldVerifier.isValidName(input)) {
// If the input is not valid, throw an IllegalArgumentException back to
// the client.
throw new IllegalArgumentException(
"Name must be at least 4 characters long");
}
private final static Logger _log = LoggerFactory.getLogger(InviteServiceImpl.class);
private final static String MAIL_SERVICE_HOST = "localhost";
private final static String MAIL_SERVICE_PORT = "25";
private static final String SENDER_EMAIL = "notificationSenderEmail";
private static final String GATEWAY_NAME = "portalinstancename";
/**
* the current ASLSession
* @return the session
*/
private ASLSession getASLSession() {
String sessionID = this.getThreadLocalRequest().getSession().getId();
String user = (String) this.getThreadLocalRequest().getSession().getAttribute(ScopeHelper.USERNAME_ATTRIBUTE);
if (user == null) {
_log.warn("USER IS NULL setting test.user");
user = "test.user";
}
else {
_log.info("LIFERAY PORTAL DETECTED user=" + user);
}
return SessionManager.getInstance().getASLSession(sessionID, user);
}
/**
*
*/
@Override
public Boolean sendInviteEmail(String name, String lastName, String email) throws IllegalArgumentException {
ASLSession aslSession = getASLSession();
String vreName = aslSession.getGroupName();
String fromFullName = aslSession.getUserFullName();
Properties props = System.getProperties();
Session session = null;
props.put("mail.smtp.host", MAIL_SERVICE_HOST);
props.put("mail.smtp.port", MAIL_SERVICE_PORT);
session = Session.getDefaultInstance(props);
session.setDebug(true);
String serverInfo = getServletContext().getServerInfo();
String userAgent = getThreadLocalRequest().getHeader("User-Agent");
try {
MimeMessage message = new MimeMessage(session);
message.setHeader("Content-Type", "text/plain; charset=UTF-8");
// Set From: header field of the header.
message.setFrom(new InternetAddress(getSenderEmail(), getPortalInstanceName()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
// Escape data from the client to avoid cross-site script vulnerabilities.
input = escapeHtml(input);
userAgent = escapeHtml(userAgent);
// Set Subject: header field
message.setSubject(name + ", " + fromFullName + " would like you to try " + vreName);
return "Hello, " + input + "!<br><br>I am running " + serverInfo
+ ".<br><br>looks like you are using:<br>" + userAgent;
}
// Now set the actual message
message.setText(getTextEmail(name, lastName, email, fromFullName, vreName));
// Send message
Transport.send(message);
_log.debug("Sent message successfully to " + email );
} catch (Exception mex) {
mex.printStackTrace();
_log.error("Sent message ERROR to " + email );
return false;
}
return true;
}
private String getTextEmail(String name, String lastName, String email, String fromFullName, String vreName) {
String username = getASLSession().getUsername();
String portalUrl = null;
try {
portalUrl = PortalUtil.getPortalURL(OrganizationsUtil.getCompany().getVirtualHost(), PortalUtil.getPortalPort(), true);
} catch (Exception e1) {
e1.printStackTrace();
_log.warn("While trying to send email for invitation to " + email);
return null;
}
String portalHost = portalUrl.replaceAll("https://", "");
portalHost = portalHost.replaceAll("http://", "");
StringBuilder body = new StringBuilder();
body.append("Dear " + name)
.append("\n\n")
.append(fromFullName).append("\n")
.append("would like you to try the " + vreName + " Virtual Research Environment")
.append("\n\n")
.append("WARNING / LEGAL TEXT: This message is intended only for the use of the individual or entity to which it is addressed and may contain")
.append("information which is privileged, confidential, proprietary, or exempt from disclosure under applicable law. "
+ "If you are not the intended recipient or the person responsible for delivering the message to the intended recipient, "
+ "you are strictly prohibited from disclosing, distributing, copying, or in any way using this message.")
.append("If you have received this communication in error, please notify the <sender> and destroy and delete any copies you may have received.");
return body.toString();
}
/**
* read the portal instance name from a property file and returns it
*/
private static String getPortalInstanceName() {
//get the portles to look for from the property file
Properties props = new Properties();
String toReturn = "";
try {
String propertyfile = OrganizationsUtil.getTomcatFolder()+"conf/gcube-data.properties";
File propsFile = new File(propertyfile);
FileInputStream fis = new FileInputStream(propsFile);
props.load( fis);
toReturn = props.getProperty(GATEWAY_NAME);
}
//catch exception in case properties file does not exist
catch(IOException e) {
toReturn = "D4science Gateway";
_log.error("gcube-data.properties file not found under $CATALINA_HOME/conf dir, returning default Portal Name " + toReturn);
return toReturn;
}
_log.debug("Returning Gateway Name: " + toReturn );
return toReturn;
}
/**
* read the sender email for notifications name from a property file and returns it
*/
private static String getSenderEmail() {
//get the portles to look for from the property file
Properties props = new Properties();
String toReturn = "";
try {
String propertyfile = OrganizationsUtil.getTomcatFolder()+"conf/gcube-data.properties";
File propsFile = new File(propertyfile);
FileInputStream fis = new FileInputStream(propsFile);
props.load( fis);
toReturn = props.getProperty(SENDER_EMAIL);
}
//catch exception in case properties file does not exist
catch(IOException e) {
toReturn = "do-not-reply@d4science.org";
_log.error("gcube-data.properties file not found under $CATALINA_HOME/conf dir, returning default Email" + toReturn);
return toReturn;
}
_log.debug("Returning SENDER_EMAIL: " + toReturn );
return toReturn;
}
/**
* Escape an html string. Escaping data received from the client helps to
* prevent cross-site script vulnerabilities.
*
* @param html the html string to escape
* @return the escaped string
*/
private String escapeHtml(String html) {
if (html == null) {
return null;
}
return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(
">", "&gt;");
}
}

View File

@ -1,42 +0,0 @@
package org.gcube.portlets.user.invitefriends.shared;
/**
* <p>
* FieldVerifier validates that the name the user enters is valid.
* </p>
* <p>
* This class is in the <code>shared</code> packing because we use it in both
* the client code and on the server. On the client, we verify that the name is
* valid before sending an RPC request so the user doesn't have to wait for a
* network round trip to get feedback. On the server, we verify that the name is
* correct to ensure that the input is correct regardless of where the RPC
* originates.
* </p>
* <p>
* When creating a class that is used on both the client and the server, be sure
* that all code is translatable and does not use native JavaScript. Code that
* is note translatable (such as code that interacts with a database or the file
* system) cannot be compiled into client side JavaScript. Code that uses native
* JavaScript (such as Widgets) cannot be run on the server.
* </p>
*/
public class FieldVerifier {
/**
* Verifies that the specified name is valid for our service.
*
* In this example, we only require that the name is at least four
* characters. In your application, you can use more complex checks to ensure
* that usernames, passwords, email addresses, URLs, and other fields have the
* proper syntax.
*
* @param name the name to validate
* @return true if valid, false if invalid
*/
public static boolean isValidName(String name) {
if (name == null) {
return false;
}
return name.length() > 3;
}
}