Example #1
0
  @Test
  public void testStaticEncoding() throws Exception {

    final AsciiString method = GET.asciiName();
    final AsciiString scheme = SCHEME_HTTPS;
    final AsciiString authority = AsciiString.of("www.example.com");
    final AsciiString path = AsciiString.of("/index.html");

    final ByteBuf buf = Unpooled.buffer();
    writeMethod(buf, method);
    writeScheme(buf, scheme);
    writeAuthority(buf, authority);
    writePath(buf, path);

    final Decoder decoder = new Decoder(Integer.MAX_VALUE, Integer.MAX_VALUE);
    final ByteBufInputStream in = new ByteBufInputStream(buf);
    final HeaderListener listener = mock(HeaderListener.class);
    decoder.decode(in, listener);

    verify(listener).addHeader(HEADER_METHOD.array(), method.array(), false);
    verify(listener).addHeader(HEADER_SCHEME.array(), scheme.array(), false);
    verify(listener).addHeader(HEADER_AUTHORITY.array(), authority.array(), false);
    verify(listener).addHeader(HEADER_PATH.array(), path.array(), false);

    verifyNoMoreInteractions(listener);
  }
Example #2
0
 @Override
 @JsonValue
 public String toString() {
   switch (this) {
     case READ_WRITE:
       return ALLOW_ALL;
     case READ_ONLY:
       return GET.name();
     case WRITE_ONLY:
       return "w";
     default:
       return this.name();
   }
 }
  @Override
  public Response serve(final Request req) {

    if (log.isDebugEnabled()) {
      log.debug("uri=" + req.uri);
      log.debug("method=" + req.method);
      log.debug("headers=" + req.headers);
      log.debug("params=" + req.params);
    } else if (log.isInfoEnabled()) log.info(req.method + " '" + req.uri + "' ");

    try {

      if (GET.equalsIgnoreCase(req.method)) {

        return doGet(req);

      } else if (POST.equalsIgnoreCase(req.method)) {

        return doPost(req);

      } else if (PUT.equalsIgnoreCase(req.method)) {

        return doPut(req);

      } else if (DELETE.equalsIgnoreCase(req.method)) {

        return doDelete(req);

      } else {

        return new Response(HTTP_METHOD_NOT_ALLOWED, MIME_TEXT_PLAIN, "" + req.method);
      }

    } catch (Throwable e) {

      log.error(e.getMessage(), e);

      final StringWriter w = new StringWriter();

      e.printStackTrace(new PrintWriter(w));

      /*
       * Note: if you send an HTTP_INTERNALERROR (500) the browser won't
       * display the response body so you have to send an Ok with the text
       * of the error message....
       */

      return new Response(HTTP_OK, MIME_TEXT_PLAIN, w.toString());
    }
  }
 HttpServerHandler(
     LayoutService layoutService,
     Map<Pattern, HttpService> httpServices,
     HttpSessionManager httpSessionManager,
     List<Object> jsonServices) {
   this.layoutService = layoutService;
   this.httpServices = ImmutableMap.copyOf(httpServices);
   this.httpSessionManager = httpSessionManager;
   List<JsonServiceMapping> jsonServiceMappings = Lists.newArrayList();
   for (Object jsonService : jsonServices) {
     for (Method method : jsonService.getClass().getDeclaredMethods()) {
       GET annotationGET = method.getAnnotation(GET.class);
       if (annotationGET != null) {
         jsonServiceMappings.add(
             ImmutableJsonServiceMapping.builder()
                 .httpMethod(HttpMethod.GET)
                 .path(annotationGET.value())
                 .service(jsonService)
                 .methodName(method.getName())
                 .build());
       }
       POST annotationPOST = method.getAnnotation(POST.class);
       if (annotationPOST != null) {
         jsonServiceMappings.add(
             ImmutableJsonServiceMapping.builder()
                 .httpMethod(HttpMethod.POST)
                 .path(annotationPOST.value())
                 .service(jsonService)
                 .methodName(method.getName())
                 .build());
       }
     }
   }
   this.jsonServiceMappings = ImmutableList.copyOf(jsonServiceMappings);
   allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
 }
  /**
   * Handles a operation request via HTTP.
   *
   * @param http The HttpExchange object that allows access to the request and response.
   * @throws IOException if an error occurs while attempting to process the request.
   */
  private void processRequest(final HttpExchange http) throws IOException {
    final URI request = http.getRequestURI();
    final String requestMethod = http.getRequestMethod();

    boolean isGet = GET.equals(requestMethod);
    if (!isGet && !POST.equals(requestMethod)) {
      http.sendResponseHeaders(METHOD_NOT_ALLOWED, -1);

      return;
    }

    ModelNode dmr;
    ModelNode response;
    int status = OK;

    Headers requestHeaders = http.getRequestHeaders();
    boolean encode =
        APPLICATION_DMR_ENCODED.equals(requestHeaders.getFirst(ACCEPT))
            || APPLICATION_DMR_ENCODED.equals(requestHeaders.getFirst(CONTENT_TYPE));

    try {
      dmr = isGet ? convertGetRequest(request) : convertPostRequest(http.getRequestBody(), encode);
    } catch (IllegalArgumentException iae) {
      ROOT_LOGGER.debugf("Unable to construct ModelNode '%s'", iae.getMessage());
      http.sendResponseHeaders(INTERNAL_SERVER_ERROR, -1);

      return;
    }

    try {
      response = modelController.execute(new OperationBuilder(dmr).build());
    } catch (Throwable t) {
      ROOT_LOGGER.modelRequestError(t);
      http.sendResponseHeaders(INTERNAL_SERVER_ERROR, -1);

      return;
    }

    if (response.hasDefined(OUTCOME) && FAILED.equals(response.get(OUTCOME).asString())) {
      status = INTERNAL_SERVER_ERROR;
    }

    boolean pretty = dmr.hasDefined("json.pretty") && dmr.get("json.pretty").asBoolean();
    writeResponse(http, isGet, pretty, response, status, encode);
  }
 private String mediaTypeOf(final String httpMethod, final HttpHeaders headers) {
   if (GET.equals(httpMethod)) {
     return headers
         .getAcceptableMediaTypes()
         .stream()
         .map(this::mediaType)
         .filter(mt -> mt.startsWith(MEDIA_TYPE_PREFIX))
         .findFirst()
         .orElseThrow(
             () ->
                 new BadRequestException(
                     format(
                         "No matching action for accept media types: %s",
                         headers.getAcceptableMediaTypes())));
   } else {
     return mediaType(headers.getMediaType());
   }
 }
 public TextCommandServiceImpl(Node node) {
   this.node = node;
   this.hazelcast = node.factory;
   this.logger = node.getLogger(this.getClass().getName());
   this.parallelExecutor = this.node.executorManager.newParallelExecutor(40);
   textCommandProcessors[GET.getValue()] = new GetCommandProcessor(this, true);
   textCommandProcessors[PARTIAL_GET.getValue()] = new GetCommandProcessor(this, false);
   textCommandProcessors[SET.getValue()] = new SetCommandProcessor(this);
   textCommandProcessors[ADD.getValue()] = new SetCommandProcessor(this);
   textCommandProcessors[REPLACE.getValue()] = new SetCommandProcessor(this);
   textCommandProcessors[GET_END.getValue()] = new NoOpCommandProcessor(this);
   textCommandProcessors[DELETE.getValue()] = new DeleteCommandProcessor(this);
   textCommandProcessors[QUIT.getValue()] = new SimpleCommandProcessor(this);
   textCommandProcessors[STATS.getValue()] = new StatsCommandProcessor(this);
   textCommandProcessors[UNKNOWN.getValue()] = new ErrorCommandProcessor(this);
   textCommandProcessors[ERROR_CLIENT.getValue()] = new ErrorCommandProcessor(this);
   textCommandProcessors[ERROR_SERVER.getValue()] = new ErrorCommandProcessor(this);
   textCommandProcessors[HTTP_GET.getValue()] = new HttpGetCommandProcessor(this);
   textCommandProcessors[HTTP_POST.getValue()] = new HttpPostCommandProcessor(this);
   textCommandProcessors[HTTP_PUT.getValue()] = new HttpPostCommandProcessor(this);
   textCommandProcessors[HTTP_DELETE.getValue()] = new HttpDeleteCommandProcessor(this);
   textCommandProcessors[NO_OP.getValue()] = new NoOpCommandProcessor(this);
 }