All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.khaleesi.carfield.tools.sparkjobserver.api.SparkJobServerClientFactory Maven / Gradle / Ivy

The newest version!
package org.khaleesi.carfield.tools.sparkjobserver.api;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

/**
 * The factory is responsible for creating instance of ISparkJobServerClient
 * to communicate with the Spark Job Server with the arranged rest apis.
 * 
 * @author bluebreezecf
 * @since 2014-09-07
 *
 */
public final class SparkJobServerClientFactory {
	private static final SparkJobServerClientFactory INSTANCE = new SparkJobServerClientFactory();
	
	private static Logger logger = Logger.getLogger(SparkJobServerClientFactory.class);
	
	private static Map jobServerClientCache 
	    = new ConcurrentHashMap();
	
	/**
	 * The default constructor of SparkJobServerClientFactory. 
	 */
	private SparkJobServerClientFactory() {
	}
	
	/**
	 * Gets the unique instance of SparkJobServerClientFactory.
	 * @return the instance of SparkJobServerClientFactory
	 */
	public static SparkJobServerClientFactory getInstance() {
		return INSTANCE;
	}
	
	/**
	 * Creates an instance of ISparkJobServerClient with the given url.
	 * 
	 * @param url the url of the target Spark Job Server
	 * @return the corresponding ISparkJobServerClient instance
	 * @throws SparkJobServerClientException error occurs when trying to create the 
	 *     target spark job server client
	 */
	public ISparkJobServerClient createSparkJobServerClient(String url) 
		throws SparkJobServerClientException {
		if (!isValidUrl(url)) {
			throw new SparkJobServerClientException("Invalid url can't be used to create a spark job server client.");
		}
		String sparkJobServerUrl = url.trim();
		ISparkJobServerClient sparkJobServerClient = jobServerClientCache.get(sparkJobServerUrl);
		if (null == sparkJobServerClient) {
			sparkJobServerClient = new SparkJobServerClientImpl(url);
			jobServerClientCache.put(url, sparkJobServerClient);
		}
		return sparkJobServerClient;
	}
	
	/**
	 * Checks the given url is valid or not.
	 * 
	 * @param url the url to be checked
	 * @return true if it is valid, false otherwise
	 */
	private boolean isValidUrl(String url) {
		if (url == null || url.trim().length() <= 0) {
			logger.error("The given url is null or empty.");
			return false;
		}
		try {
			new URL(url);
		} catch (MalformedURLException me) {
			StringBuffer buff = new StringBuffer("The given url ");
			buff.append(url).append(" is invalid.");
			logger.error(buff.toString(), me);
		}
		return true;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy