Exemplo n.º 1
0
  @Test
  public void testHandlesInvalidAuthentication() throws IOException {
    String message =
        "GET /logs HTTP/1.1\n"
            + "Authorization: Basic YWRtaW46aHVudGVyMh==\r\n\r\n"; // bad_credentials (terminal h
                                                                   // instead of g)

    BufferedReader bufferedReader = new BufferedReader(new StringReader(message));
    HashMap state = new HashMap();
    RequestHandler requestHandler = new RequestHandler(bufferedReader, state);

    HashMap response = requestHandler.respondToRequest();

    Object header = response.get("message");
    Object credentials = response.get("Authorization");

    assertEquals("HTTP/1.1 401\r\n\r\nAuthentication required", new String((byte[]) header));
    assertEquals(
        "Basic YWRtaW46aHVudGVyMh==", credentials); // bad_credentials (terminal h instead of g)

    HashMap returnedState = (HashMap) response.get("state");
    String requests = (String) returnedState.get("requests");

    assert (requests != null);
  }
Exemplo n.º 2
0
 @Test
 public void testAddSpacesAroundEqualsSigns() {
   BufferedReader bufferedReader = new BufferedReader(new StringReader(""));
   HashMap state = new HashMap();
   RequestHandler requestHandler = new RequestHandler(bufferedReader, state);
   String body = "data=cosby";
   assertEquals("data = cosby", requestHandler.addSpacesAroundEqualsSigns(body));
 }
Exemplo n.º 3
0
  @Test
  public void testReadBytesFromBufferedReader() throws IOException {
    String request = "This is 16 bytes";
    BufferedReader bufferedReader = new BufferedReader(new StringReader(request));
    HashMap state = new HashMap();
    RequestHandler requestHandler = new RequestHandler(bufferedReader, state);

    assertEquals("This is 16 bytes", requestHandler.readBody(16));
  }
Exemplo n.º 4
0
  @Test
  public void testSplitRequestByLine() {
    String request = "GET / HTTP/1.1\n" + "Host: localhost:5000\n" + "Connection: keep-alive\n";
    BufferedReader bufferedReader = new BufferedReader(new StringReader(request));
    HashMap state = new HashMap();
    RequestHandler requestHandler = new RequestHandler(bufferedReader, state);
    List<String> parsedMessageHead = requestHandler.splitRequestByLine(request);

    assertEquals("GET / HTTP/1.1", parsedMessageHead.get(0));
    assertEquals("Host: localhost:5000", parsedMessageHead.get(1));
    assertEquals("Connection: keep-alive", parsedMessageHead.get(2));
  }
Exemplo n.º 5
0
  @Test
  public void testRespondsCorrectlyToQueryString() throws IOException {
    String request = "GET /parameters?variable_1=Operators%20%3C HTTP/1.1\r\n\r\n";
    HashMap state = null;

    BufferedReader bufferedReader = new BufferedReader(new StringReader(request));
    RequestHandler requestHandler = new RequestHandler(bufferedReader, state);

    requestHandler.respondToRequest();

    assertEquals("variable_1 = Operators <", new String(requestHandler.getBody()));
  }
 public void execute(
     final Params params,
     final RequestHandler.OnErrorListener listener,
     final Map<String, Object> requestMap,
     final Map<String, Object> paramMap) {
   synchronized (handlers) {
     if (position < handlers.length) {
       final RequestHandler handler = handlers[position];
       position++;
       handler.execute(params, listener, requestMap, paramMap, this);
     }
   }
 }
Exemplo n.º 7
0
  @Test
  public void testMapMultipleFields() {
    String request = "Host: localhost:5000\n" + "Connection: keep-alive\n";
    BufferedReader bufferedReader = new BufferedReader(new StringReader(request));
    HashMap state = new HashMap();
    RequestHandler requestHandler = new RequestHandler(bufferedReader, state);
    ArrayList<String> splitRequest = requestHandler.splitRequestByLine(request);
    Map testMap = new HashMap();
    testMap.put("Host", "localhost:5000");
    testMap.put("Connection", "keep-alive");
    requestHandler.mapFields(splitRequest);

    assertEquals(testMap, requestHandler.getHeaderFields());
  }
