/*
 * Copyright 2013-2014 the original author or authors.
 *
 * 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.springframework.cloud.aws.cache;

import com.amazonaws.services.elasticache.AmazonElastiCache;
import com.amazonaws.services.elasticache.model.CacheCluster;
import com.amazonaws.services.elasticache.model.DescribeCacheClustersRequest;
import com.amazonaws.services.elasticache.model.DescribeCacheClustersResult;
import com.amazonaws.services.elasticache.model.Endpoint;
import org.springframework.cloud.aws.cache.memcached.MemcachedClient;
import org.springframework.cloud.aws.core.env.ResourceIdResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AbstractFactoryBean;

import java.net.InetSocketAddress;

/**
 * @author Agim Emruli
 */
public class ElasticMemcachedFactoryBean extends AbstractFactoryBean<MemcachedClient> {

	private static final Logger LOGGER = LoggerFactory.getLogger(ElasticMemcachedFactoryBean.class);

	private final AmazonElastiCache amazonElastiCache;
	private final String cacheClusterId;
	private final ResourceIdResolver resourceIdResolver;

	public ElasticMemcachedFactoryBean(AmazonElastiCache amazonElastiCache, String cacheClusterId, ResourceIdResolver resourceIdResolver) {
		this.amazonElastiCache = amazonElastiCache;
		this.resourceIdResolver = resourceIdResolver;
		this.cacheClusterId = cacheClusterId;
	}

	public ElasticMemcachedFactoryBean(AmazonElastiCache amazonElastiCache, String cacheClusterId) {
		this(amazonElastiCache, cacheClusterId, null);
	}

	@Override
	public Class<MemcachedClient> getObjectType() {
		return MemcachedClient.class;
	}

	@Override
	protected MemcachedClient createInstance() throws Exception {
		DescribeCacheClustersResult describeCacheClustersResult = this.amazonElastiCache.describeCacheClusters(new DescribeCacheClustersRequest().withCacheClusterId(getCacheClusterName()));

		CacheCluster cacheCluster = describeCacheClustersResult.getCacheClusters().get(0);
		if (!"available".equals(cacheCluster.getCacheClusterStatus())) {
			LOGGER.warn("Cache cluster is not available now. Connection may fail during cache access. Current status is {}", cacheCluster.getCacheClusterStatus());
		}

		if (!"memcached".equals(cacheCluster.getEngine())) {
			throw new IllegalStateException("Currently only memcached is supported as the cache cluster engine");
		}

		Endpoint configurationEndpoint = cacheCluster.getConfigurationEndpoint();

		// We return every time one configuration endpoint. The amazon memcached client will connect to all nodes.
		return new MemcachedClient(new InetSocketAddress(configurationEndpoint.getAddress(), configurationEndpoint.getPort()));
	}

	@Override
	protected void destroyInstance(MemcachedClient instance) throws Exception {
		instance.shutdown();
	}

	private String getCacheClusterName() {
		return this.resourceIdResolver != null ? this.resourceIdResolver.resolveToPhysicalResourceId(this.cacheClusterId) : this.cacheClusterId;
	}
}

@@ -1294,16 +1294,54 @@
 Address;
+%0Aimport java.util.concurrent.TimeUnit;
 %0A%0A/**%0A *
@@ -1551,16 +1551,63 @@
 .class);
+%0A%09private static final int SHUTDOWN_DELAY = 10;
 %0A%0A%09priva
@@ -3409,28 +3409,216 @@
 %7B%0A%09%09
-instance.shutdown();
+boolean shutdownCompleted = instance.shutdown(SHUTDOWN_DELAY, TimeUnit.SECONDS);%0A%09%09if (!shutdownCompleted) %7B%0A%09%09%09LOGGER.warn(%22Error shutting down memcached client after :'%22 + SHUTDOWN_DELAY + %22' seconds%22);%0A%09%09%7D
 %0A%09%7D%0A

Add timeout while shutting down the memcached client