001/* 002 * (C) Copyright 2012-2019 Nuxeo (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.mail.MailSessionBuilder; 035import org.nuxeo.runtime.api.Framework; 036 037/** 038 * @author matic 039 */ 040public class EmailResourceFactory implements ObjectFactory { 041 042 @Override 043 public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) { 044 final Reference ref = (Reference) obj; 045 if (!Session.class.getName().equals(ref.getClassName())) { 046 return null; 047 } 048 final Properties properties = toProperties(ref.getAll()); 049 return AccessController.doPrivileged( 050 (PrivilegedAction<Session>) () -> MailSessionBuilder.fromProperties(properties).build()); 051 052 } 053 054 protected Properties toProperties(Enumeration<RefAddr> attributes) { 055 Properties props = new Properties(); 056 while (attributes.hasMoreElements()) { 057 RefAddr attribute = attributes.nextElement(); 058 if ("factory".equals(attribute.getType())) { 059 continue; 060 } 061 String key = attribute.getType(); 062 String value = Framework.expandVars((String) attribute.getContent()); 063 props.put(key, value); 064 } 065 return props; 066 } 067}