org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest Java Examples

The following examples show how to use org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebSocketProvider.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@OnWebSocketConnect @SuppressWarnings("unused")
public void onWebSocketConnect(final Session session)
{
    SocketAddress localAddress = session.getLocalAddress();
    SocketAddress remoteAddress = session.getRemoteAddress();
    _protocolEngine = _factory.newProtocolEngine(remoteAddress);

    // Let AMQP do timeout handling
    session.setIdleTimeout(0);

    _connectionWrapper = new ConnectionWrapper(session, localAddress, remoteAddress, _protocolEngine, _server.getThreadPool());
    if (session.getUpgradeRequest() instanceof ServletUpgradeRequest)
    {
        ServletUpgradeRequest upgradeRequest = (ServletUpgradeRequest) session.getUpgradeRequest();
        if (upgradeRequest.getCertificates() != null && upgradeRequest.getCertificates().length > 0)
        {
            _connectionWrapper.setPeerCertificate(upgradeRequest.getCertificates()[0]);
        }
    }
    _protocolEngine.setNetworkConnection(_connectionWrapper);
    _protocolEngine.setWorkListener(object -> _server.getThreadPool().execute(() -> _connectionWrapper.doWork()));
    _activeConnections.add(_connectionWrapper);
    _idleTimeoutChecker.wakeup();

}
 
Example #2
Source File: ExchangeSocketCreator.java    From conga with Apache License 2.0 6 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) {
  Principal principal = request.getUserPrincipal();
  String source;
  source = (null != principal) ? principal.getName() : request.getRemoteAddress();
  for (String subprotocol : request.getSubProtocols()) {
    if ("binary".equals(subprotocol)) {
      response.setAcceptedSubProtocol(subprotocol);
      return new BinaryExchangeSocket(sessions, ringBuffer, source);
    } else if ("text".equals(subprotocol)) {
      response.setAcceptedSubProtocol(subprotocol);
      return new TextExchangeSocket(sessions, ringBuffer, source);
    }
  }

  return null;
}
 
Example #3
Source File: JettyWebSocketClientTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
public TestJettyWebSocketServer(final WebSocketHandler webSocketHandler) {

			this.server = new Server();
			ServerConnector connector = new ServerConnector(this.server);
			connector.setPort(0);

			this.server.addConnector(connector);
			this.server.setHandler(new org.eclipse.jetty.websocket.server.WebSocketHandler() {
				@Override
				public void configure(WebSocketServletFactory factory) {
					factory.setCreator(new WebSocketCreator() {
						@Override
						public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
							if (!CollectionUtils.isEmpty(req.getSubProtocols())) {
								resp.setAcceptedSubProtocol(req.getSubProtocols().get(0));
							}
							JettyWebSocketSession session = new JettyWebSocketSession(null, null);
							return new JettyWebSocketHandlerAdapter(webSocketHandler, session);
						}
					});
				}
			});
		}
 
Example #4
Source File: JettyWebSocketClientTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public TestJettyWebSocketServer(final WebSocketHandler webSocketHandler) {

			this.server = new Server();
			ServerConnector connector = new ServerConnector(this.server);
			connector.setPort(0);

			this.server.addConnector(connector);
			this.server.setHandler(new org.eclipse.jetty.websocket.server.WebSocketHandler() {
				@Override
				public void configure(WebSocketServletFactory factory) {
					factory.setCreator(new WebSocketCreator() {
						@Override
						public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
							if (!CollectionUtils.isEmpty(req.getSubProtocols())) {
								resp.setAcceptedSubProtocol(req.getSubProtocols().get(0));
							}
							JettyWebSocketSession session = new JettyWebSocketSession(null, null);
							return new JettyWebSocketHandlerAdapter(webSocketHandler, session);
						}
					});
				}
			});
		}
 
