Java Code Examples for io.netty.handler.codec.http.FullHttpResponse#getStatus()

The following examples show how to use io.netty.handler.codec.http.FullHttpResponse#getStatus() . 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: WebSocketTestClient.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {

    Channel ch = ctx.channel();

    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) o);
        // the handshake response was processed upgrade is complete
        handshakeLatch.countDown();
        ReferenceCountUtil.release(o);
        return;
    }

    if (o instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) o;
        ReferenceCountUtil.release(o);
        throw new Exception("Unexpected HttpResponse (status=" + response.getStatus() + ", content="
                + response.content().toString(CharsetUtil.UTF_8) + ')');
    }
    ctx.fireChannelRead(o);
}
 
Example 2
Source File: WebSocketClientHandshaker13.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
    }

    String accept = headers.get(Names.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 3
Source File: WebSocketClientHandshaker07.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
    }

    String accept = headers.get(Names.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 4
Source File: WebSocketClientHandshaker08.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
    }

    String accept = headers.get(Names.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example 5
Source File: SessionAuthDelegate.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAuthorized(ChannelHandlerContext ctx, FullHttpRequest req) {
   if(!sessionAuth.isAuthorized(ctx, req)) {
      logger.debug("session is not authorized, attempting to authenticate request");
      FullHttpResponse response = authenticator.authenticateRequest(ctx.channel(), req);
      logger.debug("response from authenticator is {}", response);
      return response != null && response.getStatus() != HttpResponseStatus.UNAUTHORIZED;
   }
   return true;
}
 
Example 6
Source File: WebSocketClientHandler.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    moniter.updateTime();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.getStatus() +
                        ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
    	 TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
    	 service.onReceive(textFrame.text());
    } else if (frame instanceof BinaryWebSocketFrame) {
    	BinaryWebSocketFrame binaryFrame=(BinaryWebSocketFrame)frame;
    	service.onReceive(decodeByteBuff(binaryFrame.content()));
    }else if (frame instanceof PongWebSocketFrame) {
        System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        System.out.println("WebSocket Client received closing");
        ch.close();
    }
}
 
Example 7
Source File: WebSocketClientHandler.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    moniter.updateTime();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.getStatus() +
                        ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
    	 TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
    	 service.onReceive(textFrame.text());
    } else if (frame instanceof BinaryWebSocketFrame) {
    	BinaryWebSocketFrame binaryFrame=(BinaryWebSocketFrame)frame;
    	service.onReceive(decodeByteBuff(binaryFrame.content()));
    }else if (frame instanceof PongWebSocketFrame) {
        System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        System.out.println("WebSocket Client received closing");
        ch.close();
    }
}
 
Example 8
Source File: WebSocketClientHandler.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.getStatus() +
                        ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        System.out.println("WebSocket Client received message: " + textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
        System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        System.out.println("WebSocket Client received closing");
        ch.close();
    }
}
 
Example 9
Source File: WebSocketClientHandshaker00.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 WebSocket Protocol Handshake
 * Upgrade: WebSocket
 * Connection: Upgrade
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Location: ws://example.com/demo
 * Sec-WebSocket-Protocol: sample
 *
 * 8jKS'y:G*Co,Wxa-
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = new HttpResponseStatus(101, "WebSocket Protocol Handshake");

    if (!response.getStatus().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.getStatus());
    }

    HttpHeaders headers = response.headers();

    String upgrade = headers.get(Names.UPGRADE);
    if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
                + upgrade);
    }

    String connection = headers.get(Names.CONNECTION);
    if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + connection);
    }

    ByteBuf challenge = response.content();
    if (!challenge.equals(expectedChallengeResponseBytes)) {
        throw new WebSocketHandshakeException("Invalid challenge");
    }
}
 
Example 10
Source File: Tracker.java    From blueflood with Apache License 2.0 5 votes vote down vote up
public void trackResponse(HttpRequest request, FullHttpResponse response) {
    // check if tenantId is being tracked by JMX TenantTrackerMBean and log the response if it is
    // HttpRequest is needed for original request uri and tenantId
    if (request == null) return;
    if (response == null) return;

    String tenantId = findTid( request.getUri() );
    if (isTracking(tenantId)) {
        HttpResponseStatus status = response.getStatus();
        String messageBody = response.content().toString(Constants.DEFAULT_CHARSET);

        // get parameters
        String queryParams = getQueryParameters(request);

        // get headers
        String headers = "";
        for (String headerName : response.headers().names()) {
            headers += "\n" + headerName + "\t" + response.headers().get(headerName);
        }

        // get response content
        String responseContent = "";
        if ((messageBody != null) && (!messageBody.isEmpty())) {
            responseContent = "\nRESPONSE_CONTENT:\n" + messageBody;
        }

        String logMessage = "[TRACKER] " +
                "Response for tenantId " + tenantId + " " + request.getMethod() + " request " + request.getUri() + queryParams +
                "\nRESPONSE_STATUS: " + status.code() +
                "\nRESPONSE HEADERS: " + headers +
                responseContent;

        log.info(logMessage);
    }

}
 
