removed ldap export thread and moved to another dedicated servlet

git-svn-id: http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/portal/social-mail-servlet@120478 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Massimiliano Assante 2015-11-30 14:29:01 +00:00
parent f773e72185
commit a9961f4202
5 changed files with 8 additions and 228 deletions

View File

@ -18,12 +18,10 @@ 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.resources.gcore.ServiceEndpoint.Property;
import org.gcube.common.resources.gcore.utils.Group;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.server.DBCassandraAstyanaxImpl;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.portal.ldapexport.LDAPSync;
import org.gcube.portal.socialmail.PeriodicTask;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
@ -37,14 +35,9 @@ public class PortalSchedulerService extends HttpServlet {
private static final Logger _log = LoggerFactory.getLogger(PortalSchedulerService.class);
private static final String POP3_SERVER_NAME = "Pop3MailServer";
private static final String LDAP_SERVER_NAME = "LDAPServer";
private static final String LDAP_SERVER_FILTER_NAME = "filter";
private static final String LDAP_SERVER_PRINCPAL_NAME = "ldapPrincipal";
private static final int POP3_MINUTES_DELAY = 1;
private static final int LDAP_MINUTES_DELAY = 15;
private static DatabookStore store;
@ -53,10 +46,6 @@ public class PortalSchedulerService extends HttpServlet {
private String pop3user;
private String pop3password;
private String ldapUrl;
private String filter;
private String principal;
private String ldapPassword;
public void init() {
store = new DBCassandraAstyanaxImpl();
@ -97,61 +86,17 @@ public class PortalSchedulerService extends HttpServlet {
e.printStackTrace();
}
}
else if (accessPoints[i].name().compareTo(LDAP_SERVER_NAME) == 0) {
_log.info("Found credentials for " + LDAP_SERVER_NAME);
AccessPoint found = accessPoints[i];
ldapUrl = found.address();
String encrPassword = found.password();
try {
ldapPassword = StringEncrypter.getEncrypter().decrypt( encrPassword);
} catch (Exception e) {
_log.error("Something went wrong while decrypting password for " + LDAP_SERVER_NAME);
e.printStackTrace();
}
Group<Property> propGroup = found.properties();
Property[] props = (Property[]) propGroup.toArray(new Property[propGroup.size()]);
for (int j = 0; j < props.length; j++) {
if (props[j].name().compareTo(LDAP_SERVER_FILTER_NAME) == 0) {
_log.info("\tFound properties of " + LDAP_SERVER_FILTER_NAME);
String encrValue = props[j].value();
System.out.println("Filter encrypted = " + encrValue);
try {
filter = StringEncrypter.getEncrypter().decrypt(encrValue);
} catch (Exception e) {
_log.error("Something went wrong while decrypting value for " + LDAP_SERVER_FILTER_NAME);
e.printStackTrace();
}
}
else if (props[j].name().compareTo(LDAP_SERVER_PRINCPAL_NAME) == 0) {
_log.info("\tFound properties of " + LDAP_SERVER_PRINCPAL_NAME);
String encrValue = props[j].value();
try {
principal = StringEncrypter.getEncrypter().decrypt(encrValue);
} catch (Exception e) {
_log.error("Something went wrong while decrypting value for " + LDAP_SERVER_PRINCPAL_NAME);
e.printStackTrace();
}
}
}
}
}
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ScheduledExecutorService ldapScheduler = Executors.newScheduledThreadPool(1);
ldapScheduler.scheduleAtFixedRate(new LDAPSync(ldapUrl, filter, principal, ldapPassword), 0, LDAP_MINUTES_DELAY, TimeUnit.MINUTES);
ScheduledExecutorService pop3Scheduler = Executors.newScheduledThreadPool(1);
pop3Scheduler.scheduleAtFixedRate(new PeriodicTask(store, portalName, pop3Server, pop3user, pop3password), 0, POP3_MINUTES_DELAY, TimeUnit.MINUTES);
String toReturn = "<DIV>Check Notification Email Started ... </DIV>";
toReturn += "<DIV>LDAPSync SCRIPT Started ... </DIV>";
response.setContentType("text/html");
response.getWriter().write(toReturn);

View File

@ -1,165 +0,0 @@
package org.gcube.portal.ldapexport;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.gcube.common.portal.PortalContext;
import org.gcube.portal.custom.communitymanager.OrganizationsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.Organization;
import com.liferay.portal.model.User;
import com.liferay.portal.service.OrganizationLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
public class LDAPSync implements Runnable {
private static final Logger _log = LoggerFactory.getLogger(LDAPSync.class);
private String ldapUrl;
private String filter;
private String principal;
private String pwd;
public LDAPSync(String ldapUrl, String filter, String principal, String pwd) {
this.ldapUrl = ldapUrl;
this.filter = filter;
this.principal = principal;
this.pwd = pwd;
_log.info("Starting LDAPSync over " + ldapUrl);
}
@Override
public void run() {
_log.debug("Reading Portal Users ...");
List<User> users = null;
try {
users = getAllLiferayUsers();
_log.debug("\n***Read " + users.size() + " from LR DB\n");
} catch (Exception e1) {
e1.printStackTrace();
}
_log.debug("Initializing LDAP exporter ...");
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUrl);
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS, pwd);
try {
DirContext ctx = new InitialDirContext(env);
_log.debug("Initiating LDAP Sync ...");
for (User user : users) {
updateUserInLDAP(user.getScreenName(), user.getFirstName(), user.getLastName(), user.getFullName(), user.getEmailAddress(), "{SHA}"+user.getPassword(), ctx, filter);
//_log.debug("Updated " + user.getScreenName());
}
_log.debug("LDAP Sync cycle done");
} catch (NamingException e) {
_log.error("Something went Wrong during LDAP Sync");
e.printStackTrace();
}
if (! users.isEmpty())
_log.info("LDAP Sync Completed OK!");
else
_log.warn("LDAP Sync cycle skipped this time");
}
private String getSubContext(String username) {
return "uid="+username+",ou=People,o=Liferay,ou=Organizations,dc=d4science,dc=org";
}
private boolean checkIfLDAPUserExists(String username, DirContext ctx, String filter) {
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answer;
try {
answer = ctx.search(getSubContext(username), filter, ctls);
} catch (NamingException e) {
_log.info("user: " + username + " not found in LDAP, trying to export it");
return false;
}
return answer.hasMoreElements();
}
/**
*
* @param username
* @param name
* @param lastName
* @param email
* @param passwd
* @param ctx
* @throws NamingException
*/
private void updateUserInLDAP(String username, String name, String lastName, String fullName, String email, String passwd, DirContext ctx, String filter) throws NamingException {
Attributes attributes=new BasicAttributes();
Attribute objectClass=new BasicAttribute("objectClass");
objectClass.add("inetOrgPerson");
attributes.put(objectClass);
//the main ldap server uses 'givenName' for the First name, 'cn' for "first name last name', 'sn' for the last name
Attribute givenName = new BasicAttribute("givenName");
Attribute cn = new BasicAttribute("cn");
Attribute sn = new BasicAttribute("sn");
Attribute mail = new BasicAttribute("mail");
Attribute userPassword = new BasicAttribute("userPassword");
givenName.add(name);
cn.add(fullName);
sn.add(lastName);
mail.add(email);
userPassword.add(passwd);
attributes.put(givenName);
attributes.put(cn);
attributes.put(sn);
attributes.put(mail);
attributes.put(userPassword);
if (checkIfLDAPUserExists(username, ctx, filter)) {
//_log.debug("User " + username + " already exists, replacing attributes");
ctx.modifyAttributes(getSubContext(username), DirContext.REPLACE_ATTRIBUTE, attributes);
}
else {
ctx.createSubcontext(getSubContext(username),attributes);
_log.debug("New User Found with uid=" + username + " created");
}
}
private List<User> getAllLiferayUsers() {
String infraName = PortalContext.getConfiguration().getInfrastructureName();
_log.info("TRY Reading non chached users belonging to: /" + infraName);
List<User> toReturn = new ArrayList<User>();
Organization rootInfra;
try {
CacheRegistryUtil.clear();
rootInfra = OrganizationLocalServiceUtil.getOrganization(OrganizationsUtil.getCompany().getCompanyId(), infraName);
toReturn = UserLocalServiceUtil.getOrganizationUsers(rootInfra.getOrganizationId());
} catch (PortalException | SystemException e) {
_log.error("Error during LDAP Sync, could not retrieve users from LR DB: " + e.getMessage());
}
return toReturn;
}
}

