package com.cisco.server;
import java.util.Properties;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy;
import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;
import org.apache.log4j.Logger;
public class ServerConfiguration {
private static Logger logger = Logger.getLogger(ServerConfiguration.class);
private static final int POOL_SIZE = 10;
private static final int MAX_POOL_SIZE = 100;
private static final int MAX_REQUEST_QUEUE_SIZE = 1000;
private static final int DEFAULT_SERVER_PORT = 23;
public static final String DEFAULT_REJECTED_EXECUTION_HANDLER = "DiscardPolicy";
private final Properties properties = new Properties();
private final int serverPort;
private final int poolSize;
private final int maxPoolSize;
private final int maxRequestQueueSize;
private final String rejectedExecutionHandler;
public ServerConfiguration() {
loadProperties();
serverPort = getIntProperty("serverPort", DEFAULT_SERVER_PORT);
poolSize = getIntProperty("nthreads", POOL_SIZE);
maxPoolSize = getIntProperty("maxNthreads", MAX_POOL_SIZE);
maxRequestQueueSize = getIntProperty("maxRequestQueueSize", MAX_REQUEST_QUEUE_SIZE);
rejectedExecutionHandler = getStringProperty("rejectedExecutionHandler", DEFAULT_REJECTED_EXECUTION_HANDLER);
}
private void loadProperties() {
try {
java.net.URL url = ServerConfiguration.class.getClassLoader().getResource("conf/server.properties");
properties.load(url.openStream());
} catch (Exception e) {
logger.error(e);
}
}
private String getStringProperty(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}
private int getIntProperty(String key, int defaultValue) {
return Integer.parseInt(properties.getProperty(key, defaultValue + ""));
}
public int getServerPort() {
return serverPort;
}
public int getPoolSize() {
return poolSize;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public int getMaxRequestQueueSize() {
return maxRequestQueueSize;
}
public RejectedExecutionHandler getRejectedExecutionHandler() {
if (rejectedExecutionHandler.equals("AbortPolicy")) {
return new AbortPolicy();
} else if (rejectedExecutionHandler.equals("CallerRunsPolicy")) {
return new CallerRunsPolicy();
} else if (rejectedExecutionHandler.equals("DiscardOldestPolicy")) {
return new DiscardOldestPolicy();
} else {// default "DiscardPolicy"
return new DiscardPolicy();
}
}
@Override
public String toString() {
String configuration = "Server configuration:\n";
configuration += "- serverPort:" + serverPort + "\n";
configuration += "- poolSize:" + poolSize + "\n";
configuration += "- maxPoolSize:" + maxPoolSize + "\n";
configuration += "- maxRequestQueueSize:" + maxRequestQueueSize + "\n";
configuration += "- rejectedExecutionHandler:" + rejectedExecutionHandler;
return configuration;
}
}