EasySMTAConnector.java

/**
 * Copyright 2014 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

package org.genesys.server.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLPeerUnverifiedException;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.genesys.server.exception.EasySMTAException;
import org.genesys.server.service.EasySMTA;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

@Profile({ "aws", "cacher" })
@Component
public class EasySMTAConnector implements EasySMTA {
	private static final Logger LOG = LoggerFactory.getLogger(EasySMTAConnector.class);

	@Value("${itpgrfa.easysmta.url}")
	private String serverUrl;

	@Value("${itpgrfa.easysmta.username}")
	private String serverUsername;

	@Value("${itpgrfa.easysmta.password}")
	private String serverPassword;

	@Override
	public EasySMTA.EasySMTAUserData getUserData(String emailAddress) throws EasySMTAException {
		
		LOG.info("Checking EasySMTA at {} for email: {}", serverUrl, emailAddress);
		final HttpPost httpPost = new HttpPost(serverUrl);

		final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("esUsername", serverUsername));
		nvps.add(new BasicNameValuePair("esPassword", serverPassword));
		nvps.add(new BasicNameValuePair("usEmail", emailAddress));
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		} catch (final UnsupportedEncodingException e1) {
			LOG.error(e1.getMessage(), e1);
			return null;
		}

		HttpResponse response = null;

		final BufferedReader br = null;

		final CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		try {
			LOG.info("Using {} as Easy-SMTA username.", serverUsername);
			response = httpclient.execute(httpPost);

			// Get hold of the response entity
			final HttpEntity entity = response.getEntity();
			if (LOG.isDebugEnabled()) {
				LOG.debug("{} {}", entity.getContentType(), entity.getContentLength());
			}
			
			// If the response does not enclose an entity, there is no
			// need to bother about connection release
			if (entity != null) {
				final ObjectMapper objectMapper = new ObjectMapper();
				final JsonNode tree = objectMapper.readTree(entity.getContent());
				LOG.info("EasySMTA: {}", tree);

				if (tree.has("errorCode")) {
					// Check failed
					LOG.warn("Checking PID server failed with: {}", tree);

					// TODO Report various errorCodes!

				} else {
					return objectMapper.readValue(tree.toString(), EasySMTA.EasySMTAUserData.class);
				}
			}
		} catch (final SSLPeerUnverifiedException e) {
			throw new EasySMTAException("Secure connection to EasySMTA failed. Certificate invalid.", e);
		} catch (final ClientProtocolException e) {
			LOG.error(e.getMessage(), e);
			throw new EasySMTAException(e.getMessage(), e);
		} catch (final IOException e) {
			LOG.error(e.getMessage(), e);
			throw new EasySMTAException(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(br);
			httpPost.releaseConnection();
			IOUtils.closeQuietly(httpclient);
			LOG.debug("EasySMTA streams closed.");
		}

		return null;
	}

}