Example #5
Source File: JettyWebSocketClientTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public TestJettyWebSocketServer(int port, final WebSocketHandler webSocketHandler) {

			this.server = new Server();
			ServerConnector connector = new ServerConnector(this.server);
			connector.setPort(port);

			this.server.addConnector(connector);
			this.server.setHandler(new org.eclipse.jetty.websocket.server.WebSocketHandler() {
				@Override
				public void configure(WebSocketServletFactory factory) {
					factory.setCreator(new WebSocketCreator() {
						@Override
						public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
							if (!CollectionUtils.isEmpty(req.getSubProtocols())) {
								resp.setAcceptedSubProtocol(req.getSubProtocols().get(0));
							}
							JettyWebSocketSession session = new JettyWebSocketSession(null, null);
							return new JettyWebSocketHandlerAdapter(webSocketHandler, session);
						}
					});
				}
			});
		}
 
Example #6
Source File: EgressMobiusHandler.java    From warp10-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(final WebSocketServletFactory factory) {
  
  final EgressMobiusHandler self = this;

  final WebSocketCreator oldcreator = factory.getCreator();
  
  WebSocketCreator creator = new WebSocketCreator() {
    @Override
    public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
      MobiusWebSocket ws = (MobiusWebSocket) oldcreator.createWebSocket(req, resp);
      ws.setMobiusHandler(self);
      return ws;
    }
  };

  factory.setCreator(creator);
  super.configure(factory);
}
 
Example #7
Source File: EgressInteractiveHandler.java    From warp10-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(final WebSocketServletFactory factory) {
  
  final EgressInteractiveHandler self = this;

  final WebSocketCreator oldcreator = factory.getCreator();
  
  WebSocketCreator creator = new WebSocketCreator() {
    @Override
    public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
      InteractiveWebSocket ws = (InteractiveWebSocket) oldcreator.createWebSocket(req, resp);
      ws.setHandler(self);
      try {
        ws.setProcessor(new InteractiveProcessor(self, null, null, null, null));
      } catch (IOException ioe) {
        throw new RuntimeException(ioe);
      }
      return ws;
    }
  };

  factory.setCreator(creator);
  super.configure(factory);
}
 
Example #8
Source File: WebSocketHandler.java    From purplejs with Apache License 2.0 6 votes vote down vote up
public Object createWebSocket( final ServletUpgradeRequest req, final ServletUpgradeResponse res )
{
    final Set<String> allowSubProtocols = this.config.getSubProtocols();
    if ( allowSubProtocols.isEmpty() )
    {
        return doCreateWebSocket();
    }

    for ( final String protocol : req.getSubProtocols() )
    {
        if ( allowSubProtocols.contains( protocol ) )
        {
            res.setAcceptedSubProtocol( protocol );
            return doCreateWebSocket();
        }
    }

    return null;
}
 
Example #9
Source File: PlayerSocketCreator.java    From codenjoy with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PlayerSocket createWebSocket(ServletUpgradeRequest servletRequest, ServletUpgradeResponse response) {
    HttpServletRequest request = servletRequest.getHttpServletRequest();
    String authId = authenticationService.authenticate(request);
    PlayerSocket socket = new PlayerSocket(authId, waitForClient);
    if (authId == null) {
        log.warn("Unauthorized access [{}] from {}", getParameters(request), request.getRemoteAddr());
        try {
            response.sendError(401, UNAUTHORIZED_ACCESS);
        } catch (IOException e) {
            log.warn("Error sending status {}", e.getMessage());
        }
        return null;
    }
    socket.onClose(() -> transport.unregisterPlayerSocket(socket));
    transport.registerPlayerSocket(authId, socket);
    return socket;
}
 
Example #10
Source File: ModuleBasedWebSocketCreator.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest req,
		ServletUpgradeResponse resp) {
	String requestPath = req.getRequestPath();
    Map<String, List<String>> paramsMap = req.getParameterMap();
    String jobName = paramsMap.get("jobName").get(0);
	switch(requestPath){
	case WebConstants.JOB_ANALYSIS_SOCKET_URL:{
		jobAnalysisSocket = new JobAnalysisSocket(jobName);
		return jobAnalysisSocket;
	}
	case WebConstants.DATA_ANALYSIS_SOCKET_URL:{
		dataAnalysisSocket = new DataAnalysisSocket();
		return dataAnalysisSocket;
	}
	}
	return null;
}
 
