Browse Source

most of the part is complete, missing the notification part and bug on newlines not reported.

git-svn-id: http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/portal/social-mail-servlet@117104 82a268e6-3cf1-43bd-a215-b396298e98cf
Feature/21689
Massimiliano Assante 7 years ago
parent
commit
fc423272e3
  1. 32
      .classpath
  2. 42
      .project
  3. 13
      .settings/.jsdtscope
  4. 3
      .settings/org.eclipse.core.resources.prefs
  5. 8
      .settings/org.eclipse.jdt.core.prefs
  6. 4
      .settings/org.eclipse.m2e.core.prefs
  7. 11
      .settings/org.eclipse.wst.common.component
  8. 7
      .settings/org.eclipse.wst.common.project.facet.core.xml
  9. 1
      .settings/org.eclipse.wst.jsdt.ui.superType.container
  10. 1
      .settings/org.eclipse.wst.jsdt.ui.superType.name
  11. 2
      .settings/org.eclipse.wst.validation.prefs
  12. 2
      distro/INSTALL
  13. 7
      distro/LICENSE
  14. 6
      distro/MAINTAINERS
  15. 35
      distro/README
  16. 5
      distro/changelog.xml
  17. 48
      distro/descriptor.xml
  18. 25
      distro/profile.xml
  19. 1
      distro/svnpath.txt
  20. 200
      pom.xml
  21. 102
      src/main/java/org/gcube/portal/socialmail/MailReader.java
  22. 233
      src/main/java/org/gcube/portal/socialmail/PeriodicTask.java
  23. 83
      src/main/java/org/gcube/portal/socialmail/Utils.java
  24. 13
      src/main/resources/clientlog4j.properties
  25. 17
      src/main/webapp/WEB-INF/web.xml
  26. 5
      src/main/webapp/index.jsp

32
.classpath

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

42
.project

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>social-mail-servlet</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>

13
.settings/.jsdtscope

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<classpathentry kind="src" path="target/m2e-wtp/web-resources"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>

3
.settings/org.eclipse.core.resources.prefs

@ -0,0 +1,3 @@
eclipse.preferences.version=1
encoding//src/main/resources=UTF-8
encoding/<project>=UTF-8

8
.settings/org.eclipse.jdt.core.prefs

@ -0,0 +1,8 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.7

4
.settings/org.eclipse.m2e.core.prefs

@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

11
.settings/org.eclipse.wst.common.component

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="social-mail-servlet">
<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="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/java"/>
<property name="context-root" value="social-mail-servlet"/>
<property name="java-output-path" value="/social-mail-servlet/target/classes"/>
</wb-module>
</project-modules>

7
.settings/org.eclipse.wst.common.project.facet.core.xml

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="jst.web" version="2.3"/>
<installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="java" version="1.7"/>
</faceted-project>

1
.settings/org.eclipse.wst.jsdt.ui.superType.container

@ -0,0 +1 @@
org.eclipse.wst.jsdt.launching.baseBrowserLibrary

1
.settings/org.eclipse.wst.jsdt.ui.superType.name

@ -0,0 +1 @@
Window

2
.settings/org.eclipse.wst.validation.prefs

@ -0,0 +1,2 @@
disabled=06target
eclipse.preferences.version=1

2
distro/INSTALL

@ -0,0 +1,2 @@

7
distro/LICENSE

