speed stackss+mediaserver

jetty Web Server 自制应用服务器_小组_ThinkSAAS
jetty Web Server 自制应用服务器
jetty Web Server 自制应用服务器
jetty Web Server 自制应用服务器,取自于我的最近在集群中也参考国外一个jetty写的很好服务器博客中提到一个经验而写的。感觉速度和性能有很大提高。
1.main class 如下;
public final class Bootstrap {
//~ Static fields/initializers =============================================
private static final String SHUTDOWN ="SHUTDOWN";
private static final String RELOAD ="RELOAD";
//~ Instance fields ========================================================
* The port number on which we wait for shutdown commands.
* A random number generator that is only used if
* the shutdown command string is longer than 1024 characters.
private Random random =
//~ Constructors ===========================================================
private Bootstrap() {
//~ Methods ================================================================
private Logger getLogger() {
if (logger == null) {
logger = LoggerFactory.getLogger(getClass());
public void init() {
String painiuHome = System.getProperty("net365.home", System.getProperty("user.dir","."));
String configDir = System.getProperty("net365.config.dir");
if (configDir == null) {
configDir = painiuHome + File.separator +"etc"+ File.
if (!configDir.endsWith(File.separator)) {
configDir += File.
String configFile = configDir +"net365.properties";
Map vars = new HashMap();
vars.put("home", painiuHome);
Configuration.initialize(configFile, vars);
initLoggingSystem(configDir);
port = Configuration.getInteger("server.shutdown.port", 8014);
private void initLoggingSystem(String configDir) {
File loggingConfigFile = new File(configDir,"logging.properties");
if (loggingConfigFile.exists()) {
System.setProperty("java.util.logging.config.file", loggingConfigFile.getAbsolutePath());
File log4jConfigFile = new File(configDir,"log4j.properties");
if (log4jConfigFile.exists()) {
PropertyConfigurator.configure(log4jConfigFile.getAbsolutePath());
public void startServer() throws Exception {
getLogger().info("Bootstrap: Starting Server...");
server = new Server();
server.initialize();
server.setGracefulShutdown(Configuration.getInteger("server.shutdown.timeout", 0));
server.setStopAtShutdown(true);
server.start();
public void stopServer() throws Exception {
getLogger().info("Bootstrap: Stopping Server...");
server.stop();
public static void main(String[] args) {
Bootstrap bootstrap = new Bootstrap();
bootstrap.init();
String command ="start";
if (args.length & 0) {
command = args[args.length - 1];
if (command.equals("start")) {
bootstrap.startServer();
bootstrap.await();
bootstrap.stopServer();
} else if (command.equals("stop")) {
bootstrap.stop();
} else if (command.equals("restart")) {
bootstrap.stop();
// give me 2 seconds to shutdown the server
Thread.sleep(2000);
} catch (InterruptedException e) {}
bootstrap.startServer();
bootstrap.await();
bootstrap.stopServer();
} else if (command.equals("reload")) {
bootstrap.reload();
System.exit(0);
} catch (Throwable t) {
t.printStackTrace();
public void stop() {
sendCommand(SHUTDOWN);
public void reload() {
sendCommand(RELOAD);
private void sendCommand(String command) {
Socket socket = new Socket("127.0.0.1", port);
OutputStream stream = socket.getOutputStream();
for (int i = 0; i & command.length(); i++) {
stream.write(command.charAt(i));
stream.flush();
stream.close();
socket.close();
} catch (IOException e) {
getLogger().error("IOException occurred:", e);
public void await() {
// Set up a server socket to wait on
ServerSocket serverSocket =
serverSocket =
new ServerSocket(port, 1,
InetAddress.getByName("127.0.0.1"));
} catch (IOException e) {
getLogger().error("Bootstrap.await: create["+ port +"]:", e);
System.exit(1);
// Loop waiting for a connection and a valid command
while (true) {
// Wait for the next connection
Socket socket =
InputStream stream =
socket = serverSocket.accept();
socket.setSoTimeout(10 * 1000); // Ten seconds
stream = socket.getInputStream();
} catch (AccessControlException ace) {
getLogger().warn("StandardServer.accept security exception:"+ ace.getMessage(), ace);
} catch (IOException e) {
getLogger().error("StandardServer.await: accept:", e);
System.exit(1);
// Read a set of characters from the socket
StringBuffer command = new StringBuffer();
int expected = 1024; // Cut off to avoid DoS attack
while (expected & SHUTDOWN.length()) {
if (random == null)
random = new Random(System.currentTimeMillis());
expected += (random.nextInt() % 1024);
while (expected & 0) {
int ch = -1;
ch = stream.read();
} catch (IOException e) {
getLogger().warn("Bootstrap.await: read:", e);
if (ch & 32) // Control character or EOF terminates loop
command.append((char) ch);
expected--;
// Close the socket now that we are done with it
socket.close();
} catch (IOException e) {
// Match against our command string
if (command.toString().equals(SHUTDOWN)) {
} else if (command.toString().equals(RELOAD)) {
server.reload();
} catch (Exception e) {
getLogger().error("Bootstrap.reloading failed", e);
getLogger().warn("Bootstrap.await: Invalid command '"+
command.toString() +"' received");
// Close the server socket and return
serverSocket.close();
} catch (IOException e) {
2.server class 如下:
public class Server extends org.mortbay.jetty.Server {
//~ Static fields/initializers =============================================
private static final Logger logger = LoggerFactory.getLogger(Server.class);
//~ Instance fields ========================================================
private ClassPathXmlApplicationContext applicationC
private RemotingServer remotingS
//~ Constructors ===========================================================
public Server() {
//~ Methods ================================================================
private void initApplicationContext() {
String configLocation = Configuration.get("spring.config.location","applicationContext*.xml");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
context.setConfigLocation(context.CLASSPATH_ALL_URL_PREFIX + configLocation);
context.refresh();
applicationContext =
//private void initYPFS() {
//YPFS.initialize(null);
private SecurityHandler createSecurityHandler() {
return new SecurityHandler();
private SessionHandler createSessionHandler() {
//SessionManager sessionManager = (SessionManager) applicationContext.getBean("jettySessionManager");
//if (sessionManager == null) {
//logger.error("SessionManager not configured! use default: HashSessionManager");
SessionManager sessionManager = new HashSessionManager();
sessionManager.setSessionDomain("."+ Configuration.get("webapp.domain"));
return new SessionHandler(sessionManager);
private ErrorHandler createErrorHandler() {
ErrorHandler handler = new ErrorHandler();
handler.setShowStacks(Configuration.getBoolean("devmode", false));
public void reload() throws Exception {
applicationContext.refresh();
webapp.stop();
webapp.start();
public void initialize() throws Exception {
initApplicationContext();
//initYPFS();
Connector connector = new SelectChannelConnector();
connector.setPort(Configuration.getInteger("server.port", 8080));
setConnectors(new Connector[] { connector });
webapp = initWebAppHandler();
if (Configuration.getBoolean("devmode", false)) {
// setup static context for development
List handlers = new ArrayList(3);
handlers.add(webapp);
if (Configuration.get("server.media.vhosts") != null) {
handlers.add(initStaticContext());
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));
setHandler(contexts);
setHandler(webapp);
private Handler initStaticContext() {
ResourceHandler staticHandler = new ResourceHandler();
ContextHandler staticContext = new ContextHandler();
staticContext.setContextPath("/");
staticContext.setResourceBase(Configuration.get("server.media.war"));
staticContext.setHandler(staticHandler);
String vhosts = Configuration.get("server.media.vhosts","");
("Starting media server, vhosts: {}", vhosts);
staticContext.setVirtualHosts(StringUtils.split(vhosts));
return staticC
/* (non-Javadoc)
* @see org.mortbay.jetty.Server#doStop()
protected void doStop() throws Exception {
("Shutting down...");
super.doStop();
if (remotingServer != null) {
("Stopping remoting server...");
remotingServer.stop();
applicationContext.destroy();
private Handler initWebAppHandler() throws IOException {
WebAppContext context = new WebAppContext(createSecurityHandler(), createSessionHandler(), null, createErrorHandler());
context.setDefaultsDescriptor("com/net365/server/jetty/webdefault.xml");
context.setContextPath(Configuration.get("webapp.contextPath","/"));
context.setWar(Configuration.get("server.war"));
context.setExtractWAR(false);
context.setParentLoaderPriority(true);
context.setTempDirectory(new File(Configuration.get("server.tmpDir")));
context.setAttribute(B2CEshop.APPLICATION_CONTEXT_KEY, applicationContext);
if (Configuration.getBoolean("devmode", false)) {
String vhosts = Configuration.get("server.vhosts","");
("Starting server in DevMode, vhosts: {}", vhosts);
context.setVirtualHosts(StringUtils.split(vhosts));
InputStream in =
Resource resource = context.getWebInf().addPath("urlrewrite.xml");
if (resource == null || !resource.exists()) {
logger.error("Url rewrite rules not found, url rewrite will not be supported");
in = resource.getInputStream();
RewriteHandler handler = new RewriteHandler();
handler.setHandler(context);
handler.setRules(loadRewriteRules(in));
handler.setActionExtension(Configuration.get("webapp.action.extension"));
} finally {
if (in != null) {
in.close();
} catch (IOException e) {
logger.error("Error closing urlrewrite configuration file", e);
private static Rule[] loadRewriteRules(InputStream in) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
parser = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
logger.error("Unable to setup XML parser for reading conf", e);
DefaultHandler handler = new DefaultHandler();
parser.setErrorHandler(handler);
parser.setEntityResolver(handler);
List rules = new ArrayList();
Document doc = parser.parse(in);
Element rootElement = doc.getDocumentElement();
NodeList categoryList = rootElement.getChildNodes();
for (int i = 0; i & categoryList.getLength(); i++) {
Node node = categoryList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE &&
((Element) node).getTagName().equals("category")) {
String categoryName = getAttrValue(node,"name");
NodeList ruleList = node.getChildNodes();
for (int j = 0; j & ruleList.getLength(); j++) {
Node subNode = ruleList.item(j);
if (subNode.getNodeType() == Node.ELEMENT_NODE &&
((Element) subNode).getTagName().equals("rule")) {
Element ruleElement = (Element) subN
RewriteRegexRule rule = new RewriteRegexRule();
rule.setCategory(categoryName);
rule.setRegex(getNodeValue(ruleElement.getElementsByTagName("from").item(0)));
rule.setReplacement(getNodeValue(ruleElement.getElementsByTagName("to").item(0)));
rules.add(rule);
} catch (SAXParseException e) {
logger.error("Parse error on line"+ e.getLineNumber() +""+ e.getMessage(), e);
} catch (Exception e) {
logger.error("Exception loading conf"+ e.getMessage(), e);
return rules.toArray(new Rule[rules.size()]);
private static String getNodeValue(Node node) {
if (node == null)
NodeList nodeList = node.getChildNodes();
if (nodeList == null)
Node child = nodeList.item(0);
if (child == null)
if ((child.getNodeType() == Node.TEXT_NODE)) {
String value = ((Text) child).getData();
return value.trim();
private static String getAttrValue(Node n, String attrName) {
if (n == null)
NamedNodeMap attrs = n.getAttributes();
if (attrs == null)
Node attr = attrs.getNamedItem(attrName);
if (attr == null)
String val = attr.getNodeValue();
if (val == null)
return val.trim();
* @(#)Bootstrap.java
* Copyright 2009 Net365. All rights reserved.
package com.painiu.server.
import java.io.F
import java.io.IOE
import java.io.InputS
import java.io.OutputS
import java.net.InetA
import java.net.ServerS
import java.net.S
import java.security.AccessControlE
import java.util.HashM
import java.util.M
import java.util.R
import org.apache.log4j.PropertyC
import org.slf4j.L
import org.slf4j.LoggerF
import com.painiu.config.C
* &a href="Monitor.java.html"&&i&View Source&/i&&/a&
* @author Zhang Songfu
* @version $Id$
public final class Bootstrap {
//~ Static fields/initializers =============================================
private static final String SHUTDOWN ="SHUTDOWN";
private static final String RELOAD ="RELOAD";
//~ Instance fields ========================================================
* The port number on which we wait for shutdown commands.
* A random number generator that is &strong&only&/strong& used if
* the shutdown command string is longer than 1024 characters.
private Random random =
//~ Constructors ===========================================================
private Bootstrap() {
//~ Methods ================================================================
private Logger getLogger() {
if (logger == null) {
logger = LoggerFactory.getLogger(getClass());
public void init() {
String painiuHome = System.getProperty("painiu.home", System.getProperty("user.dir","."));
String configDir = System.getProperty("painiu.config.dir");
if (configDir == null) {
configDir = painiuHome + File.separator +"etc"+ File.
if (!configDir.endsWith(File.separator)) {
configDir += File.
String configFile = configDir +"painiu.properties";
Map&String, String& vars = new HashMap&String, String&();
vars.put("home", painiuHome);
Configuration.initialize(configFile, vars);
initLoggingSystem(configDir);
port = Configuration.getInteger("server.shutdown.port", 8014);
private void initLoggingSystem(String configDir) {
File loggingConfigFile = new File(configDir,"logging.properties");
if (loggingConfigFile.exists()) {
System.setProperty("java.util.logging.config.file", loggingConfigFile.getAbsolutePath());
File log4jConfigFile = new File(configDir,"log4j.properties");
if (log4jConfigFile.exists()) {
PropertyConfigurator.configure(log4jConfigFile.getAbsolutePath());
public void startServer() throws Exception {
getLogger().info("Bootstrap: Starting Server...");
server = new Server();
server.initialize();
server.setGracefulShutdown(Configuration.getInteger("server.shutdown.timeout", 0));
server.setStopAtShutdown(true);
server.start();
public void stopServer() throws Exception {
getLogger().info("Bootstrap: Stopping Server...");
server.stop();
public static void main(String[] args) {
Bootstrap bootstrap = new Bootstrap();
bootstrap.init();
String command ="start";
if (args.length & 0) {
command = args[args.length - 1];
if (command.equals("start")) {
bootstrap.startServer();
bootstrap.await();
bootstrap.stopServer();
} else if (command.equals("stop")) {
bootstrap.stop();
} else if (command.equals("restart")) {
bootstrap.stop();
// give me 2 seconds to shutdown the server
Thread.sleep(2000);
} catch (InterruptedException e) {}
bootstrap.startServer();
bootstrap.await();
bootstrap.stopServer();
} else if (command.equals("reload")) {
bootstrap.reload();
System.exit(0);
} catch (Throwable t) {
t.printStackTrace();
public void stop() {
sendCommand(SHUTDOWN);
public void reload() {
sendCommand(RELOAD);
private void sendCommand(String command) {
Socket socket = new Socket("127.0.0.1", port);
OutputStream stream = socket.getOutputStream();
for (int i = 0; i & command.length(); i++) {
stream.write(command.charAt(i));
stream.flush();
stream.close();
socket.close();
} catch (IOException e) {
getLogger().error("IOException occurred:", e);
public void await() {
// Set up a server socket to wait on
ServerSocket serverSocket =
serverSocket =
new ServerSocket(port, 1,
InetAddress.getByName("127.0.0.1"));
} catch (IOException e) {
getLogger().error("Bootstrap.await: create["+ port +"]:", e);
System.exit(1);
// Loop waiting for a connection and a valid command
while (true) {
// Wait for the next connection
Socket socket =
InputStream stream =
socket = serverSocket.accept();
socket.setSoTimeout(10 * 1000); // Ten seconds
stream = socket.getInputStream();
} catch (AccessControlException ace) {
getLogger().warn("StandardServer.accept security exception:"+ ace.getMessage(), ace);
} catch (IOException e) {
getLogger().error("StandardServer.await: accept:", e);
System.exit(1);
// Read a set of characters from the socket
StringBuffer command = new StringBuffer();
int expected = 1024; // Cut off to avoid DoS attack
while (expected & SHUTDOWN.length()) {
if (random == null)
random = new Random(System.currentTimeMillis());
expected += (random.nextInt() % 1024);
while (expected & 0) {
int ch = -1;
ch = stream.read();
} catch (IOException e) {
getLogger().warn("Bootstrap.await: read:", e);
if (ch & 32) // Control character or EOF terminates loop
command.append((char) ch);
expected--;
// Close the socket now that we are done with it
socket.close();
} catch (IOException e) {
// Match against our command string
if (command.toString().equals(SHUTDOWN)) {
} else if (command.toString().equals(RELOAD)) {
server.reload();
} catch (Exception e) {
getLogger().error("Bootstrap.reloading failed", e);
getLogger().warn("Bootstrap.await: Invalid command '"+
command.toString() +"' received");
// Close the server socket and return
serverSocket.close();
} catch (IOException e) {
* @(#)Server.java
* Copyright 2009 Net365. All rights reserved.
package com.painiu.server.
import java.io.F
import java.io.IOE
import java.io.InputS
import java.util.ArrayL
import java.util.I
import java.util.L
import java.util.M
import javax.xml.parsers.DocumentB
import javax.xml.parsers.DocumentBuilderF
import javax.xml.parsers.ParserConfigurationE
import mons.lang.StringU
import org.apache.mina.core.service.IoH
import org.mortbay.jetty.C
import org.mortbay.jetty.H
import org.mortbay.jetty.SessionM
import org.mortbay.jetty.handler.ContextH
import org.mortbay.jetty.handler.ContextHandlerC
import org.mortbay.jetty.handler.ResourceH
import org.mortbay.jetty.handler.RequestLogH
import org.mortbay.jetty.nio.SelectChannelC
import org.mortbay.jetty.security.SecurityH
import org.mortbay.jetty.servlet.HashSessionM
import org.mortbay.jetty.servlet.SessionH
import org.mortbay.jetty.webapp.WebAppC
import org.mortbay.resource.R
import org.slf4j.L
import org.slf4j.LoggerF
import org.springframework.context.support.ClassPathXmlApplicationC
import org.w3c.dom.D
import org.w3c.dom.E
import org.w3c.dom.NamedNodeM
import org.w3c.dom.N
import org.w3c.dom.NodeL
import org.w3c.dom.T
import org.xml.sax.SAXParseE
import org.xml.sax.helpers.DefaultH
import com.painiu.P
import com.painiu.config.C
import com.painiu.remoting.ServiceR
import com.painiu.remoting.server.RemotingS
import com.painiu.server.jetty.rewrite.RewriteH
import com.painiu.server.jetty.rewrite.RewriteRegexR
import com.painiu.server.jetty.rewrite.R
* &a href="Server.java.html"&&i&View Source&/i&&/a&
* @author Zhang Songfu
* @version $Id$
public class Server extends org.mortbay.jetty.Server {
//~ Static fields/initializers =============================================
private static final Logger logger = LoggerFactory.getLogger(Server.class);
//~ Instance fields ========================================================
private ClassPathXmlApplicationContext applicationC
private RemotingServer remotingS
//~ Constructors ===========================================================
public Server() {
//~ Methods ================================================================
private void initApplicationContext() {
String configLocation = Configuration.get("spring.config.location","applicationContext*.xml");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
context.setConfigLocation(context.CLASSPATH_ALL_URL_PREFIX + configLocation);
context.refresh();
applicationContext =
//private void initYPFS() {
//YPFS.initialize(null);
private SecurityHandler createSecurityHandler() {
return new SecurityHandler();
private SessionHandler createSessionHandler() {
//SessionManager sessionManager = (SessionManager) applicationContext.getBean("jettySessionManager");
//if (sessionManager == null) {
//logger.error("SessionManager not configured! use default: HashSessionManager");
SessionManager sessionManager = new HashSessionManager();
sessionManager.setSessionDomain("."+ Configuration.get("webapp.domain"));
return new SessionHandler(sessionManager);
private ErrorHandler createErrorHandler() {
ErrorHandler handler = new ErrorHandler();
handler.setShowStacks(Configuration.getBoolean("devmode", false));
public void reload() throws Exception {
applicationContext.refresh();
webapp.stop();
webapp.start();
public void initialize() throws Exception {
initApplicationContext();
//initYPFS();
Connector connector = new SelectChannelConnector();
connector.setPort(Configuration.getInteger("server.port", 8080));
setConnectors(new Connector[] { connector });
webapp = initWebAppHandler();
if (Configuration.getBoolean("devmode", false)) {
// setup static context for development
List&Handler& handlers = new ArrayList&Handler&(3);
handlers.add(webapp);
if (Configuration.get("server.media.vhosts") != null) {
handlers.add(initStaticContext());
if (Configuration.get("solr.mode","standalone").equals("embedded")) {
handlers.add(initSolrContext());
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));
setHandler(contexts);
setHandler(webapp);
if (Configuration.getBoolean("remoting.server.enabled", false)) {
startRemotingServer();
private Handler initStaticContext() {
ResourceHandler staticHandler = new ResourceHandler();
ContextHandler staticContext = new ContextHandler();
staticContext.setContextPath("/");
staticContext.setResourceBase(Configuration.get("server.media.war"));
staticContext.setHandler(staticHandler);
String vhosts = Configuration.get("server.media.vhosts","");
("Starting media server, vhosts: {}", vhosts);
staticContext.setVirtualHosts(StringUtils.split(vhosts));
return staticC
private Handler initSolrContext() {
System.setProperty("solr.home", Configuration.get("solr.home"));
System.setProperty("solr.data.dir", Configuration.get("solr.data.dir"));
WebAppContext solr = new WebAppContext();
solr.setContextPath("/");
solr.setWar(Configuration.get("solr.war"));
solr.setExtractWAR(true);
solr.setParentLoaderPriority(true);
solr.setTempDirectory(new File(Configuration.get("server.tmpDir")));
String vhosts = Configuration.get("solr.vhosts","");
("Starting solr server, vhosts: {}", vhosts);
solr.setVirtualHosts(StringUtils.split(vhosts));
@SuppressWarnings("unchecked")
private void startRemotingServer() {
int port = Configuration.getInteger("remoting.server.port", 8787);
int idle = Configuration.getInteger("remoting.server.idleTime", 10);
Map services = (Map) applicationContext.getBean("remoteServices");
if (services == null) {
logger.error("remoteServices not found, remoting service server is not started");
for (Iterator i = services.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
Class&?& iface = Class.forName((String) entry.getKey());
ServiceRegistry.register(iface, entry.getValue());
} catch (ClassNotFoundException e) {
logger.error("Service interface: {} not found, service ignored", entry.getKey());
remotingServer = new RemotingServer(port, idle);
IoHandler handler = (IoHandler) applicationContext.getBean("remoteServiceHandler");
if (handler != null) {
remotingServer.setHandler(handler);
remotingServer.start();
} catch (Throwable e) {
logger.error("Exception occurred while starting remote server", e);
("Remoting server listening on port: {}", port);
/* (non-Javadoc)
* @see org.mortbay.jetty.Server#doStop()
protected void doStop() throws Exception {
("Shutting down...");
super.doStop();
if (remotingServer != null) {
("Stopping remoting server...");
remotingServer.stop();
//YPFS.shutdown();
applicationContext.destroy();
private Handler initWebAppHandler() throws IOException {
WebAppContext context = new WebAppContext(createSecurityHandler(), createSessionHandler(), null, createErrorHandler());
context.setDefaultsDescriptor("com/painiu/server/jetty/webdefault.xml");
context.setContextPath(Configuration.get("webapp.contextPath","/"));
context.setWar(Configuration.get("server.war"));
context.setExtractWAR(false);
context.setParentLoaderPriority(true);
context.setTempDirectory(new File(Configuration.get("server.tmpDir")));
context.setAttribute(Painiu.APPLICATION_CONTEXT_KEY, applicationContext);
if (Configuration.getBoolean("devmode", false)) {
String vhosts = Configuration.get("server.vhosts","");
("Starting server in DevMode, vhosts: {}", vhosts);
context.setVirtualHosts(StringUtils.split(vhosts));
InputStream in =
Resource resource = context.getWebInf().addPath("urlrewrite.xml");
if (resource == null || !resource.exists()) {
logger.error("Url rewrite rules not found, url rewrite will not be supported");
in = resource.getInputStream();
RewriteHandler handler = new RewriteHandler();
handler.setHandler(context);
handler.setRules(loadRewriteRules(in));
handler.setActionExtension(Configuration.get("webapp.action.extension"));
} finally {
if (in != null) {
in.close();
} catch (IOException e) {
logger.error("Error closing urlrewrite configuration file", e);
private static Rule[] loadRewriteRules(InputStream in) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
parser = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
logger.error("Unable to setup XML parser for reading conf", e);
DefaultHandler handler = new DefaultHandler();
parser.setErrorHandler(handler);
parser.setEntityResolver(handler);
List&Rule& rules = new ArrayList&Rule&();
Document doc = parser.parse(in);
Element rootElement = doc.getDocumentElement();
NodeList categoryList = rootElement.getChildNodes();
for (int i = 0; i & categoryList.getLength(); i++) {
Node node = categoryList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE &&
((Element) node).getTagName().equals("category")) {
String categoryName = getAttrValue(node,"name");
NodeList ruleList = node.getChildNodes();
for (int j = 0; j & ruleList.getLength(); j++) {
Node subNode = ruleList.item(j);
if (subNode.getNodeType() == Node.ELEMENT_NODE &&
((Element) subNode).getTagName().equals("rule")) {
Element ruleElement = (Element) subN
RewriteRegexRule rule = new RewriteRegexRule();
rule.setCategory(categoryName);
rule.setRegex(getNodeValue(ruleElement.getElementsByTagName("from").item(0)));
rule.setReplacement(getNodeValue(ruleElement.getElementsByTagName("to").item(0)));
rules.add(rule);
} catch (SAXParseException e) {
logger.error("Parse error on line"+ e.getLineNumber() +""+ e.getMessage(), e);
} catch (Exception e) {
logger.error("Exception loading conf"+ e.getMessage(), e);
return rules.toArray(new Rule[rules.size()]);
private static String getNodeValue(Node node) {
if (node == null)
NodeList nodeList = node.getChildNodes();
if (nodeList == null)
Node child = nodeList.item(0);
if (child == null)
if ((child.getNodeType() == Node.TEXT_NODE)) {
String value = ((Text) child).getData();
return value.trim();
private static String getAttrValue(Node n, String attrName) {
if (n == null)
NamedNodeMap attrs = n.getAttributes();
if (attrs == null)
Node attr = attrs.getNamedItem(attrName);
if (attr == null)
String val = attr.getNodeValue();
if (val == null)
return val.trim();
&util:properties id="jdbcConfiguration"location="classpath:jdbc.properties"/&
&bean id="dataSourceFactory"class="com.painiu.core.dao.support.DbcpDataSourceFactory"/&
&bean id="dataSource"class="com.painiu.core.dao.support.DataSourceFactoryBean"&
&property name="properties"&&ref local="jdbcConfiguration"/&&/property&
&property name="dataSourceFactory"&&ref local="dataSourceFactory"/&&/property&
* @(#)DataSourceFactory.java Jul 18, 2009
* Copyright 2009 Net365. All rights reserved.
package com.painiu.core.dao.
import java.util.P
import javax.sql.DataS
* &a href="DataSourceFactory.java.html"&&i&View Source&/i&&/a&
* @author Zhang Songfu
* @version $Id: DataSourceFactory.java -04-15 09:28:48Z zhangsongfu $
public interface DataSourceFactory {
public DataSource createDataSource(Properties props) throws E
* @(#)DataSourceFactoryBean.java Jul 18, 2009
* Copyright 2009 Net365. All rights reserved.
package com.painiu.core.dao.
import java.util.P
import javax.sql.DataS
import org.springframework.beans.factory.FactoryB
import org.springframework.beans.factory.InitializingB
import org.springframework.util.A
* &a href="DataSourceFactoryBean.java.html"&&i&View Source&/i&&/a&
* @author Zhang Songfu
* @version $Id: DataSourceFactoryBean.java -04-15 09:28:48Z zhangsongfu $
public class DataSourceFactoryBean implements FactoryBean, InitializingBean {
//~ Static fields/initializers =============================================
//~ Instance fields ========================================================
private DataSourceFactory dataSourceF
private DataSource dataS
//~ Constructors ===========================================================
//~ Methods ================================================================
/* (non-Javadoc)
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
public void afterPropertiesSet() throws Exception {
Assert.notNull(dataSourceFactory);
Assert.notNull(properties);
dataSource = dataSourceFactory.createDataSource(properties);
/* (non-Javadoc)
* @see org.springframework.beans.factory.FactoryBean#getObject()
public Object getObject() throws Exception {
return dataS
/* (non-Javadoc)
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
@SuppressWarnings("unchecked")
public Class getObjectType() {
return DataSource.
/* (non-Javadoc)
* @see org.springframework.beans.factory.FactoryBean#isSingleton()
public boolean isSingleton() {
//~ Accessors ==============================================================
* @param properties the properties to set
public void setProperties(Properties properties) {
this.properties =
* @param dataSourceFactory the dataSourceFactory to set
public void setDataSourceFactory(DataSourceFactory dataSourceFactory) {
this.dataSourceFactory = dataSourceF
* @(#)DBCPDataSourceFactory.java Jul 18, 2009
* Copyright 2009 Net365. All rights reserved.
package com.painiu.core.dao.
import java.io.ByteArrayInputS
import java.sql.C
import java.util.E
import java.util.P
import javax.sql.DataS
import mons.dbcp.BasicDataS
import com.painiu.core.dao.support.DataSourceF
* &a href="DBCPDataSourceFactory.java.html"&&i&View Source&/i&&/a&
* @author Zhang Songfu
* @version $Id: DbcpDataSourceFactory.java -04-15 09:28:48Z zhangsongfu $
public class DbcpDataSourceFactory implements DataSourceFactory {
private final static String PROP_DEFAULTAUTOCOMMIT ="defaultAutoCommit";
private final static String PROP_DEFAULTREADONLY ="defaultReadOnly";
private final static String PROP_DEFAULTTRANSACTIONISOLATION ="defaultTransactionIsolation";
private final static String PROP_DEFAULTCATALOG ="defaultCatalog";
private final static String PROP_DRIVERCLASSNAME ="driverClassName";
private final static String PROP_MAXACTIVE ="maxActive";
private final static String PROP_MAXIDLE ="maxIdle";
private final static String PROP_MINIDLE ="minIdle";
private final static String PROP_INITIALSIZE ="initialSize";
private final static String PROP_MAXWAIT ="maxWait";
private final static String PROP_TESTONBORROW ="testOnBorrow";
private final static String PROP_TESTONRETURN ="testOnReturn";
private final static String PROP_TIMEBETWEENEVICTIONRUNSMILLIS ="timeBetweenEvictionRunsMillis";
private final static String PROP_NUMTESTSPEREVICTIONRUN ="numTestsPerEvictionRun";
private final static String PROP_MINEVICTABLEIDLETIMEMILLIS ="minEvictableIdleTimeMillis";
private final static String PROP_TESTWHILEIDLE ="testWhileIdle";
private final static String PROP_PASSWORD ="password";
private final static String PROP_URL ="url";
private final static String PROP_USERNAME ="username";
private final static String PROP_VALIDATIONQUERY ="validationQuery";
private final static String PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED ="accessToUnderlyingConnectionAllowed";
// private final static String PROP_REMOVEABANDONED ="removeAbandoned";
// private final static String PROP_REMOVEABANDONEDTIMEOUT ="removeAbandonedTimeout";
// private final static String PROP_LOGABANDONED ="logAbandoned";
private final static String PROP_POOLPREPAREDSTATEMENTS ="poolPreparedStatements";
private final static String PROP_MAXOPENPREPAREDSTATEMENTS ="maxOpenPreparedStatements";
private final static String PROP_CONNECTIONPROPERTIES ="connectionProperties";
// -------------------------------------------------- ObjectFactory Methods
* Creates and configures a {@link BasicDataSource} instance based on the
* given properties.
* @param properties the datasource configuration properties
* @throws Exception if an error occurs creating the data source
public DataSource createDataSource(Properties properties) throws Exception {
BasicDataSource dataSource = new BasicDataSource();
String value =
value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT);
if (value != null) {
dataSource.setDefaultAutoCommit(Boolean.valueOf(value).booleanValue());
value = properties.getProperty(PROP_DEFAULTREADONLY);
if (value != null) {
dataSource.setDefaultReadOnly(Boolean.valueOf(value).booleanValue());
value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
if (value != null) {
int level = -1;
if ("NONE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_NONE;
else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_COMMITTED;
else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_UNCOMMITTED;
else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_REPEATABLE_READ;
else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_SERIALIZABLE;
level = Integer.parseInt(value);
} catch (NumberFormatException e) {
System.err.println("Could not parse defaultTransactionIsolation:"+ value);
System.err.println("WARNING: defaultTransactionIsolation not set");
System.err.println("using default value of database driver");
level = -1;
dataSource.setDefaultTransactionIsolation(level);
value = properties.getProperty(PROP_DEFAULTCATALOG);
if (value != null) {
dataSource.setDefaultCatalog(value);
value = properties.getProperty(PROP_DRIVERCLASSNAME);
if (value != null) {
dataSource.setDriverClassName(value);
value = properties.getProperty(PROP_MAXACTIVE);
if (value != null) {
dataSource.setMaxActive(Integer.parseInt(value));
value = properties.getProperty(PROP_MAXIDLE);
if (value != null) {
dataSource.setMaxIdle(Integer.parseInt(value));
value = properties.getProperty(PROP_MINIDLE);
if (value != null) {
dataSource.setMinIdle(Integer.parseInt(value));
value = properties.getProperty(PROP_INITIALSIZE);
if (value != null) {
dataSource.setInitialSize(Integer.parseInt(value));
value = properties.getProperty(PROP_MAXWAIT);
if (value != null) {
dataSource.setMaxWait(Long.parseLong(value));
value = properties.getProperty(PROP_TESTONBORROW);
if (value != null) {
dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
value = properties.getProperty(PROP_TESTONRETURN);
if (value != null) {
dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
if (value != null) {
dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value));
value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN);
if (value != null) {
dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS);
if (value != null) {
dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value));
value = properties.getProperty(PROP_TESTWHILEIDLE);
if (value != null) {
dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
value = properties.getProperty(PROP_PASSWORD);
if (value != null) {
dataSource.setPassword(value);
value = properties.getProperty(PROP_URL);
if (value != null) {
dataSource.setUrl(value);
value = properties.getProperty(PROP_USERNAME);
if (value != null) {
dataSource.setUsername(value);
value = properties.getProperty(PROP_VALIDATIONQUERY);
if (value != null) {
dataSource.setValidationQuery(value);
value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
if (value != null) {
dataSource.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS);
if (value != null) {
dataSource.setPoolPreparedStatements(Boolean.valueOf(value).booleanValue());
value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS);
if (value != null) {
dataSource.setMaxOpenPreparedStatements(Integer.parseInt(value));
value = properties.getProperty(PROP_CONNECTIONPROPERTIES);
if (value != null) {
Properties p = getProperties(value);
Enumeration&?& e = p.propertyNames();
while (e.hasMoreElements()) {
String propertyName = (String) e.nextElement();
dataSource.addConnectionProperty(propertyName, p.getProperty(propertyName));
// Return the configured DataSource instance
return dataS
* &p&Parse properties from the string. Format of the string must be [propertyName=]*&p&
* @param propText
* @return Properties
* @throws Exception
static private Properties getProperties(String propText) throws Exception {
Properties p = new Properties();
if (propText != null) {
p.load(new ByteArrayInputStream(propText.replace(';', 'n').getBytes()));
用户评论(0)
开发技术学习小组列表
PHP开发框架
缓存Memcache
服务器环境
ThinkSAAS商业授权:
ThinkSAAS为用户提供有偿个性定制开发服务
ThinkSAAS将为商业授权用户提供二次开发指导和技术支持
手机客户端
ThinkSAAS接收任何功能的Iphone(IOS)和Android手机的客户端定制开发服务
让ThinkSAAS更好,把建议拿来。
iphone扫码下载客户端

我要回帖

更多关于 mediaserver linux 的文章

 

随机推荐