Example #11
Source File: GatewayWebsocketHandler.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest req,
    ServletUpgradeResponse resp) {

  try {
    final URI requestURI = req.getRequestURI();
    final String path = requestURI.getPath();

    /* URL used to connect to websocket backend */
    final String backendURL = getMatchedBackendURL(path, requestURI);
    LOG.debugLog("Generated backend URL for websocket connection: " + backendURL);

    /* Upgrade happens here */
    final ClientEndpointConfig clientConfig = getClientEndpointConfig(req);
    clientConfig.getUserProperties().put("org.apache.knox.gateway.websockets.truststore", getTruststore());
    return new ProxyWebSocketAdapter(URI.create(backendURL), pool, clientConfig, config);
  } catch (final Exception e) {
    LOG.failedCreatingWebSocket(e);
    throw new RuntimeException(e);
  }
}
 
Example #12
Source File: ServerRpcProvider.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("cast")
@Override
public void configure(WebSocketServletFactory factory) {
  if (websocketMaxIdleTime == 0) {
    // Jetty does not allow to set infinite timeout.
    factory.getPolicy().setIdleTimeout(Integer.MAX_VALUE);
  } else {
    factory.getPolicy().setIdleTimeout(websocketMaxIdleTime);
  }
  factory.getPolicy().setMaxTextMessageSize(websocketMaxMessageSize * 1024 * 1024);
  factory.setCreator(new WebSocketCreator() {
    @Override
    public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
      ParticipantId loggedInUser =
          provider.sessionManager.getLoggedInUser(req.getSession());

      return new WebSocketConnection(loggedInUser, provider).getWebSocketServerChannel();
    }
  });
}
 
Example #13
Source File: PHttpServer.java    From jphp with Apache License 2.0 6 votes vote down vote up
@Signature
public void addWebSocket(Environment env, String path, ArrayMemory _handlers) {
    WebSocketParam param = _handlers.toBean(env, WebSocketParam.class);

    ContextHandler contextHandler = new ContextHandler(path);
    contextHandler.setHandler(new WebSocketHandler() {
        @Override
        public void configure(WebSocketServletFactory factory) {
            factory.setCreator(new WebSocketCreator() {
                @Override
                public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
                    return new WebSocket(env, param);
                }
            });
        }
    });

    handlers.addHandler(contextHandler);
}
 
Example #14
Source File: NotebookWebSocketCreator.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) {
  String origin = request.getHeader("Origin");
  if (notebookServer.checkOrigin(request.getHttpServletRequest(), origin)) {
    return new NotebookSocket(request.getHttpServletRequest(), "", notebookServer);
  } else {
    LOG.error("Websocket request is not allowed by {} settings. Origin: {}",
        ZEPPELIN_ALLOWED_ORIGINS, origin);
    return null;
  }
}
 
Example #15
Source File: WebSocketCreatorImpl.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
    LOG.info("createWebSocket ...");
    Long id = atomicLong.getAndIncrement();
    WsEndpoint wsEndpoint = new WsEndpoint(id, this, requestRouter);
    wsEndPoints.put(id, wsEndpoint);
    return wsEndpoint;
}
 
Example #16
Source File: WebSocketTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(final WebSocketServletFactory factory) {
    factory.register(EventsWebSocket.class);
    factory.setCreator(new WebSocketCreator() {
        @Override
        public EventsWebSocket createWebSocket(final ServletUpgradeRequest servletUpgradeRequest,
                final ServletUpgradeResponse servletUpgradeResponse) {
            return new EventsWebSocket();
        }
    });
}
 
