001/*
002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     mcedica@nuxeo.com
016 */
017package org.nuxeo.ecm.core.test;
018
019import java.io.File;
020import java.util.ArrayList;
021import java.util.List;
022
023import org.apache.commons.io.FileUtils;
024import org.nuxeo.common.Environment;
025import org.nuxeo.runtime.api.Framework;
026import org.nuxeo.runtime.test.runner.FeaturesRunner;
027import org.nuxeo.runtime.test.runner.SimpleFeature;
028
029import com.dumbster.smtp.SimpleSmtpServer;
030
031/**
032 * @since 5.7
033 */
034public class FakeSmtpMailServerFeature extends SimpleFeature {
035
036    public static final int SERVER_PORT = 2525;
037
038    public static final String SERVER_HOST = "127.0.0.1";
039
040    public static SimpleSmtpServer server;
041
042    @Override
043    public void beforeSetup(FeaturesRunner runner) throws Exception {
044        server = SimpleSmtpServer.start(SERVER_PORT);
045        if (Framework.isInitialized()) {
046
047            File file = new File(Environment.getDefault().getConfig(), "mail.properties");
048            file.getParentFile().mkdirs();
049            List<String> mailProperties = new ArrayList<String>();
050            mailProperties.add(String.format("mail.smtp.host = %s", SERVER_HOST));
051            mailProperties.add(String.format("mail.smtp.port = %s", SERVER_PORT));
052            FileUtils.writeLines(file, mailProperties);
053
054            Framework.getProperties().put("mail.transport.host", SERVER_HOST);
055            Framework.getProperties().put("mail.transport.port", SERVER_PORT);
056        }
057
058    }
059
060    @Override
061    public void afterTeardown(FeaturesRunner runner) throws Exception {
062        if (server != null) {
063            server.stop();
064        }
065    }
066}