001/* 002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * matic 018 */ 019package org.nuxeo.ecm.platform.ec.notification.email; 020 021import java.security.AccessController; 022import java.security.PrivilegedAction; 023import java.util.Enumeration; 024import java.util.Hashtable; 025import java.util.Properties; 026 027import javax.mail.Session; 028import javax.naming.Context; 029import javax.naming.Name; 030import javax.naming.RefAddr; 031import javax.naming.Reference; 032import javax.naming.spi.ObjectFactory; 033 034import org.nuxeo.runtime.api.Framework; 035 036/** 037 * @author matic 038 */ 039public class EmailResourceFactory implements ObjectFactory { 040 041 @Override 042 public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) { 043 final Reference ref = (Reference) obj; 044 if (!ref.getClassName().equals("javax.mail.Session")) 045 return (null); 046 final Properties properties = toProperties(ref.getAll()); 047 return AccessController.doPrivileged((PrivilegedAction<Session>) () -> EmailHelper.newSession(properties)); 048 049 } 050 051 protected Properties toProperties(Enumeration<RefAddr> attributes) { 052 Properties props = new Properties(); 053 while (attributes.hasMoreElements()) { 054 RefAddr attribute = attributes.nextElement(); 055 if ("factory".equals(attribute.getType())) { 056 continue; 057 } 058 String key = attribute.getType(); 059 String value = Framework.expandVars((String) attribute.getContent()); 060 props.put(key, value); 061 } 062 return props; 063 } 064}