Example #17
Source File: WebSocketReceiverServlet.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse res) {
  String requester = req.getRemoteAddress() + ":" + req.getRemotePort();
  if (isShuttingDown()) {
    LOG.debug("Shutting down, discarding incoming request from '{}'", requester);
    res.setStatusCode(HttpServletResponse.SC_GONE);
    return null;
  }

  try {
    if (validateRequest(req, res)) {
      LOG.debug("Request accepted from '{}'", requester);
      return new WebSocketReceiverSocket(
          requester,
          receiver,
          errorQueue,
          requestMeter,
          invalidRequestMeter,
          errorRequestMeter,
          requestTimer
      );
    }
  } catch (Exception ex) {
    errorQueue.offer(ex);
    errorRequestMeter.mark();
    LOG.warn("Error while processing request payload from '{}': {}", requester, ex.toString(), ex);
    try {
      res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString());
    } catch (IOException e) {
      LOG.warn("Error while sending WebSocket error message: {}", ex.toString(), ex);
    }
  }
  invalidRequestMeter.mark();
  return null;
}
 
Example #18
Source File: WebSocketTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(final WebSocketServletFactory factory) {
    factory.register(CookiesWebSocket.class);
    factory.setCreator(new WebSocketCreator() {
        @Override
        public Object createWebSocket(final ServletUpgradeRequest servletUpgradeRequest,
                final ServletUpgradeResponse servletUpgradeResponse) {
            return new CookiesWebSocket();
        }
    });
}
 
Example #19
Source File: PlayerTransportTest.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
private PlayerSocket createWebSocket() {
    ServletUpgradeRequest request = mock(ServletUpgradeRequest.class);
    HttpServletRequest httpRequest = mock(HttpServletRequest.class);
    when(request.getHttpServletRequest()).thenReturn(httpRequest);
    ServletUpgradeResponse response = mock(ServletUpgradeResponse.class);
    responses.add(response);
    return creator.createWebSocket(request, response);
}
 
Example #20
Source File: SOSWebSocket.java    From sensorhub with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp)
{
    // return null if request was not accepted
    if (request == null)
        return null;
    
    return this;
}
 
Example #21
Source File: WebSocketTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(final WebSocketServletFactory factory) {
    factory.register(ChatWebSocket.class);
    factory.setCreator(new WebSocketCreator() {
        @Override
        public Object createWebSocket(final ServletUpgradeRequest servletUpgradeRequest,
                final ServletUpgradeResponse servletUpgradeResponse) {
            return new ChatWebSocket();
        }
    });
}
 
Example #22
Source File: OpenfireWebSocketServlet.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(WebSocketServletFactory factory)
{
    if (XmppWebSocket.isCompressionEnabled()) {
        factory.getExtensionFactory().register("permessage-deflate", PerMessageDeflateExtension.class);
    }
    final int messageSize = JiveGlobals.getIntProperty("xmpp.parser.buffer.size", 1048576);
    factory.getPolicy().setMaxTextMessageBufferSize(messageSize * 5);
    factory.getPolicy().setMaxTextMessageSize(messageSize);
    factory.setCreator(new WebSocketCreator() {
        @Override
        public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp)
        {
            try {
                for (String subprotocol : req.getSubProtocols())
                {
                    if ("xmpp".equals(subprotocol))
                    {
                        resp.setAcceptedSubProtocol(subprotocol);
                        return new XmppWebSocket();
                    }
                }
            } catch (Exception e) {
                Log.warn(MessageFormat.format("Unable to load websocket factory: {0} ({1})", e.getClass().getName(), e.getMessage()));
            }
            Log.warn("Failed to create websocket for {}:{} make a request at {}", req.getRemoteAddress(), req.getRemotePort(), req.getRequestPath() );
            return null;
        }
    });
}
 
Example #23
Source File: GatewayWebsocketHandler.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link ClientEndpointConfig} config that contains the headers
 * to be passed to the backend.
 * @since 0.14.0
 */
private ClientEndpointConfig getClientEndpointConfig(final ServletUpgradeRequest req) {

  return ClientEndpointConfig.Builder.create().configurator( new ClientEndpointConfig.Configurator() {

     @Override
     public void beforeRequest(final Map<String, List<String>> headers) {

       /* Add request headers */
       req.getHeaders().forEach(headers::putIfAbsent);

     }
  }).build();
}
 