Example 11
Source File: IpcdClientHandler.java    From arcusipcd with Apache License 2.0 4 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
	Channel ch = ctx.channel();
       if (!handshaker.isHandshakeComplete()) {
           handshaker.finishHandshake(ch, (FullHttpResponse) msg);
           logger.info("Ipcd client connected");
           handshakeFuture.setSuccess();
           return;
       }
       
       if (msg instanceof FullHttpResponse) {
           FullHttpResponse response = (FullHttpResponse) msg;
           Exception e = new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content="
                   + response.content().toString(CharsetUtil.UTF_8) + ')');
           logger.error("Unexpected FullHttpResponse after websocket connection", e);
           throw e;
       }

       WebSocketFrame frame = (WebSocketFrame) msg;
       if (frame instanceof TextWebSocketFrame) {
           TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
           
           logger.debug("received message: " + textFrame.text());
           
           // TODO handle message from server
           ServerMessage ipcdmsg = serializer.parseServerMessage(new StringReader(textFrame.text()));
           switch(ipcdmsg.getCommand()) {
            case GetParameterValues:
            	getParameterValuesHandler.handleCommand((GetParameterValuesCommand)ipcdmsg);
				break;
            case SetParameterValues:
            	setParameterValuesHandler.handleCommand((SetParameterValuesCommand)ipcdmsg);
				break;
            case GetDeviceInfo:
            	getDeviceInfoHandler.handleCommand((GetDeviceInfoCommand)ipcdmsg);
            	break;
            case SetDeviceInfo:
            	setDeviceInfoHandler.handleCommand((SetDeviceInfoCommand)ipcdmsg);
            	break;
			case Download:
				downloadHandler.handleCommand((DownloadCommand)ipcdmsg);
				break;
			case Reboot:
				rebootHandler.handleCommand((RebootCommand)ipcdmsg);
				break;
			case FactoryReset:
				factoryResetHandler.handleCommand((FactoryResetCommand)ipcdmsg);
				break;
			case Leave:
				leaveHandler.handleCommand((LeaveCommand)ipcdmsg);
				break;
			case GetParameterInfo:
				getParameterInfoHandler.handleCommand((GetParameterInfoCommand)ipcdmsg);
				break;
			case GetEventConfiguration:
				getEventConfigurationHandler.handleCommand((GetEventConfigurationCommand)ipcdmsg);
				break;
			case GetReportConfiguration:
				getReportConfigurationHandler.handleCommand((GetReportConfigurationCommand)ipcdmsg);
				break;
			case SetEventConfiguration:
				setEventConfigurationHandler.handleCommand((SetEventConfigurationCommand)ipcdmsg);
				break;
			case SetReportConfiguration:
				setReportConfigurationHandler.handleCommand((SetReportConfigurationCommand)ipcdmsg);
				break;
			default:
				break;
           }
       } else if (frame instanceof PongWebSocketFrame) {
           logger.debug("IPCD Client received pong");
       } else if (frame instanceof CloseWebSocketFrame) {
           logger.info("WebSocket Client received closing");
           ch.close();
       }
	
}
 
Example 12
Source File: ResetPasswordRESTHandler.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   String json = req.content().toString(CharsetUtil.UTF_8);
   ClientMessage clientMessage = JSON.fromJson(json, ClientMessage.class);

   MessageBody body = clientMessage.getPayload();

   String email = PersonService.ResetPasswordRequest.getEmail(body);
   String password = PersonService.ResetPasswordRequest.getPassword(body);
   Person person = personDao.findByEmail(email);

   Errors.assertValidRequest(password.length() < MAX_PASSWORD_LENGTH, "New password is too long.");
   Errors.assertValidRequest(password.length() > MIN_PASSWORD_LENGTH, "New password is missing or too short.");

   if(person == null) {
      return error(CODE_PERSON_NOT_FOUND, PERSON_NOT_FOUND_MSG);
   }

   ResetPasswordResult result = personDao.resetPassword(email,
         PersonService.ResetPasswordRequest.getToken(body),
         password);

   if (result == FAILURE) {
      logger.info("person=[{}] failed to reset their password - general failure", person.getId()); // Audit event
      return error(CODE_PERSON_RESET_FAILED, PASSWORD_RESET_FAILED_MSG);
   }
   else if (result == TOKEN_FAILURE) {
      logger.info("person=[{}] failed to reset their password - wrong token", person.getId()); // Audit event
      return error(CODE_PERSON_RESET_TOKEN_FAILED, PASSWORD_RESET_TOKEN_FAILED_MSG);
   }

   logger.info("person=[{}] reset their password", person.getId()); // Audit event
   notify(person);
   FullHttpResponse response = login(email, password, ctx);

   Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(response.headers().get(HttpHeaders.Names.SET_COOKIE));
   String newSessId = cookies.stream()
      .filter(c -> Objects.equals(c.name(), cookieConfig.getAuthCookieName()))
      .findFirst()
      .map(Cookie::value)
      .orElse(null);

   // internal message to all client bridges to boot active sessions for this user now that there password
   // has changed
   platformBus.send(
      PlatformMessage.buildBroadcast(
         PersonCapability.PasswordChangedEvent.builder().withSession(newSessId).build(),
         Address.fromString(person.getAddress())
      )
      .create()
   );

   if(response.getStatus() == HttpResponseStatus.OK) {
      ClientMessage message = ClientMessage.builder()
            .withCorrelationId(clientMessage.getCorrelationId())
            .withSource(Address.platformService(PersonService.NAMESPACE).getRepresentation())
            .withPayload(PersonService.SendPasswordResetResponse.instance())
            .create();
      DefaultFullHttpResponse http = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1,
            HttpResponseStatus.OK,
            Unpooled.copiedBuffer(JSON.toJson(message), CharsetUtil.UTF_8)
      );
      http.headers().set(response.headers());
      return http;
   }
   return response;
}