@ -0,0 +1,7 @@
gCube System - License
------------------------------------------------------------
The gCube/gCore software is licensed as Free Open Source software conveying to the EUPL (http://ec.europa.eu/idabc/eupl).
The software and documentation is provided by its authors/distributors "as is" and no expressed or
implied warranty is given for its use, quality or fitness for a particular case.

6
distro/MAINTAINERS

@ -0,0 +1,6 @@
Mantainers
-------
* Massimiliano Assante (massimiliano.assante@isti.cnr.it), CNR Pisa,
Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo".

35
distro/README

@ -0,0 +1,35 @@
The gCube System - Social Library
------------------------------------------------------------
This work is partially funded by the European Commission in the
context of the iMarine project (www.i-marine.eu), under the 1st call of FP7 IST priority.
Authors
-------
Massimiliano Assante
*
Version and Release Date
------------------------
Description
-----------
Social Mail Servlet
Download information
--------------------
Source code is available from SVN:
https://svn.d4science.research-infrastructures.eu/gcube/trunk/portal/social-mail-servlet
Binaries can be downloaded from:
http://www.gcube-system.org/
Documentation
-------------
Documentation is available on-line from the Projects Documentation Wiki:
Licensing
---------
This software is licensed under the terms you may find in the file named "LICENSE" in this directory.

5
distro/changelog.xml

@ -0,0 +1,5 @@
<ReleaseNotes>
<Changeset component="org.gcube.portal.social-mail-servlet.1-0-0" date="2015-07-07">
<Change>First Release</Change>
</Changeset>
</ReleaseNotes>

48
distro/descriptor.xml

@ -0,0 +1,48 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>servicearchive</id>
<formats>
<format>tar.gz</format>
</formats>
<baseDirectory>/</baseDirectory>
<fileSets>
<fileSet>
<directory>${distroDirectory}</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<includes>
<include>README</include>
<include>LICENSE</include>
<include>INSTALL</include>
<include>MAINTAINERS</include>
<include>changelog.xml</include>
</includes>
<fileMode>755</fileMode>
<filtered>true</filtered>
</fileSet>
<fileSet>
<directory>target/apidocs</directory>
<outputDirectory>/${artifactId}/doc/api</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<fileMode>755</fileMode>
</fileSet>
</fileSets>
<files>
<file>
<source>${distroDirectory}/profile.xml</source>
<outputDirectory>./</outputDirectory>
<filtered>true</filtered>
</file>
<file>
<source>target/${build.finalName}.war</source>
<outputDirectory>/${artifactId}</outputDirectory>
</file>
<file>
<source>${distroDirectory}/svnpath.txt</source>
<outputDirectory>/${artifactId}</outputDirectory>
<filtered>true</filtered>
</file>
</files>
</assembly>

25
distro/profile.xml

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID></ID>
<Type>Library</Type>
<Profile>
<Description>${description}</Description>
<Class>Portal</Class>
<Name>${artifactId}</Name>
<Version>1.0.0</Version>
<Packages>
<Software>
<Name>${artifactId}</Name>
<Version>${version}</Version>
<MavenCoordinates>
<groupId>${groupId}</groupId>
<artifactId>${artifactId}</artifactId>
<version>${version}</version>
</MavenCoordinates>
<Files>
<File>${build.finalName}.war</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

1
distro/svnpath.txt

@ -0,0 +1 @@
${scm.url}

200
pom.xml

@ -0,0 +1,200 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>maven-parent</artifactId>
<groupId>org.gcube.tools</groupId>
<version>1.0.0</version>
<relativePath />
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.gcube.portal</groupId>
<artifactId>social-mail-servlet</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>social-mail-servlet Maven Webapp</name>
<description>This component read periodically email replies from user wanting to reply to a post via email</description>
<properties>
<java-version>1.7</java-version>
<liferay-version>6.0.6</liferay-version>
<distroDirectory>${project.basedir}/distro</distroDirectory>
<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>
</properties>
<scm>
<url>http://svn.d4science.research-infrastructures.eu/gcube/trunk/portal/${project.artifactId}</url>
</scm>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>maven-portal-bom</artifactId>
<version>LATEST</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.common.portal</groupId>
<artifactId>portal-manager</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>custom-portal-handler</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.applicationsupportlayer</groupId>
<artifactId>aslcore</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.applicationsupportlayer</groupId>
<artifactId>aslsocial</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>social-networking-library</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google</groupId>
<artifactId>gwt-jsonmaker</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.dvos</groupId>
<artifactId>usermanagement-core</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>ic-client</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-encryption</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>portal-service</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.portlet</groupId>
<artifactId>portlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>social-mail-servlet</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>exploded</goal>
</goals>
</execution>
</executions>
<configuration>
<webappDirectory>${webappDirectory}</webappDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<!-- SA Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>servicearchive</id>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>copy-profile</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>target</outputDirectory>
<resources>
<resource>
<directory>${distroDirectory}</directory>
<filtering>true</filtering>
<includes>
<include>profile.xml</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

102
src/main/java/org/gcube/portal/socialmail/MailReader.java

@ -0,0 +1,102 @@
package org.gcube.portal.socialmail;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.gcube.common.encryption.StringEncrypter;
import org.gcube.common.portal.PortalContext;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.server.DBCassandraAstyanaxImpl;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("serial")
public class MailReader extends HttpServlet {
private static final Logger _log = LoggerFactory.getLogger(MailReader.class);
private static final int MINUTES_DELAY = 1;
private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private static DatabookStore store;
private static String portalName;
private static String host;
private static String user;
private static String password;
public void init() {
store = new DBCassandraAstyanaxImpl();
portalName = PortalContext.getPortalInstanceName();
PortalContext context = PortalContext.getConfiguration();
String scope = "/" + context.getInfrastructureName();
ScopeProvider.instance.set(scope);
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Category/text() eq 'Portal'");
query.addCondition("$resource/Profile/Name/text() eq '" + portalName + "'");
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> list = client.submit(query);
if (list == null || list.isEmpty()) {
_log.error("Could not find any Service endpoint registred in the infrastructure for this portal: " + portalName);
}
else if (list.size() > 1) {
_log.warn("Found more than one Service endpoint registred in the infrastructure for this portal: " + portalName);
}
else {
for (ServiceEndpoint res : list) {
AccessPoint found = res.profile().accessPoints().iterator().next();
host = found.address();
user = found.username();
String encrPassword = found.password();
try {
password = StringEncrypter.getEncrypter().decrypt( encrPassword);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
scheduler.scheduleAtFixedRate(new PeriodicTask(store, portalName, host, user, password), 0, MINUTES_DELAY, TimeUnit.MINUTES);
String toReturn = "Check Notification Email Started ... ";
response.setContentType("text/html");
response.getWriter().write(toReturn);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
public static void main(String[] args) {
new MailReader().init();
System.out.println("Scheduling periodic task ... ");
//System.out.println(host + user + password);
scheduler.scheduleAtFixedRate(new PeriodicTask(store, portalName, host, user, password), 0, MINUTES_DELAY, TimeUnit.MINUTES);
}
}

233
src/main/java/org/gcube/portal/socialmail/PeriodicTask.java

@ -0,0 +1,233 @@
package org.gcube.portal.socialmail;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage.RecipientType;
import org.gcube.application.framework.core.session.ASLSession;
import org.gcube.application.framework.core.session.SessionManager;
import org.gcube.application.framework.core.util.GenderType;
import org.gcube.applicationsupportlayer.social.mailing.EmailPlugin;
import org.gcube.common.portal.PortalContext;
import org.gcube.portal.custom.communitymanager.OrganizationsUtil;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.portal.databook.shared.Comment;
import org.gcube.portal.databook.shared.ex.FeedIDNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.sun.mail.util.MailSSLSocketFactory;
/**
*
* @author Massimiliano Assante, CNR-ISTI
*
*/
public class PeriodicTask implements Runnable {
private static final Logger _log = LoggerFactory.getLogger(PeriodicTask.class);
private DatabookStore socialStore;
private String host;
private String mailserver_username;
private String password;
private String portalName;
public PeriodicTask(DatabookStore store, String portalName, String host, String mailserver_username, String password) {
super();
this.socialStore = store;
this.portalName = portalName;
this.host = host;
this.mailserver_username = mailserver_username;
this.password = password;
}
@Override
public void run() {
//check("pop.isti.cnr.it", "social.post", "kof9044+");
check(portalName, host, mailserver_username, password);
}
/**
* @return a fake session usuful for Notifications
*/
private ASLSession getFakeASLSession(String emailAddress) {
String sessionID = UUID.randomUUID().toString();
PortalContext context = PortalContext.getConfiguration();
String scope = "/" + context.getInfrastructureName();
String username = "";
long companyId;
try {
companyId = OrganizationsUtil.getCompany().getCompanyId();
User user = UserLocalServiceUtil.getUserByEmailAddress(companyId, emailAddress);
username = user.getScreenName();
SessionManager.getInstance().getASLSession(sessionID, username).setScope(scope);
//add the social information needed by apps
String fullName = user.getFirstName() + " " + user.getLastName();
String email = user.getEmailAddress();
String thumbnailURL = "/image/user_male_portrait?img_id="+user.getPortraitId();
boolean isMale = user.isMale();
SessionManager.getInstance().getASLSession(sessionID, username).setUserFullName(fullName);
SessionManager.getInstance().getASLSession(sessionID, username).setUserEmailAddress(email);
SessionManager.getInstance().getASLSession(sessionID, username).setUserAvatarId(thumbnailURL);
SessionManager.getInstance().getASLSession(sessionID, username).setUserGender(isMale? GenderType.MALE : GenderType.FEMALE);
} catch (PortalException | SystemException e) {
e.printStackTrace();
}
return SessionManager.getInstance().getASLSession(sessionID, username);
}
public void check(String portalName, String host, String user, String password) {
try {
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
}
catch (GeneralSecurityException e) {
e.printStackTrace();
}
sf.setTrustAllHosts(true);
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.ssl.enable", "true");
pop3Props.setProperty("mail.protocol.ssl.trust", host);
pop3Props.put("mail.pop3s.ssl.socketFactory", sf);
pop3Props.setProperty("mail.pop3s.port", "995");
Session emailSession = Session.getDefaultInstance(pop3Props);
//emailSession.setDebug(true);
//create the POP3 socialStore object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_WRITE);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
_log.debug("Found " + messages.length + " new messages ...");
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
_log.debug("--------------- FOUND EMAIL ------------------");
String subject = message.getSubject();
_log.debug("Parsing email of " + message.getFrom()[0] + " with subject: " + subject);
String feedId = extractFeedId(message);
String commentText = extractText(portalName, feedId, message);
String escapedCommentText = Utils.escapeHtmlAndTransformUrl(commentText);
Address[] froms = message.getFrom();
String emailAddress = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
ASLSession fakeSession = getFakeASLSession(emailAddress);
Comment comment = new Comment(UUID.randomUUID().toString(), fakeSession.getUsername(),
new Date(), feedId, escapedCommentText, fakeSession.getUserFullName(), fakeSession.getUserAvatarId());
_log.debug("Parsed and escapedCommentText =>" + escapedCommentText);
boolean commentCommitResult = false;
try {
if (socialStore.addComment(comment))
commentCommitResult = true;
} catch (FeedIDNotFoundException e) {
_log.error("Related post not found for this comment " + e.getMessage());
e.printStackTrace();
}
if (commentCommitResult) { //the notify
_log.info("Now the NOTIFICATION SHOULD START!!!!!");
}
message.setFlag(Flags.Flag.DELETED, true);
System.out.println("Marked DELETE for message: " + subject);
}
//close the socialStore and folder objects
emailFolder.close(true);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private String extractFeedId(Message message) throws MessagingException {
Address[] emails = message.getRecipients(RecipientType.TO);
String toParse = emails[0].toString();
int plus = toParse.indexOf('+');
int at = toParse.indexOf('@');
if (plus == -1)
return null;
return toParse.substring(plus+1, at);
}
private String extractText(String portalName, String subjectId, Message message) throws Exception {
Address[] emails = message.getRecipients(RecipientType.TO);
Object messageContent = message.getContent();
String toParse = null;
// Check if content is pure text/html or in parts
if (messageContent instanceof Multipart) {
_log.debug("Found Multipart Message, getting text part");
Multipart multipart = (Multipart) messageContent;
BodyPart part = multipart.getBodyPart(0);
part.toString();
toParse = part.getContent().toString();
}
else {
_log.debug("Found g text/plain Message, getting text");
toParse = messageContent.toString();
}
String[] lines = toParse.split(System.getProperty("line.separator"));
int until = -1;
for (int i = 0; i < lines.length; i++) {
if (lines[i].contains(EmailPlugin.WRITE_ABOVE_TO_REPLY)) {
until = i;
break;
}
}
String toReturn = "";
for (int i = 0; i < until; i++) {
if (! ( lines[i].contains(portalName) || lines[i].contains(subjectId) || (lines[i].startsWith("> ") && lines[i].trim().length() < 2)) ) {
toReturn += lines[i];
}
}
return toReturn;
}
}

83
src/main/java/org/gcube/portal/socialmail/Utils.java

@ -0,0 +1,83 @@
package org.gcube.portal.socialmail;
import java.net.MalformedURLException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Utils {
private static final Logger _log = LoggerFactory.getLogger(Utils.class);
/**
* 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
*/
protected static String escapeHtmlAndTransformUrl(String html) {
if (html == null) {
return null;
}
String toReturn = html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
.replaceAll(">", "&gt;");
// replace all the line breaks by <br/>
toReturn = toReturn.replaceAll("(\r\n|\n)"," <br/> ");
//transfrom the URL in a clickable URL
toReturn = transformUrls(toReturn);
// then replace all the double spaces by the html version &nbsp;
toReturn = toReturn.replaceAll("\\s\\s","&nbsp;&nbsp;");
return toReturn;
}
/**
* utility method that convert a url ina text in a clickable url by the browser
* and if the user has just pasted a link, converts the link in: shared a link
* @param feedText
* @return the text with the clickable url in it
*/
protected static String transformUrls(String feedText) {
StringBuilder sb = new StringBuilder();
// separate input by spaces ( URLs have no spaces )
String [] parts = feedText.split("\\s");
// Attempt to convert each item into an URL.
for (int i = 0; i < parts.length; i++) {
String toCheck = getHttpToken(parts[i]);
if (toCheck != null) {
try {
URL url = new URL(toCheck);
if (i == 0 && parts.length == 1) //then he shared just a link
return sb.append("<span style=\"color:gray; font-size:12px;\">shared </span><a class=\"link\" href=\"").append(url).append("\" target=\"_blank\">").append("a link.").append("</a> ").toString();
// If possible then replace with anchor...
sb.append("<a class=\"link\" href=\"").append(url).append("\" target=\"_blank\">").append(url).append("</a> ");
} catch (MalformedURLException e) {
// If there was an URL then it's not valid
_log.error("MalformedURLException returning... ");
return feedText;
}
} else {
sb.append(parts[i]);
sb.append(" ");
}
}
return sb.toString();
}
/**
* check the tokens of a pasted text and see if there's any http link in it
* @param item a text token
* @return the actual http link
*/
private static String getHttpToken(String item) {
if (item.startsWith("http") || item.startsWith("www") || item.startsWith("(www") || item.startsWith("(http")) {
if (item.startsWith("("))
item = item.substring(1, item.length());
if (item.endsWith(".") || item.endsWith(")")) { //sometimes people write the url and close the phrase with a .
item = item.substring(0, item.length()-1);
}
item = item.startsWith("www") ? "http://"+item : item;
//System.out.println("getHttpToken returns -> " + item);
return item;
}
return null;
}
}

13
src/main/resources/clientlog4j.properties

@ -0,0 +1,13 @@
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
# Print the date in ISO 8601 format
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
# Print only messages of level TRACE or above in the package org.gcube
log4j.logger.org.gcube=TRACE
log4j.logger.org.gcube.application.framework.core.session=INFO
log4j.logger.com.netflix.astyanax.connectionpool=ERROR
log4j.logger.org.gcube.portal.databook.server.DBCassandraAstyanaxImpl=TRACE
log4j.logger.org.gcube.common=ERROR

17
src/main/webapp/WEB-INF/web.xml

@ -0,0 +1,17 @@
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Email Comments Reader Webapp</display-name>
<servlet>
<servlet-name>read-mail</servlet-name>
<servlet-class>org.gcube.portal.socialmail.MailReader</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>read-mail</servlet-name>
<url-pattern>/read-mail</url-pattern>
</servlet-mapping>
</web-app>

5
src/main/webapp/index.jsp

@ -0,0 +1,5 @@
<html>
<body>
<h2>Hello From Mail Reader Scheduler service!</h2>
</body>
</html>
Loading…
Cancel
Save