Return-Path: X-Original-To: apmail-cxf-commits-archive@www.apache.org Delivered-To: apmail-cxf-commits-archive@www.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id 85063104F8 for ; Tue, 25 Feb 2014 17:25:50 +0000 (UTC) Received: (qmail 46783 invoked by uid 500); 25 Feb 2014 17:25:38 -0000 Delivered-To: apmail-cxf-commits-archive@cxf.apache.org Received: (qmail 46759 invoked by uid 500); 25 Feb 2014 17:25:38 -0000 Mailing-List: contact commits-help@cxf.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@cxf.apache.org Delivered-To: mailing list commits@cxf.apache.org Received: (qmail 46602 invoked by uid 99); 25 Feb 2014 17:25:31 -0000 Received: from tyr.zones.apache.org (HELO tyr.zones.apache.org) (140.211.11.114) by apache.org (qpsmtpd/0.29) with ESMTP; Tue, 25 Feb 2014 17:25:31 +0000 Received: by tyr.zones.apache.org (Postfix, from userid 65534) id 3832592C7AD; Tue, 25 Feb 2014 17:25:31 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: ay@apache.org To: commits@cxf.apache.org Date: Tue, 25 Feb 2014 17:25:31 -0000 Message-Id: <85d1416cd92044d9aaaf38a78ae8d040@git.apache.org> X-Mailer: ASF-Git Admin Mailer Subject: [1/2] git commit: [CXF-5339] websocket in cxf http-jetty transport Repository: cxf Updated Branches: refs/heads/master c92b639c2 -> 99e152091 [CXF-5339] websocket in cxf http-jetty transport Project: http://git-wip-us.apache.org/repos/asf/cxf/repo Commit: http://git-wip-us.apache.org/repos/asf/cxf/commit/8018b198 Tree: http://git-wip-us.apache.org/repos/asf/cxf/tree/8018b198 Diff: http://git-wip-us.apache.org/repos/asf/cxf/diff/8018b198 Branch: refs/heads/master Commit: 8018b198a9b6a2304f50c37322a7fbeb0f6884ba Parents: 7705a92 Author: Akitoshi Yoshida Authored: Tue Feb 25 18:20:47 2014 +0100 Committer: Akitoshi Yoshida Committed: Tue Feb 25 18:21:21 2014 +0100 ---------------------------------------------------------------------- parent/pom.xml | 2 + rt/transports/http-jetty/pom.xml | 5 + .../http_jetty/JettyHTTPDestination.java | 37 +- .../http_jetty/JettyHTTPExtendedHandler.java | 60 ++ .../transport/http_jetty/JettyHTTPHandler.java | 4 +- .../transport/http_jetty/JettyWebSocket.java | 1018 ++++++++++++++++++ .../transport/http/AbstractHTTPDestination.java | 9 + systests/jaxrs/pom.xml | 24 + .../apache/cxf/systest/jaxrs/BookServer.java | 3 + .../org/apache/cxf/systest/jaxrs/BookStore.java | 25 +- .../jaxrs/JAXRSClientServerWebSocketTest.java | 97 ++ .../cxf/systest/jaxrs/WebSocketTestClient.java | 155 +++ 12 files changed, 1433 insertions(+), 6 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/parent/pom.xml ---------------------------------------------------------------------- diff --git a/parent/pom.xml b/parent/pom.xml index 264939a..78f17fe 100644 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -73,6 +73,7 @@ 1.1.3 5.9.0 + 1.8.1 1.2.14 1.50 2.2_2 @@ -123,6 +124,7 @@ 2011.1 3.0.3 4.0.7.Final + 3.8.0.Final [4,5) 20100527_1 2.6.1 http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/rt/transports/http-jetty/pom.xml ---------------------------------------------------------------------- diff --git a/rt/transports/http-jetty/pom.xml b/rt/transports/http-jetty/pom.xml index 06df9ca..cf90eec 100644 --- a/rt/transports/http-jetty/pom.xml +++ b/rt/transports/http-jetty/pom.xml @@ -100,6 +100,11 @@ org.eclipse.jetty + jetty-websocket + ${cxf.jetty.version} + + + org.eclipse.jetty jetty-jmx ${cxf.jetty.version} true http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPDestination.java ---------------------------------------------------------------------- diff --git a/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPDestination.java b/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPDestination.java index 533d2a6..02a678d 100644 --- a/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPDestination.java +++ b/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPDestination.java @@ -23,6 +23,7 @@ import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.lang.reflect.Constructor; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; @@ -57,16 +58,29 @@ import org.eclipse.jetty.server.AbstractHttpConnection.Output; import org.eclipse.jetty.server.Request; import org.springframework.util.ClassUtils; + public class JettyHTTPDestination extends AbstractHTTPDestination { private static final Logger LOG = LogUtils.getL7dLogger(JettyHTTPDestination.class); + private static Constructor handlerConstructor; protected JettyHTTPServerEngine engine; protected JettyHTTPServerEngineFactory serverEngineFactory; protected ServletContext servletContext; protected URL nurl; protected ClassLoader loader; + + + static { + try { + Class cls = ClassUtils.forName("org.apache.cxf.transport.http_jetty.JettyHTTPExtendedHandler", + JettyHTTPDestination.class.getClassLoader()); + handlerConstructor = cls.getDeclaredConstructor(new Class[]{JettyHTTPDestination.class, boolean.class}); + } catch (Throwable t) { + //ignore + } + } /** * This variable signifies that finalizeConfig() has been called. @@ -168,8 +182,23 @@ public class JettyHTTPDestination extends AbstractHTTPDestination { } catch (Exception e) { throw new Fault(e); } - engine.addServant(url, - new JettyHTTPHandler(this, contextMatchOnExact())); + // pick the handler supportig websocket if jetty-websocket is available otherwise pick the default handler. + JettyHTTPHandler jhd = createJettyHTTPHandler(this, contextMatchOnExact()); + engine.addServant(url, jhd); + + } + + private JettyHTTPHandler createJettyHTTPHandler(JettyHTTPDestination jhd, + boolean cmExact) { + if (handlerConstructor != null) { + try { + return (JettyHTTPHandler)handlerConstructor.newInstance(new Object[]{jhd, cmExact}); + } catch (Exception e) { + //ignore + } + } + // use the default handler + return new JettyHTTPHandler(jhd, cmExact); } /** @@ -262,7 +291,9 @@ public class JettyHTTPDestination extends AbstractHTTPDestination { resp.flushBuffer(); Request baseRequest = (req instanceof Request) ? (Request)req : getCurrentRequest(); - baseRequest.setHandled(true); + if (baseRequest != null) { + baseRequest.setHandled(true); + } super.invokeComplete(context, req, resp, m); } http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPExtendedHandler.java ---------------------------------------------------------------------- diff --git a/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPExtendedHandler.java b/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPExtendedHandler.java new file mode 100644 index 0000000..a15c5ff --- /dev/null +++ b/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPExtendedHandler.java @@ -0,0 +1,60 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.cxf.transport.http_jetty; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.websocket.WebSocket; +import org.eclipse.jetty.websocket.WebSocketFactory; + +/** + * The extended version of JettyHTTPHandler that can support websocket. + */ +class JettyHTTPExtendedHandler extends JettyHTTPHandler implements WebSocketFactory.Acceptor { + private final WebSocketFactory webSocketFactory = new WebSocketFactory(this); + + public JettyHTTPExtendedHandler(JettyHTTPDestination jhd, boolean cmExact) { + super(jhd, cmExact); + } + + public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) { + return new JettyWebSocket(jettyHTTPDestination, servletContext, request, protocol); + } + + @Override + public void handle(String target, Request baseRequest, HttpServletRequest request, + HttpServletResponse response) throws IOException, ServletException { + // only switch to websocket if websocket is enabled for this destination + if (jettyHTTPDestination != null && jettyHTTPDestination.isEnableWebSocket() + && (webSocketFactory.acceptWebSocket(request, response) || response.isCommitted())) { + baseRequest.setHandled(true); + } else { + super.handle(target, baseRequest, request, response); + } + } + + public boolean checkOrigin(HttpServletRequest request, String protocol) { + return true; + } +} http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPHandler.java ---------------------------------------------------------------------- diff --git a/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPHandler.java b/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPHandler.java index 7b5214d..0894cbe 100644 --- a/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPHandler.java +++ b/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyHTTPHandler.java @@ -29,10 +29,10 @@ import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; public class JettyHTTPHandler extends AbstractHandler { + protected JettyHTTPDestination jettyHTTPDestination; + protected ServletContext servletContext; private String urlName; private boolean contextMatchExact; - private JettyHTTPDestination jettyHTTPDestination; - private ServletContext servletContext; public JettyHTTPHandler(JettyHTTPDestination jhd, boolean cmExact) { contextMatchExact = cmExact; http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyWebSocket.java ---------------------------------------------------------------------- diff --git a/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyWebSocket.java b/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyWebSocket.java new file mode 100644 index 0000000..d20d816 --- /dev/null +++ b/rt/transports/http-jetty/src/main/java/org/apache/cxf/transport/http_jetty/JettyWebSocket.java @@ -0,0 +1,1018 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.cxf.transport.http_jetty; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.security.Principal; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.TreeMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.servlet.AsyncContext; +import javax.servlet.DispatcherType; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.servlet.http.Part; + +import org.apache.cxf.common.logging.LogUtils; +import org.apache.cxf.helpers.CastUtils; +import org.eclipse.jetty.websocket.WebSocket; + +class JettyWebSocket implements WebSocket.OnBinaryMessage, WebSocket.OnTextMessage { + private static final Logger LOG = LogUtils.getL7dLogger(JettyWebSocket.class); + + private JettyHTTPDestination jettyHTTPDestination; + private ServletContext servletContext; + private Connection webSocketConnection; + private Map requestProperties; + private String protocol; + + public JettyWebSocket(JettyHTTPDestination jettyHTTPDestination, ServletContext servletContext, + HttpServletRequest request, String protocol) { + this.jettyHTTPDestination = jettyHTTPDestination; + this.servletContext = servletContext; + this.protocol = protocol; + this.requestProperties = readProperties(request); + } + + private Map readProperties(HttpServletRequest request) { + Map properties = new HashMap(); + properties.put("servletPath", request.getServletPath()); + properties.put("requestURI", request.getRequestURI()); + properties.put("requestURL", request.getRequestURL().toString()); + properties.put("contextPath", request.getContextPath()); + properties.put("servletPath", request.getServletPath()); + properties.put("pathInfo", request.getPathInfo()); + properties.put("protocol", protocol); + // some additional ones + properties.put("localAddr", request.getLocalAddr()); + properties.put("localName", request.getLocalName()); + properties.put("localPort", request.getLocalPort()); + properties.put("locale", request.getLocale()); + properties.put("locales", request.getLocales()); + properties.put("remoteHost", request.getRemoteHost()); + properties.put("remoteAddr", request.getRemoteAddr()); + properties.put("serverName", request.getServerName()); + properties.put("secure", request.isSecure()); + + return properties; + } + + @Override + public void onClose(int closeCode, String message) { + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "onClose({0}, {1})", new Object[]{closeCode, message}); + } + } + + @Override + public void onOpen(Connection connection) { + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "onOpen({0}))", connection); + } + this.webSocketConnection = connection; + } + + @Override + public void onMessage(String data) { + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "onMessage({0})", data); + } + try { + byte[] bdata = data.getBytes("utf-8"); + jettyHTTPDestination.invoke(null, servletContext, + createServletRequest(bdata, 0, bdata.length), + createServletResponse()); + } catch (Exception e) { + LOG.log(Level.WARNING, "Failed to invoke service", e); + } + } + + @Override + public void onMessage(byte[] data, int offset, int length) { + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "onMessage({0}, {1}, {2})", new Object[]{data, offset, length}); + } + try { + jettyHTTPDestination.invoke(null, servletContext, + createServletRequest(data, offset, length), + createServletResponse()); + } catch (Exception e) { + LOG.log(Level.WARNING, "Failed to invoke service", e); + } + } + + @SuppressWarnings("unchecked") + T getRequestProperty(String name, Class cls) { + return (T)requestProperties.get(name); + } + + private WebSocketVirtualServletRequest createServletRequest(byte[] data, int offset, int length) + throws IOException { + return new WebSocketVirtualServletRequest(servletContext, this, new ByteArrayInputStream(data, offset, length)); + } + + private WebSocketVirtualServletResponse createServletResponse() throws IOException { + return new WebSocketVirtualServletResponse(this); + } + + /** + * Writes to the underlining socket. + * + * @param data + * @param offset + * @param length + */ + public void write(byte[] data, int offset, int length) throws IOException { + LOG.log(Level.INFO, "write(byte[], offset, length)"); + webSocketConnection.sendMessage(data, offset, length); + } + + public ServletOutputStream getServletOutputStream() { + LOG.log(Level.INFO, "getServletOutputStream()"); + return new ServletOutputStream() { + @Override + public void write(int b) throws IOException { + byte[] data = new byte[1]; + data[0] = (byte)b; + write(data, 0, 1); + } + + @Override + public void write(byte[] data, int offset, int length) throws IOException { + webSocketConnection.sendMessage(data, offset, length); + } + }; + } + + public OutputStream getOutputStream() { + LOG.log(Level.INFO, "getServletOutputStream()"); + return new OutputStream() { + @Override + public void write(int b) throws IOException { + byte[] data = new byte[1]; + data[0] = (byte)b; + write(data, 0, 1); + } + + @Override + public void write(byte[] data, int offset, int length) throws IOException { + webSocketConnection.sendMessage(data, offset, length); + } + }; + + } + + // + static class WebSocketVirtualServletRequest implements HttpServletRequest { + private ServletContext context; + private JettyWebSocket websocket; + private InputStream in; + private Map requestHeaders; + + public WebSocketVirtualServletRequest(ServletContext context, JettyWebSocket websocket, InputStream in) + throws IOException { + this.context = context; + this.websocket = websocket; + this.in = in; + + requestHeaders = readHeaders(in); + String path = requestHeaders.get("$path"); + String origin = websocket.getRequestProperty("requestURI", String.class); + if (path.length() < origin.length()) { + //TODO use a more appropriate exception (invalidxxx?); + throw new IOException("invalid path: " + path + " not within " + origin); + } + } + + @Override + public AsyncContext getAsyncContext() { + return null; + } + + @Override + public Object getAttribute(String name) { + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "getAttribute({0})", name); + } + return null; + } + + @Override + public Enumeration getAttributeNames() { + LOG.log(Level.INFO, "getAttributeNames()"); + return null; + } + + @Override + public String getCharacterEncoding() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getCharacterEncoding()"); + return null; + } + + @Override + public int getContentLength() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getContentLength()"); + return 0; + } + + @Override + public String getContentType() { + LOG.log(Level.INFO, "getContentType()"); + return requestHeaders.get("Content-Type"); + } + + @Override + public DispatcherType getDispatcherType() { + LOG.log(Level.INFO, "getDispatcherType()"); + return null; + } + + @Override + public ServletInputStream getInputStream() throws IOException { + return new ServletInputStream() { + @Override + public int read() throws IOException { + return in.read(); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + return in.read(b, off, len); + } + }; + } + + @Override + public String getLocalAddr() { + LOG.log(Level.INFO, "getLocalAddr()"); + return websocket.getRequestProperty("localAddr", String.class); + } + + @Override + public String getLocalName() { + LOG.log(Level.INFO, "getLocalName()"); + return websocket.getRequestProperty("localName", String.class); + } + + @Override + public int getLocalPort() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getLocalPort()"); + return 0; + } + + @Override + public Locale getLocale() { + LOG.log(Level.INFO, "getLocale()"); + return websocket.getRequestProperty("locale", Locale.class); + } + + @Override + public Enumeration getLocales() { + LOG.log(Level.INFO, "getLocales()"); + return CastUtils.cast(websocket.getRequestProperty("locales", Enumeration.class)); + } + + @Override + public String getParameter(String name) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "getParameter({0})", name); + } + return null; + } + + @Override + public Map getParameterMap() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getParameterMap()"); + return null; + } + + @Override + public Enumeration getParameterNames() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getParameterNames()"); + return null; + } + + @Override + public String[] getParameterValues(String name) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "getParameterValues({0})", name); + } + return null; + } + + @Override + public String getProtocol() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getProtocol"); + return null; + } + + @Override + public BufferedReader getReader() throws IOException { + LOG.log(Level.INFO, "getReader"); + return new BufferedReader(new InputStreamReader(in, "utf-8")); + } + + @Override + public String getRealPath(String path) { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getRealPath"); + return null; + } + + @Override + public String getRemoteAddr() { + LOG.log(Level.INFO, "getRemoteAddr"); + return websocket.getRequestProperty("remoteAddr", String.class); + } + + @Override + public String getRemoteHost() { + LOG.log(Level.INFO, "getRemoteHost"); + return websocket.getRequestProperty("remoteHost", String.class); + } + + @Override + public int getRemotePort() { + LOG.log(Level.INFO, "getRemotePort"); + return websocket.getRequestProperty("remotePort", int.class); + } + + @Override + public RequestDispatcher getRequestDispatcher(String path) { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getRequestDispatcher"); + return null; + } + + @Override + public String getScheme() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getScheme"); + return null; + } + + @Override + public String getServerName() { + return websocket.getRequestProperty("serverName", String.class); + } + + @Override + public int getServerPort() { + LOG.log(Level.INFO, "getServerPort"); + return websocket.getRequestProperty("serverPoart", int.class); + } + + @Override + public ServletContext getServletContext() { + LOG.log(Level.INFO, "getServletContext"); + return context; + } + + @Override + public boolean isAsyncStarted() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "isAsyncStarted"); + return false; + } + + @Override + public boolean isAsyncSupported() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "isAsyncSupported"); + return false; + } + + @Override + public boolean isSecure() { + LOG.log(Level.INFO, "isSecure"); + return websocket.getRequestProperty("secure", boolean.class); + } + + @Override + public void removeAttribute(String name) { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "removeAttribute"); + } + + @Override + public void setAttribute(String name, Object o) { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "setAttribute"); + } + + @Override + public void setCharacterEncoding(String env) throws UnsupportedEncodingException { + LOG.log(Level.INFO, "setCharacterEncoding"); + // ignore as we stick to utf-8. + } + + @Override + public AsyncContext startAsync() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "startAsync"); + return null; + } + + @Override + public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "startAsync"); + return null; + } + + @Override + public boolean authenticate(HttpServletResponse servletResponse) throws IOException, ServletException { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "authenticate"); + return false; + } + + @Override + public String getAuthType() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getAuthType"); + return null; + } + + @Override + public String getContextPath() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getContextPath"); + return null; + } + + @Override + public Cookie[] getCookies() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getCookies"); + return null; + } + + @Override + public long getDateHeader(String name) { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getDateHeader"); + return 0; + } + + @Override + public String getHeader(String name) { + LOG.log(Level.INFO, "getHeader"); + return requestHeaders.get(name); + } + + @Override + public Enumeration getHeaderNames() { + LOG.log(Level.INFO, "getHeaderNames"); + return Collections.enumeration(requestHeaders.keySet()); + } + + @Override + public Enumeration getHeaders(String name) { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getHeaders"); + return Collections.enumeration(Arrays.asList(requestHeaders.get(name))); + } + + @Override + public int getIntHeader(String name) { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getIntHeader"); + return 0; + } + + @Override + public String getMethod() { + LOG.log(Level.INFO, "getMethod"); + return requestHeaders.get("$method"); + } + + @Override + public Part getPart(String name) throws IOException, ServletException { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getPart"); + return null; + } + + @Override + public Collection getParts() throws IOException, ServletException { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getParts"); + return null; + } + + @Override + public String getPathInfo() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getPathInfo"); + return null; + } + + @Override + public String getPathTranslated() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getPathTranslated"); + return null; + } + + @Override + public String getQueryString() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getQueryString"); + return null; + } + + @Override + public String getRemoteUser() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getRemoteUser"); + return null; + } + + @Override + public String getRequestURI() { + LOG.log(Level.INFO, "getRequestURI"); + return requestHeaders.get("$path"); + } + + @Override + public StringBuffer getRequestURL() { + LOG.log(Level.INFO, "getRequestURL"); + String origin = websocket.getRequestProperty("requestURI", String.class); + StringBuffer sb = new StringBuffer(); + sb.append(origin).append(getRequestURI().substring(origin.length())); + + return sb; + } + + @Override + public String getRequestedSessionId() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getRequestedSessionId"); + return null; + } + + @Override + public String getServletPath() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getServletPath"); + return null; + } + + @Override + public HttpSession getSession() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getSession"); + return null; + } + + @Override + public HttpSession getSession(boolean create) { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getSession"); + return null; + } + + @Override + public Principal getUserPrincipal() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getUserPrincipal"); + return null; + } + + @Override + public boolean isRequestedSessionIdFromCookie() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "isRequestedSessionIdFromCookie"); + return false; + } + + @Override + public boolean isRequestedSessionIdFromURL() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "isRequestedSessionIdFromURL"); + return false; + } + + @Override + public boolean isRequestedSessionIdFromUrl() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "isRequestedSessionIdFromUrl"); + return false; + } + + @Override + public boolean isRequestedSessionIdValid() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "isRequestedSessionIdValid"); + return false; + } + + @Override + public boolean isUserInRole(String role) { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "isUserInRole"); + return false; + } + + @Override + public void login(String username, String password) throws ServletException { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "login"); + + } + + @Override + public void logout() throws ServletException { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "logout"); + + } + + } + + //TODO need to make the header setting to be written to the body (as symmetric to the request behavior) + static class WebSocketVirtualServletResponse implements HttpServletResponse { + private JettyWebSocket websocket; + + public WebSocketVirtualServletResponse(JettyWebSocket websocket) { + this.websocket = websocket; + } + + @Override + public void flushBuffer() throws IOException { + LOG.log(Level.INFO, "flushBuffer()"); + } + + @Override + public int getBufferSize() { + LOG.log(Level.INFO, "getBufferSize()"); + return 0; + } + + @Override + public String getCharacterEncoding() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getCharacterEncoding()"); + return null; + } + + @Override + public String getContentType() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getContentType()"); + return null; + } + + @Override + public Locale getLocale() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getLocale"); + return null; + } + + @Override + public ServletOutputStream getOutputStream() throws IOException { + LOG.log(Level.INFO, "getOutputStream()"); + return websocket.getServletOutputStream(); + } + + @Override + public PrintWriter getWriter() throws IOException { + LOG.log(Level.INFO, "getWriter()"); + return new PrintWriter(websocket.getOutputStream()); + } + + @Override + public boolean isCommitted() { + return false; + } + + @Override + public void reset() { + } + + @Override + public void resetBuffer() { + LOG.log(Level.INFO, "resetBuffer()"); + } + + @Override + public void setBufferSize(int size) { + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "setBufferSize({0})", size); + } + } + + @Override + public void setCharacterEncoding(String charset) { + // TODO + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "setCharacterEncoding({0})", charset); + } + } + + @Override + public void setContentLength(int len) { + // TODO + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "setContentLength({0})", len); + } + } + + @Override + public void setContentType(String type) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "setContentType({0})", type); + } + } + + @Override + public void setLocale(Locale loc) { + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "setLocale({0})", loc); + } + } + + @Override + public void addCookie(Cookie cookie) { + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "addCookie({0})", cookie); + } + } + + @Override + public void addDateHeader(String name, long date) { + // TODO + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "addDateHeader({0}, {1})", new Object[]{name, date}); + } + } + + @Override + public void addHeader(String name, String value) { + // TODO + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "addHeader({0}, {1})", new Object[]{name, value}); + } + } + + @Override + public void addIntHeader(String name, int value) { + // TODO + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "addIntHeader({0}, {1})", new Object[]{name, value}); + } + } + + @Override + public boolean containsHeader(String name) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "containsHeader({0})", name); + } + return false; + } + + @Override + public String encodeRedirectURL(String url) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "encodeRedirectURL({0})", url); + } + return null; + } + + @Override + public String encodeRedirectUrl(String url) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "encodeRedirectUrl({0})", url); + } + return null; + } + + @Override + public String encodeURL(String url) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "encodeURL({0})", url); + } + return null; + } + + @Override + public String encodeUrl(String url) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "encodeUrl({0})", url); + } + return null; + } + + @Override + public String getHeader(String name) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "getHeader({0})", name); + } + return null; + } + + @Override + public Collection getHeaderNames() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getHeaderNames()"); + return null; + } + + @Override + public Collection getHeaders(String name) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "getHeaders({0})", name); + } + return null; + } + + @Override + public int getStatus() { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "getStatus()"); + return 0; + } + + @Override + public void sendError(int sc) throws IOException { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "sendError{0}", sc); + } + } + + @Override + public void sendError(int sc, String msg) throws IOException { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "sendError({0}, {1})", new Object[]{sc, msg}); + } + } + + @Override + public void sendRedirect(String location) throws IOException { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "sendRedirect({0})", location); + } + } + + @Override + public void setDateHeader(String name, long date) { + // ignore + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "setDateHeader({0}, {1})", new Object[]{name, date}); + } + } + + @Override + public void setHeader(String name, String value) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "setHeader({0}, {1})", new Object[]{name, value}); + } + } + + @Override + public void setIntHeader(String name, int value) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "setIntHeader({0}, {1})", new Object[]{name, value}); + } + } + + @Override + public void setStatus(int sc) { + // TODO Auto-generated method stub + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "setStatus({0})", sc); + } + } + + @Override + public void setStatus(int sc, String sm) { + // TODO Auto-generated method stub + LOG.log(Level.INFO, "setStatus({0}, {1})", new Object[]{sc, sm}); + + } + } + + /* + * We accept only a restricted syntax as we have the syntax in our control. + * Do not allow multiline or line-wrapped headers. + * Do not allow charset other than utf-8. (although i would have preferred iso-8859-1 ;-) + */ + private static Map readHeaders(InputStream in) throws IOException { + Map headers = new TreeMap(String.CASE_INSENSITIVE_ORDER); + // read the request line + String line = readLine(in); + int del = line.indexOf(' '); + if (del < 0) { + throw new IOException("invalid request: " + line); + } + headers.put("$method", line.substring(0, del).trim()); + headers.put("$path", line.substring(del + 1).trim()); + + // read headers + while ((line = readLine(in)) != null) { + if (line.length() > 0) { + del = line.indexOf(':'); + if (del < 0) { + headers.put(line.trim(), ""); + } else { + headers.put(line.substring(0, del).trim(), line.substring(del + 1).trim()); + } + } + } + + return headers; + } + + ///// this is copied from AttachmentDeserializer. we may think about putting this method to IOUtils + private static String readLine(InputStream in) throws IOException { + StringBuffer buffer = new StringBuffer(128); + + int c; + + while ((c = in.read()) != -1) { + // a linefeed is a terminator, always. + if (c == '\n') { + break; + } else if (c == '\r') { + //just ignore the CR. The next character SHOULD be an NL. If not, we're + //just going to discard this + continue; + } else { + // just add to the buffer + buffer.append((char)c); + } + } + + // no characters found...this was either an eof or a null line. + if (buffer.length() == 0) { + return null; + } + + return buffer.toString(); + } + ///// END +} http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/rt/transports/http/src/main/java/org/apache/cxf/transport/http/AbstractHTTPDestination.java ---------------------------------------------------------------------- diff --git a/rt/transports/http/src/main/java/org/apache/cxf/transport/http/AbstractHTTPDestination.java b/rt/transports/http/src/main/java/org/apache/cxf/transport/http/AbstractHTTPDestination.java index 65400a2..c0fc511 100644 --- a/rt/transports/http/src/main/java/org/apache/cxf/transport/http/AbstractHTTPDestination.java +++ b/rt/transports/http/src/main/java/org/apache/cxf/transport/http/AbstractHTTPDestination.java @@ -116,6 +116,7 @@ public abstract class AbstractHTTPDestination protected CertConstraints certConstraints; protected boolean isServlet3; protected ContinuationProviderFactory cproviderFactory; + protected boolean enableWebSocket; private volatile boolean serverPolicyCalced; @@ -861,6 +862,14 @@ public abstract class AbstractHTTPDestination this.multiplexWithAddress = multiplexWithAddress; } + public boolean isEnableWebSocket() { + return enableWebSocket; + } + + public void setEnableWebSocket(boolean enableWebSocket) { + this.enableWebSocket = enableWebSocket; + } + public HTTPServerPolicy getServer() { calcServerPolicy(null); return serverPolicy; http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/systests/jaxrs/pom.xml ---------------------------------------------------------------------- diff --git a/systests/jaxrs/pom.xml b/systests/jaxrs/pom.xml index 17eda0d..887351b 100644 --- a/systests/jaxrs/pom.xml +++ b/systests/jaxrs/pom.xml @@ -110,6 +110,12 @@ ${cxf.jetty.version} + org.eclipse.jetty + jetty-websocket + ${cxf.jetty.version} + test + + org.apache.cxf cxf-core ${project.version} @@ -383,6 +389,24 @@ httpclient test + + com.ning + async-http-client + ${cxf.ahc.version} + test + + + io.netty + netty + + + + + io.netty + netty + ${cxf.netty3.version} + test + http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookServer.java ---------------------------------------------------------------------- diff --git a/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookServer.java b/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookServer.java index f315564..acc54a8 100644 --- a/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookServer.java +++ b/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookServer.java @@ -42,6 +42,7 @@ import org.apache.cxf.jaxrs.provider.BinaryDataProvider; import org.apache.cxf.jaxrs.provider.JAXBElementProvider; import org.apache.cxf.message.Message; import org.apache.cxf.testutil.common.AbstractBusTestServerBase; +import org.apache.cxf.transport.http_jetty.JettyHTTPDestination; public class BookServer extends AbstractBusTestServerBase { public static final String PORT = allocatePort(BookServer.class); @@ -111,6 +112,8 @@ public class BookServer extends AbstractBusTestServerBase { sf.getProperties().put("default.content.type", "*/*"); sf.getProperties().putAll(properties); server = sf.create(); + ((JettyHTTPDestination)server.getDestination()) + .setEnableWebSocket(Boolean.parseBoolean((String)properties.get("enableWebSocket"))); BusFactory.setDefaultBus(null); BusFactory.setThreadDefaultBus(null); } http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookStore.java ---------------------------------------------------------------------- diff --git a/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookStore.java b/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookStore.java index f04c4f5..100764b 100644 --- a/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookStore.java +++ b/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookStore.java @@ -101,7 +101,6 @@ import org.apache.cxf.systest.jaxrs.BookServer20.PostMatchMode; @Path("/bookstore") @GZIP(threshold = 1) public class BookStore { - private Map books = new HashMap(); private Map cds = new HashMap(); private long bookId = 123; @@ -1146,6 +1145,30 @@ public class BookStore { } } + @GET + @Path("/bookbought") + @Produces("text/*") + public StreamingOutput getBookBought() { + return new StreamingOutput() { + public void write(final OutputStream out) throws IOException, WebApplicationException { + out.write(("Today: " + new java.util.Date()).getBytes()); + // just for testing, using a thread + new Thread(new Runnable() { + public void run() { + try { + for (int r = 2, i = 1; i <= 5; r *= 2, i++) { + Thread.sleep(500); + out.write(Integer.toString(r).getBytes()); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }).start(); + } + }; + } + @POST @Path("/books/null") @Produces("application/xml") http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerWebSocketTest.java ---------------------------------------------------------------------- diff --git a/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerWebSocketTest.java b/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerWebSocketTest.java new file mode 100644 index 0000000..06cdce4 --- /dev/null +++ b/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerWebSocketTest.java @@ -0,0 +1,97 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.cxf.systest.jaxrs; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.cxf.jaxrs.model.AbstractResourceInfo; +import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class JAXRSClientServerWebSocketTest extends AbstractBusClientServerTestBase { + public static final String PORT = BookServer.PORT; + + @BeforeClass + public static void startServers() throws Exception { + final Map< String, Object > properties = new HashMap< String, Object >(); + properties.put("enableWebSocket", "true"); + + AbstractResourceInfo.clearAllMaps(); + assertTrue("server did not launch correctly", launchServer(new BookServer(properties))); + createStaticBus(); + } + + @Test + // seems to cause PermGen issue to another systests/jaxrs later in some system. the code under analysis + @org.junit.Ignore + public void testBookWithWebSocket() throws Exception { + String address = "ws://localhost:" + PORT + "/bookstore"; + + WebSocketTestClient wsclient = new WebSocketTestClient(address, 1); + wsclient.connect(); + try { + // call the GET service + wsclient.sendMessage("GET /bookstore/booknames/123".getBytes()); + assertTrue("one book must be returned", wsclient.await(3)); + List received = wsclient.getReceivedBytes(); + assertEquals(1, received.size()); + String value = new String(received.get(0)); + assertEquals("CXF in Action", value); + + // call another GET service + wsclient.reset(1); + wsclient.sendMessage("GET /bookstore/books/123".getBytes()); + assertTrue("response expected", wsclient.await(3)); + received = wsclient.getReceivedBytes(); + value = new String(received.get(0)); + assertTrue(value.startsWith("")); + + // call the GET service using POST + wsclient.reset(1); + wsclient.sendMessage("POST /bookstore/booknames\r\n\r\n123".getBytes()); + assertFalse("wrong method, no response expected", wsclient.await(3)); + + // call the POST service + wsclient.reset(1); + wsclient.sendMessage("POST /bookstore/booksplain\r\n\r\n123".getBytes()); + assertTrue("response expected", wsclient.await(3)); + received = wsclient.getReceivedBytes(); + value = new String(received.get(0)); + assertEquals("123", value); + + // call the GET service returning a continous stream output + wsclient.reset(6); + wsclient.sendMessage("GET /bookstore/bookbought".getBytes()); + assertTrue("wrong method, no response expected", wsclient.await(5)); + received = wsclient.getReceivedBytes(); + assertEquals(6, received.size()); + assertTrue((new String(received.get(0))).startsWith("Today:")); + for (int r = 2, i = 1; i < 6; r *= 2, i++) { + assertEquals(r, Integer.parseInt(new String(received.get(i)))); + } + } finally { + wsclient.close(); + } + } +} http://git-wip-us.apache.org/repos/asf/cxf/blob/8018b198/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/WebSocketTestClient.java ---------------------------------------------------------------------- diff --git a/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/WebSocketTestClient.java b/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/WebSocketTestClient.java new file mode 100644 index 0000000..3e1b3bc --- /dev/null +++ b/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/WebSocketTestClient.java @@ -0,0 +1,155 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.cxf.systest.jaxrs; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.logging.Logger; + +import com.ning.http.client.AsyncHttpClient; +import com.ning.http.client.websocket.WebSocket; +import com.ning.http.client.websocket.WebSocketByteListener; +import com.ning.http.client.websocket.WebSocketTextListener; +import com.ning.http.client.websocket.WebSocketUpgradeHandler; + +import org.apache.cxf.common.logging.LogUtils; + + + +/** + * Test client to do websocket calls. + * @see JAXRSClientServerWebSocketTest + * + * we may put this in test-tools so that other systests can use this code. + * for now keep it here to experiment jaxrs websocket scenarios. + */ +class WebSocketTestClient { + private static final Logger LOG = LogUtils.getL7dLogger(WebSocketTestClient.class); + + private List received; + private List receivedBytes; + private CountDownLatch latch; + private AsyncHttpClient client; + private WebSocket websocket; + private String url; + + public WebSocketTestClient(String url, int count) { + this.received = new ArrayList(); + this.receivedBytes = new ArrayList(); + this.latch = new CountDownLatch(count); + this.client = new AsyncHttpClient(); + this.url = url; + } + + public void connect() throws InterruptedException, ExecutionException, IOException { + websocket = client.prepareGet(url).execute( + new WebSocketUpgradeHandler.Builder().addWebSocketListener(new WsSocketListener()).build()).get(); + } + + public void sendTextMessage(String message) { + websocket.sendTextMessage(message); + } + + public void sendMessage(byte[] message) { + websocket.sendMessage(message); + } + + public boolean await(int secs) throws InterruptedException { + return latch.await(secs, TimeUnit.SECONDS); + } + + public void reset(int count) { + latch = new CountDownLatch(count); + received.clear(); + receivedBytes.clear(); + } + + public List getReceived() { + return received; + } + + public List getReceivedBytes() { + return receivedBytes; + } + + public void close() { + websocket.close(); + client.close(); + } + + class WsSocketListener implements WebSocketTextListener, WebSocketByteListener { + + public void onOpen(WebSocket ws) { + LOG.info("[ws] opened"); + } + + public void onClose(WebSocket ws) { + LOG.info("[ws] closed"); + } + + public void onError(Throwable t) { + LOG.info("[ws] error: " + t); + } + + public void onMessage(byte[] message) { + receivedBytes.add(message); + LOG.info("[ws] received bytes --> " + makeString(message)); + latch.countDown(); + } + + public void onFragment(byte[] fragment, boolean last) { + // TODO Auto-generated method stub + LOG.info("TODO [ws] received fragment bytes --> " + makeString(fragment) + "; last? " + last); + } + + public void onMessage(String message) { + received.add(message); + LOG.info("[ws] received --> " + message); + latch.countDown(); + } + + public void onFragment(String fragment, boolean last) { + // TODO Auto-generated method stub + LOG.info("TODO [ws] received fragment --> " + fragment + "; last? " + last); + } + + } + + private static String makeString(byte[] data) { + return data == null ? null : makeString(data, 0, data.length).toString(); + } + + private static StringBuilder makeString(byte[] data, int offset, int length) { + if (data .length > 256) { + return makeString(data, offset, 256).append("..."); + } + StringBuilder xbuf = new StringBuilder().append("\nHEX: "); + StringBuilder cbuf = new StringBuilder().append("\nASC: "); + for (byte b : data) { + xbuf.append(Integer.toHexString(0xff & b)).append(' '); + cbuf.append((0x80 & b) != 0 ? '.' : (char)b).append(" "); + } + return xbuf.append(cbuf); + } +}