View File

@ -250,7 +250,7 @@ public class PeriodicTask implements Runnable {
for (String rec : recipientIds) {
_log.debug(rec);
}
_log.debug("Constructing repy message");
_log.debug("Constructing reply message");
messageText += getReplyHeaderMessage(sender, originalSentTime, originalText);
_log.debug("Trying to send message with subject: " + subject, " to: " + recipientIds.toString());

View File

@ -6,13 +6,13 @@
<display-name>Email Comments Reader Webapp</display-name>
<servlet>
<servlet-name>start-peridic-tasks</servlet-name>
<servlet-name>start-email-reader</servlet-name>
<servlet-class>org.gcube.portal.PortalSchedulerService</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>start-peridic-tasks</servlet-name>
<url-pattern>/start-peridic-tasks</url-pattern>
<servlet-name>start-email-reader</servlet-name>
<url-pattern>/start-email-reader</url-pattern>
</servlet-mapping>

View File

@ -1,7 +1,7 @@
<html>
<body>
<h2>Hello From Portal Scheduler service!</h2>
<h2>Hello From D4Science Email reader service!</h2>
<a href="./start-peridic-tasks">RUN Scheduler</a>
<a href="./start-email-reader">RUN Email reader service (repeat: every minute [Default])</a>
</body>
</html>