Exemplo n.º 8
0
  @Test
  public void testGetsStringRequestFromBufferedReader() throws IOException {
    String request =
        "GET / HTTP/1.1\n" + "Host: localhost:5000\n" + "Accept-Language: en-US,en;q=0.8\r\n\r\n";

    BufferedReader bufferedReader = new BufferedReader(new StringReader(request));
    HashMap state = new HashMap();
    RequestHandler requestHandler = new RequestHandler(bufferedReader, state);
    requestHandler.readHead();

    assertEquals(
        ("GET / HTTP/1.1\n" + "Host: localhost:5000\n" + "Accept-Language: en-US,en;q=0.8\n"),
        requestHandler.getHead());
  }
  /**
   * *********************************************************
   *
   * <p>Sending message to all players in the send list
   *
   * @return - success or not
   */
  public boolean send() throws DeliveryException {

    if (amount == 0) {
      System.out.println("No amount given");
      return false;
    }

    System.out.println("Preparing to give " + amount + " coins away");

    if (recipient == null) {
      System.out.println("No recipient given");
      return false;
    }

    if (overrideUserId != null) {

      // Use dummy override to send out ONE controlled message for the first
      recipient = overrideUserId;
    }

    // System.out.println("Sending to: " + recipient);
    RequestHandler requestHandler = new RequestHandler(coinService);

    try {

      String response =
          requestHandler.executeGet(
              "auth=c7849722a97707d96ceb356d2417a4bf"
                  + "&coins="
                  + amount
                  + "&playerId="
                  + recipient);

      if (response != null) {
        System.out.println("   -> Got Response: " + response);
        return (response.indexOf("ok") >= 0);

      } else {

        System.out.println("   -> No Response");
        return false;
      }

    } catch (DeliveryException e) {

      System.out.println("   -> Got response " + e.getHttpCode());
      return false;
    }
  }
Exemplo n.º 10
0
 @Test
 public void testSplitBodyFromHead() throws UnsupportedEncodingException {
   String request =
       "GET / HTTP/1.1\n"
           + "Host: localhost:5000\n"
           + "Accept-Language: en-US,en;q=0.8\r\n\r\n"
           + "data=cosby";
   BufferedReader bufferedReader = new BufferedReader(new StringReader(request));
   HashMap state = new HashMap();
   RequestHandler requestHandler = new RequestHandler(bufferedReader, state);
   requestHandler.parseRequest(request);
   assertEquals(
       "GET / HTTP/1.1\n" + "Host: localhost:5000\n" + "Accept-Language: en-US,en;q=0.8",
       requestHandler.getHead());
 }
Exemplo n.º 11
0
 @Override
 public FutureResult<QueryResult> queryAsync(
     final Context context, final QueryRequest request, final QueryResultHandler handler) {
   final FutureQueryResultHandler future = new FutureQueryResultHandler(handler);
   requestHandler.handleQuery(getServerContext(context), request, future);
   return future;
 }
