Java Code Examples for org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse#sendError()

The following examples show how to use org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse#sendError() . 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: 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 2
Source File: ProducerHandler.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public ProducerHandler(WebSocketService service, HttpServletRequest request, ServletUpgradeResponse response) {
    super(service, request, response);
    this.numMsgsSent = new LongAdder();
    this.numBytesSent = new LongAdder();
    this.numMsgsFailed = new LongAdder();
    this.publishLatencyStatsUSec = new StatsBuckets(ENTRY_LATENCY_BUCKETS_USEC);

    if (!checkAuth(response)) {
        return;
    }

    try {
        this.producer = getProducerBuilder(service.getPulsarClient()).topic(topic.toString()).create();
        if (!this.service.addProducer(this)) {
            log.warn("[{}:{}] Failed to add producer handler for topic {}", request.getRemoteAddr(),
                    request.getRemotePort(), topic);
        }
    } catch (Exception e) {
        log.warn("[{}:{}] Failed in creating producer on topic {}: {}", request.getRemoteAddr(),
                request.getRemotePort(), topic, e.getMessage());

        try {
            response.sendError(getErrorCode(e), getErrorMessage(e));
        } catch (IOException e1) {
            log.warn("[{}:{}] Failed to send error: {}", request.getRemoteAddr(), request.getRemotePort(),
                    e1.getMessage(), e1);
        }
    }
}
 
Example 3
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 4
Source File: ReaderHandler.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public ReaderHandler(WebSocketService service, HttpServletRequest request, ServletUpgradeResponse response) {
    super(service, request, response);

    final int receiverQueueSize = getReceiverQueueSize();

    this.maxPendingMessages = (receiverQueueSize == 0) ? 1 : receiverQueueSize;
    this.numMsgsDelivered = new LongAdder();
    this.numBytesDelivered = new LongAdder();

    if (!checkAuth(response)) {
        return;
    }

    try {
        ReaderBuilder<byte[]> builder = service.getPulsarClient().newReader()
                .topic(topic.toString())
                .startMessageId(getMessageId())
                .receiverQueueSize(receiverQueueSize);
        if (queryParams.containsKey("readerName")) {
            builder.readerName(queryParams.get("readerName"));
        }

        this.reader = builder.create();

        this.subscription = ((ReaderImpl<?>) this.reader).getConsumer().getSubscription();
        if (!this.service.addReader(this)) {
            log.warn("[{}:{}] Failed to add reader handler for topic {}", request.getRemoteAddr(),
                    request.getRemotePort(), topic);
        }
    } catch (Exception e) {
        log.warn("[{}:{}] Failed in creating reader {} on topic {}", request.getRemoteAddr(),
                request.getRemotePort(), subscription, topic, e);
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to create reader: " + e.getMessage());
        } catch (IOException e1) {
            log.warn("[{}:{}] Failed to send error: {}", request.getRemoteAddr(), request.getRemotePort(),
                    e1.getMessage(), e1);
        }
    }
}
 
Example 5
Source File: ConsumerHandler.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public ConsumerHandler(WebSocketService service, HttpServletRequest request, ServletUpgradeResponse response) {
    super(service, request, response);

    ConsumerBuilderImpl<byte[]> builder;

    this.numMsgsDelivered = new LongAdder();
    this.numBytesDelivered = new LongAdder();
    this.numMsgsAcked = new LongAdder();
    this.pullMode = Boolean.valueOf(queryParams.get("pullMode"));

    try {
        // checkAuth() and getConsumerConfiguration() should be called after assigning a value to this.subscription
        this.subscription = extractSubscription(request);
        builder = (ConsumerBuilderImpl<byte[]>) getConsumerConfiguration(service.getPulsarClient());

        if (!this.pullMode) {
            this.maxPendingMessages = (builder.getConf().getReceiverQueueSize() == 0) ? 1
                    : builder.getConf().getReceiverQueueSize();
        }
        this.subscriptionType = builder.getConf().getSubscriptionType();

        if (!checkAuth(response)) {
            return;
        }

        this.consumer = builder.topic(topic.toString()).subscriptionName(subscription).subscribe();
        if (!this.service.addConsumer(this)) {
            log.warn("[{}:{}] Failed to add consumer handler for topic {}", request.getRemoteAddr(),
                    request.getRemotePort(), topic);
        }
    } catch (Exception e) {
        log.warn("[{}:{}] Failed in creating subscription {} on topic {}", request.getRemoteAddr(),
                request.getRemotePort(), subscription, topic, e);

        try {
            response.sendError(getErrorCode(e), getErrorMessage(e));
        } catch (IOException e1) {
            log.warn("[{}:{}] Failed to send error: {}", request.getRemoteAddr(), request.getRemotePort(),
                    e1.getMessage(), e1);
        }
    }
}
 
Example 6
Source File: WebSocketReceiverServlet.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private boolean validateAppId(ServletUpgradeRequest req, ServletUpgradeResponse res) throws ServletException, IOException {
  boolean valid = false;
  String ourAppId = null;
  try {
    ourAppId = getReceiver().getAppId().get();
  } catch (StageException e) {
    throw new IOException("Cant resolve credential value", e);
  }

  String requester = req.getRemoteAddress() + ":" + req.getRemotePort();
  String reqAppId = req.getHeader(HttpConstants.X_SDC_APPLICATION_ID_HEADER);

  if (reqAppId == null && receiver.isAppIdViaQueryParamAllowed()) {
    Map<String,List<String>> parameterMap = req.getParameterMap();
    if (parameterMap != null && parameterMap.containsKey(HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM)) {
      List<String> values = parameterMap.get(HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM);
      if (values != null && values.size() > 0) {
        reqAppId = values.get(0);
      }
    }
  }

  if (reqAppId == null) {
    // Since it is not possible to pass headers in some of the WebSockets client (example: browser WebSocket API)
    // http://stackoverflow.com/questions/4361173/http-headers-in-websockets-client-api
    // check sub-protocol header for APP ID
    List<String> subProtocols = req.getSubProtocols();
    if (subProtocols != null && subProtocols.contains(ourAppId)) {
      reqAppId = ourAppId;
      res.setAcceptedSubProtocol(reqAppId);
    }
  }

  if (reqAppId == null) {
    LOG.warn("Request from '{}' missing appId, rejected", requester);
    res.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing 'appId'");
  } if (reqAppId != null && !ourAppId.equals(reqAppId)) {
    LOG.warn("Request from '{}' invalid appId '{}', rejected", requester, reqAppId);
    res.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid 'appId'");
  } else {
    valid = true;
  }
  return valid;
}