找传奇、传世资源到传世资源站!
Java 正文

apache http server

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈


from clipboardimport java.io.File;import java.io.IOException;import java.io.InterruptedIOException;import java.net.InetSocketAddress;import java.net.ServerSocket;import java.net.Socket;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.Executor;import java.util.concurrent.Executors;import java.util.concurrent.RejectedExecutionHandler;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.apache.http.ConnectionClosedException;import org.apache.http.HttpConnectionFactory;import org.apache.http.HttpEntity;import org.apache.http.HttpEntityEnclosingRequest;import org.apache.http.HttpException;import org.apache.http.HttpRequest;import org.apache.http.HttpResponse;import org.apache.http.HttpServerConnection;import org.apache.http.MethodNotSupportedException;import org.apache.http.entity.ByteArrayEntity;import org.apache.http.impl.DefaultBHttpServerConnection;import org.apache.http.impl.DefaultBHttpServerConnectionFactory;import org.apache.http.protocol.BasicHttpContext;import org.apache.http.protocol.HttpContext;import org.apache.http.protocol.HttpProcessor;import org.apache.http.protocol.HttpProcessorBuilder;import org.apache.http.protocol.HttpRequestHandler;import org.apache.http.protocol.HttpService;import org.apache.http.protocol.ResponseConnControl;import org.apache.http.protocol.ResponseContent;import org.apache.http.protocol.ResponseDate;import org.apache.http.protocol.ResponseServer;import org.apache.http.protocol.UriHttpRequestHandlerMapper;import org.apache.http.util.EntityUtils;import org.w3c.dom.CDATASection;import org.w3c.dom.Document;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import com.sun.net.httpserver.spi.HttpServerProvider;public class ApacheHttpServer {public static void main(String[] args) throws Exception {HttpServerProvider provider = HttpServerProvider.provider();Map<String ,Object> svcList = parseXml(System.getProperty("user.dir") "/conf.xml");String ip = (String)((Map<String,Object>)svcList.get("conf")).get("ip");String port = (String)((Map<String,Object>)svcList.get("conf")).get("port");String url = (String)((Map<String,Object>)svcList.get("conf")).get("url");String inst = (String)((Map<String,Object>)svcList.get("conf")).get("inst");HttpRequestHandler handler = new HttpRequestHandler() {@Overridepublic void handle(HttpRequest request, HttpResponse response, HttpContext context)throws HttpException, IOException {String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {throw new MethodNotSupportedException(method " method not supported");}String entityContent = "";if (request instanceof HttpEntityEnclosingRequest) {HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();entityContent = EntityUtils.toString(entity);}String url = request.getRequestLine().getUri();String svcName = url.substring(url.lastIndexOf("/") 1);//System.out.println("接收报文------" entityContent);String fmt = (String) ((Map<String,Object>)((Map<String,Object>)svcList.get("conf")).get("fmt")).get(svcName); if(null == fmt || "".equals(fmt)) new Exception("未配置报文或xml格式不正确!格式应该是:\r\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<conf>\r\n\t<fmt>\r\n\t\t<服务码>报文内容</服务码>\r\n\t</fmt>\r\n</conf>").printStackTrace();; byte[] sendByte = fmt.trim().getBytes();response.setEntity(new ByteArrayEntity(sendByte));response.setEntity(new ByteArrayEntity(fmt.getBytes()));}};HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()).add(new ResponseServer("My Response Server 1.1")).add(new ResponseContent()).add(new ResponseConnControl()).build();UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();reqistry.register(url, handler);// Set up the HTTP servicefinal HttpService httpService = new HttpService(httpproc, reqistry);final Executor executor = new ThreadPoolExecutor(Integer.parseInt(inst), Integer.parseInt(inst), 100, TimeUnit.SECONDS,// 缓冲队列为5new ArrayBlockingQueue<Runnable>(50), Executors.defaultThreadFactory(),// new ThreadPoolExecutor.AbortPolicy());//拒绝任务new RejectedExecutionHandler() {@Overridepublic void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {System.out.println("失败。……。…。……。……。…………");}});Thread listener = new Thread() {@Overridepublic void run() {ServerSocket serverSocket = null;HttpConnectionFactory<DefaultBHttpServerConnection> connFactory = null;try {connFactory = DefaultBHttpServerConnectionFactory.INSTANCE;serverSocket = new ServerSocket();serverSocket.bind(new InetSocketAddress(ip, Integer.parseInt(port)), 500);} catch (Exception e) {e.printStackTrace();System.exit(-1);}while (!Thread.interrupted()) {try {// Set up HTTP connectionSocket socket = serverSocket.accept();final HttpServerConnection conn = connFactory.createConnection(socket);executor.execute(new Runnable() {@Overridepublic void run() {HttpContext context = new BasicHttpContext(null);try {if (!Thread.interrupted() && conn.isOpen()) {httpService.handleRequest(conn, context);}} catch (ConnectionClosedException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (HttpException e) {e.printStackTrace();} finally {try {if (conn != null) {conn.shutdown();}} catch (IOException e) {e.printStackTrace();}}}});} catch (InterruptedIOException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}};listener.setDaemon(false);listener.start();}private static Map<String, Object> parseXml(String xmlPath)throws ParserConfigurationException, SAXException, IOException {DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();DocumentBuilder dombuilder = domfac.newDocumentBuilder();File file = new File(xmlPath);Document doc = dombuilder.parse(file);Node node = doc.getChildNodes().item(0);return getNodes(node);}private static Map<String, Object> getNodes(Node element) {Map<String, Object> rootMap = new LinkedHashMap<String, Object>();// ---------------------属性-------------------------NamedNodeMap attMap = element.getAttributes();Map<String, Object> attAndNodeMap = new LinkedHashMap<String, Object>();rootMap.put(element.getNodeName(), attAndNodeMap);for (int i = 0; attMap != null && i < attMap.getLength(); i ) {Node nodes = attMap.item(i);String attName = nodes.getNodeName();String attValue = nodes.getNodeValue();attAndNodeMap.put(attName, attValue);}// ---------------------节点-------------------------NodeList nodes = element.getChildNodes();for (int k = 0; k < nodes.getLength(); k ) {if (nodes.item(k).getNodeType() == Node.ELEMENT_NODE) {Node node = nodes.item(k);String oldKey = "";if (node.getChildNodes() != null&& (node.getChildNodes().getLength() > 1 || node.getAttributes().getLength() > 0)) {Map<String, Object> subMap = getNodes(node);if (!subMap.isEmpty()) {oldKey = subMap.keySet().iterator().next();}if (attAndNodeMap.containsKey(oldKey)) {if (attAndNodeMap.get(oldKey) != null && attAndNodeMap.get(oldKey) instanceof List) {((List) attAndNodeMap.get(oldKey)).add(subMap.get(oldKey));} else {List<Object> list = new ArrayList<Object>();list.add(subMap.get(oldKey));list.add(attAndNodeMap.get(oldKey));attAndNodeMap.remove(oldKey);attAndNodeMap.put(oldKey, list);}} elseattAndNodeMap.putAll(subMap);} else{ attAndNodeMap.put(node.getNodeName(), node.getTextContent());}}if(nodes.item(k).getNodeType() == Node.CDATA_SECTION_NODE){CDATASection cdataNode = (CDATASection) nodes.item(k);String content = cdataNode.getTextContent();if(attAndNodeMap.isEmpty()){rootMap.remove(element.getNodeName());rootMap.put(cdataNode.getParentNode().getNodeName(), content);}else{rootMap.put(nodes.item(k).getParentNode().getNodeName(), content);}}}return rootMap;}}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复