Exemplo n.º 12
0
  public static void main(String[] args) {
    String url = null;
    try {
      url =
          "http://127.0.0.1:4332/query/"
              + URLEncoder.encode("\"president lobby\"", Charset.forName("UTF-8").name());
    } catch (UnsupportedEncodingException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
      System.out.println(RequestHandler.getResponse(RequestHandler.buildRequest(url)));
    } catch (Exception ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Exemplo n.º 13
0
  /**
   * User wants to login into eFaps. The user name and password is checked. User name is stored in
   * session variable {@link SecurityFilter#SESSIONPARAM_LOGIN_NAME}. After login a redirect to the
   * "common/Main.jsf" is made.<br>
   * The post parameter names are {@link #PARAM_USERNAME} and {@link #PARAM_PASSWORD}.
   *
   * @param _req request variable
   * @param _res response variable
   * @see #checkLogin
   */
  protected void doGet(final HttpServletRequest _req, final HttpServletResponse _res)
      throws ServletException, IOException {
    PrintWriter out = _res.getWriter();

    String name = _req.getParameter(PARAM_USERNAME);
    String passwd = _req.getParameter(PARAM_PASSWORD);

    if (checkLogin(name, passwd)) {
      HttpSession session = _req.getSession(true);
      session.setAttribute(SecurityFilter.SESSIONPARAM_LOGIN_NAME, name);

      _res.setContentType("text/html");

      String newUrl =
          (String) _req.getSession().getAttribute(SecurityFilter.SESSIONPARAM_LOGIN_FORWARD);
      if (newUrl == null) {
        newUrl = RequestHandler.replaceMacrosInUrl(this.forwardURL);
      } else {
        _req.getSession().removeAttribute(SecurityFilter.SESSIONPARAM_LOGIN_FORWARD);
      }
      _res.sendRedirect(newUrl);
    } else {
      doSendLoginFrameNotCorrect(_req, _res);
    }
  }
Exemplo n.º 14
0
 @Override
 public FutureResult<Resource> updateAsync(
     final Context context, final UpdateRequest request, final ResultHandler<Resource> handler) {
   final FutureResultHandler<Resource> future = new FutureResultHandler<Resource>(handler);
   requestHandler.handleUpdate(getServerContext(context), request, future);
   return future;
 }
Exemplo n.º 15
0
  @Test
  public void testPutsBodyIntoHashMap() throws IOException {
    String message =
        "POST /form HTTP/1.1\n" + "Host: localhost:5000\n" + "Content-Length: 5\r\n\r\n" + "hello";

    BufferedReader bufferedReader = new BufferedReader(new StringReader(message));
    HashMap state = new HashMap();
    RequestHandler requestHandler = new RequestHandler(bufferedReader, state);

    HashMap response = requestHandler.respondToRequest();

    HashMap stateObject = (HashMap) response.get("state");
    byte[] nestedBody = (byte[]) stateObject.get("state");

    assertArrayEquals("hello".getBytes(), nestedBody);
  }
Exemplo n.º 16
0
 private void executeRequestResponseCycle() throws Exception {
   Object request = inStream.readObject();
   logger.debug("Client Request - " + request);
   Object response = requestHandler.handleRequest(request);
   logger.debug("Response - " + response);
   outStream.writeObject(response);
 }
Exemplo n.º 17
0
  @Test
  public void testHandleRequest() throws IOException {
    String request =
        "GET / HTTP/1.1\n" + "Host: localhost:5000\n" + "Accept-Language: en-US,en;q=0.8\r\n\r\n";
    BufferedReader bufferedReader = new BufferedReader(new StringReader(request));
    HashMap state = new HashMap();
    RequestHandler requestHandler = new RequestHandler(bufferedReader, state);

    HashMap response = requestHandler.respondToRequest();
    byte[] byteResponse = (byte[]) response.get("message");

    assertArrayEquals(
        "HTTP/1.1 200 OK\r\n\r\n<p><a href='ttt'>Play Tic Tac Toe</a></p><a href='file1'>file1</a><p><a href='file2'>file2</a></p><a href='image.gif'>image.gif</a><a href='image.jpeg'>image.jpeg</a><a href='image.png'>image.png</a><a href='text-file.txt'>text-file.txt</a><a href='partial_content.txt'>partial_content.txt</a>"
            .getBytes(),
        byteResponse);
  }
Exemplo n.º 18
0
  @Test
  public void testPutsResponseHeaderIntoHashMap() throws IOException {
    String message = "GET / HTTP/1.1\n" + "Host: localhost:5000\r\n\r\n";

    BufferedReader bufferedReader = new BufferedReader(new StringReader(message));
    HashMap state = new HashMap();
    RequestHandler requestHandler = new RequestHandler(bufferedReader, state);

    HashMap response = requestHandler.respondToRequest();

    Object header = response.get("message");

    assertEquals(
        "HTTP/1.1 200 OK\r\n\r\n<p><a href='ttt'>Play Tic Tac Toe</a></p><a href='file1'>file1</a><p><a href='file2'>file2</a></p><a href='image.gif'>image.gif</a><a href='image.jpeg'>image.jpeg</a><a href='image.png'>image.png</a><a href='text-file.txt'>text-file.txt</a><a href='partial_content.txt'>partial_content.txt</a>",
        (new String((byte[]) header)));
  }
Exemplo n.º 19
0
  @Test
  public void testReadMessageHead() throws UnsupportedEncodingException {
    String request = "GET / HTTP/1.1";
    BufferedReader bufferedReader = new BufferedReader(new StringReader(request));
    HashMap state = new HashMap();
    RequestHandler requestHandler = new RequestHandler(bufferedReader, state);
    requestHandler.parseHead(request);

    assertEquals("GET", requestHandler.getHttpMethod());

    BufferedReader newBufferedReader = new BufferedReader(new StringReader(request));
    requestHandler = new RequestHandler(newBufferedReader, state);
    request = "POST / HTTP/1.1";
    requestHandler.parseHead(request);

    assertEquals("POST", requestHandler.getHttpMethod());
  }
 @Override
 public void handleRequest(Request req) {
   if (req.getRequestType().equals(RequestType.COLLECT_TAX)) {
     printHandling(req);
   } else {
     super.handleRequest(req);
   }
 }
Exemplo n.º 21
0
  @Test
  public void testHandlesValidAuthentication() throws IOException {
    String message = "GET /logs HTTP/1.1\n" + "Authorization: Basic YWRtaW46aHVudGVyMg==\r\n\r\n";

    BufferedReader bufferedReader = new BufferedReader(new StringReader(message));
    HashMap state = new HashMap();
    RequestHandler requestHandler = new RequestHandler(bufferedReader, state);

    HashMap response = requestHandler.respondToRequest();

    byte[] header = (byte[]) response.get("message");
    byte[] responseFromValidAuthentication =
        "HTTP/1.1 200 OK\r\n\r\nGET /log HTTP/1.1\nPUT /these HTTP/1.1\nHEAD /requests HTTP/1.1"
            .getBytes();

    assertEquals(new String(responseFromValidAuthentication), new String(header));
  }
Exemplo n.º 22
0
  public void blockingForward(HttpRequest request) {
    if (request == null) throw new IllegalArgumentException("Cannot forward a empty request.");

    if (Args.isEmpty(request.getURI()))
      throw new IllegalArgumentException("The remote server is unreachable.");

    if (request.getHttpHeader().size() == 0) {
      request.attachHeaders(new BasicHttpHeader());
    }
    // Set up the global settings default
    HttpConfig config = request.getHttpConfig();
    if (config == null) config = this.httpConfig;

    requestHandler.init(request, config);
    HttpResponse httpResponse = requestHandler.makeRequest();

    triggerResponseHandler(httpResponse);
  }
Exemplo n.º 23
0
 @Override
 public FutureResult<JsonValue> actionAsync(
     final Context context,
     final ActionRequest request,
     final ResultHandler<JsonValue> handler) {
   final FutureResultHandler<JsonValue> future = new FutureResultHandler<JsonValue>(handler);
   requestHandler.handleAction(getServerContext(context), request, future);
   return future;
 }
Exemplo n.º 24
0
 void respond(ResourcePath resourcePath, HttpServletRequest req, HttpServletResponse resp)
     throws IOException {
   RequestEnvironment<T, R, V> environment =
       requestEnvironmentFactory.createRequestEnvironment();
   try {
     R router = environment.createRouter();
     T resource = router.parseResource(resourcePath);
     V views = environment.createViews(router);
     Layout layout = views.createLayout(resource);
     WebEnvironment web = new WebEnvironment(new WebRequest(req), new WebResponse(resp, layout));
     RequestHandler<T> handler = environment.createRequestHandler(views, web);
     handler.processRequest(resource);
   } catch (ResourceParserException ex) {
     resp.sendError(404, ex.getMessage());
   } finally {
     environment.close();
   }
 }
Exemplo n.º 25
0
 public HttpRouter() {
   dispatcher = new DispatcherImpl(this);
   // Route service to forward the package in thread pool
   routerService = new RouterService(this);
   routerService.register(dispatcher);
   // Global setting
   httpConfig = new HttpConfig();
   // Initialize request handler
   requestHandler = RequestHandler.getInstance();
 }
Exemplo n.º 26
0
 public Deferred<HttpResponse> process(ChannelHandlerContext context, HttpRequest request) {
   HttpResponse response =
       new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK);
   response.setHeader("content-type", "text/html");
   response.setContent(
       ChannelBuffers.copiedBuffer("Accepted ShutDown Request", Charset.defaultCharset()));
   Deferred<HttpResponse> deferred = new Deferred<HttpResponse>();
   deferred.callback(response);
   shutdown();
   super.doShutdown(context.getChannel());
   return deferred;
 }
    /** {@inheritDoc} */
    @Override
    public <R extends ExtendedResult> void handleExtendedRequest(
        final Integer messageID,
        final ExtendedRequest<R> request,
        final IntermediateResponseHandler intermediateResponseHandler,
        final LdapResultHandler<R> resultHandler) {
      if (request.getOID().equals(CancelExtendedRequest.OID)) {
        // Decode the request as a cancel request.
        CancelExtendedRequest cancelRequest;
        try {
          cancelRequest =
              CancelExtendedRequest.DECODER.decodeExtendedRequest(request, new DecodeOptions());
        } catch (final DecodeException e) {
          // Couldn't decode a cancel request.
          resultHandler.handleException(
              newLdapException(ResultCode.PROTOCOL_ERROR, e.getLocalizedMessage()));
          return;
        }

        /*
         * Register the request in the pending requests table. Even
         * though this request cannot be cancelled, it is important to
         * do this in order to monitor the number of pending operations.
         */
        final RequestContextImpl<R, LdapResultHandler<R>> requestContext =
            new RequestContextImpl<>(this, resultHandler, messageID, false);
        if (addPendingRequest(requestContext)) {
          // Find and cancel the request.
          final RequestContextImpl<?, ?> cancelledRequest =
              getPendingRequest(cancelRequest.getRequestID());
          if (cancelledRequest != null) {
            final LocalizableMessage cancelReason = INFO_CANCELED_BY_CANCEL_REQUEST.get(messageID);
            cancelledRequest.cancel(cancelReason, request, requestContext, true);
          } else {
            /*
             * Couldn't find the request. Invoke on context in order
             * to remove pending request.
             */
            requestContext.handleException(newLdapException(ResultCode.NO_SUCH_OPERATION));
          }
        }
      } else {
        // StartTLS requests cannot be cancelled.
        boolean isCancelSupported = !request.getOID().equals(StartTLSExtendedRequest.OID);
        final RequestContextImpl<R, LdapResultHandler<R>> requestContext =
            new RequestContextImpl<>(this, resultHandler, messageID, isCancelSupported);

        if (addPendingRequest(requestContext)) {
          requestHandler.handleExtendedRequest(
              requestContext, request, intermediateResponseHandler, requestContext);
        }
      }
    }
 /** {@inheritDoc} */
 @Override
 public void handleModifyDN(
     final Integer messageID,
     final ModifyDNRequest request,
     final IntermediateResponseHandler intermediateResponseHandler,
     final LdapResultHandler<Result> resultHandler) {
   final RequestContextImpl<Result, LdapResultHandler<Result>> requestContext =
       new RequestContextImpl<>(this, resultHandler, messageID, true);
   if (addPendingRequest(requestContext)) {
     requestHandler.handleModifyDN(
         requestContext, request, intermediateResponseHandler, requestContext);
   }
 }
 /** {@inheritDoc} */
 @Override
 public void handleSearch(
     final Integer messageID,
     final SearchRequest request,
     final IntermediateResponseHandler intermediateResponseHandler,
     final SearchResultHandler entryHandler,
     final LdapResultHandler<Result> resultHandler) {
   final SearchRequestContextImpl requestContext =
       new SearchRequestContextImpl(this, entryHandler, resultHandler, messageID, true);
   if (addPendingRequest(requestContext)) {
     requestHandler.handleSearch(
         requestContext, request, intermediateResponseHandler, entryHandler, requestContext);
   }
 }
 /** {@inheritDoc} */
 @Override
 public void handleBind(
     final Integer messageID,
     final int version,
     final BindRequest request,
     final IntermediateResponseHandler intermediateResponseHandler,
     final LdapResultHandler<BindResult> resultHandler) {
   final RequestContextImpl<BindResult, LdapResultHandler<BindResult>> requestContext =
       new RequestContextImpl<>(this, resultHandler, messageID, false);
   if (addPendingRequest(requestContext)) {
     requestHandler.handleBind(
         requestContext, version, request, intermediateResponseHandler, requestContext);
   }
 }