Example #24
Source File: JettyWebSocketServlet.java    From sequenceiq-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(WebSocketServletFactory webSocketServletFactory) {
    webSocketServletFactory.setCreator(new WebSocketCreator() {
        @Override
        public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
            return new JettyWebSocketListener(channelProcessor);
        }
    });
}
 
Example #25
Source File: KafkaWebSocketCreator.java    From opensoc-streaming with Apache License 2.0 5 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) 
{
	boolean authGood = false;
	List<HttpCookie> cookies = request.getCookies();
	for( HttpCookie cookie : cookies )
	{
		String name = cookie.getName();
		if( name!= null && name.equals( "authToken" ))
		{
			String value = cookie.getValue();
			
			try
			{
				if( value != null && AuthToken.validateToken(configProps, value))
				{
					authGood = true;
					break;
				}
			}
			catch( Exception e )
			{
				logger.error(" Exception validating authToken:", e );
				authGood = false;
				break;
			}
			
		}
		else
		{
			continue;
		}
	}

	return new KafkaMessageSenderSocket( configProps, authGood );
}
 
Example #26
Source File: ScriptExecutionReportingWebSocketServlet.java    From gp2srv with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void configure(WebSocketServletFactory factory) {
	factory.setCreator(new WebSocketCreator() {
		public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
			return new ScriptExecutionReportingWebSocket(logger);
		}
	});
}
 
Example #27
Source File: UiWebSocketServlet.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) {
    if (!isStopped) {
        // FIXME: Replace this with globally shared opaque token to allow secure failover
        Principal p = request.getUserPrincipal();
        String userName = p != null ? p.getName() : FAKE_USERNAME;

        UiWebSocket socket = new UiWebSocket(directory, userName);
        sockets.add(socket);
        return socket;
    }
    return null;
}
 
Example #28
Source File: JettyWebSocketServer.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest servletUpgradeRequest, ServletUpgradeResponse servletUpgradeResponse) {
    final URI requestURI = servletUpgradeRequest.getRequestURI();
    final int port = servletUpgradeRequest.getLocalPort();
    final JettyWebSocketServer service = portToControllerService.get(port);

    if (service == null) {
        throw new RuntimeException("No controller service is bound with port: " + port);
    }

    final String path = requestURI.getPath();
    final WebSocketMessageRouter router;
    try {
        router = service.routers.getRouterOrFail(path);
    } catch (WebSocketConfigurationException e) {
        throw new IllegalStateException("Failed to get router due to: "  + e, e);
    }

    final RoutingWebSocketListener listener = new RoutingWebSocketListener(router) {
        @Override
        public void onWebSocketConnect(Session session) {
            final WebSocketPolicy currentPolicy = session.getPolicy();
            currentPolicy.setInputBufferSize(service.configuredPolicy.getInputBufferSize());
            currentPolicy.setMaxTextMessageSize(service.configuredPolicy.getMaxTextMessageSize());
            currentPolicy.setMaxBinaryMessageSize(service.configuredPolicy.getMaxBinaryMessageSize());
            super.onWebSocketConnect(session);
        }
    };

    return listener;
}
 
Example #29
Source File: ConsoleLogSocketCreatorTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    restfulService = mock(RestfulService.class);

    request = mock(ServletUpgradeRequest.class);
    creator = new ConsoleLogSocketCreator(mock(ConsoleLogSender.class), restfulService, new SocketHealthService(), new SystemEnvironment());
}
 
Example #30
Source File: StderrUpdateSocketCreator.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest servletUpgradeRequest, ServletUpgradeResponse servletUpgradeResponse) {
    final JobId jobId = extractJobId(servletUpgradeRequest.getRequestPath());

    return this.jobManagerEvents
            .stderrUpdates(jobId)
            .map(observable -> new ObservableByteArraySocket("stderr updates", observable))
            .orElse(null); // Effectively, a HTTP 404
}