Java Code Examples for io.netty.handler.codec.http.HttpRequest

The following are top voted examples for showing how to use io.netty.handler.codec.http.HttpRequest. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: redant   File: DataStorer.java   Source Code and License 7 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if(msg instanceof HttpRequest){
        HttpRequest request = (HttpRequest) msg;
        if(!request.uri().equals(CommonConstants.FAVICON_ICO)){
            // 将request和context存储到ThreadLocal中去,便于后期在其他地方获取并使用
            DataHolder.store(DataHolder.HolderType.REQUEST,request);
            DataHolder.store(DataHolder.HolderType.CONTEXT,ctx);
        }
    }
    /**
     * 提交给下一个ChannelHandler去处理
     * 并且不需要调用ReferenceCountUtil.release(msg);来释放引用计数
     */
    ctx.fireChannelRead(msg);
}
 
Example 2
Project: bromium   File: RequestToPageLoadingEventConverterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void ifNoPageLoadingActions_OptionalEmptyIsReturned() throws MalformedURLException, UnsupportedEncodingException {
    ActionsFilter actionsFilter = createMocks(false);
    when(actionsFilter.filter(PAGE_LOADING)).thenReturn(new ArrayList<>());

    HttpRequest httpRequest = mock(HttpRequest.class);
    when(httpRequest.getUri()).thenReturn(EXPECTED_URL);
    
    RequestToPageLoadingEventConverter requestToPageLoadingEventConverter =
            new RequestToPageLoadingEventConverter(BASE_URL, actionsFilter);

    Optional<Map<String, String>> expected = Optional.empty();
    Optional<Map<String, String>> actual = requestToPageLoadingEventConverter.convert(httpRequest);

    assertEquals(expected, actual);
}
 
Example 3
Project: tasfe-framework   File: HttpSessionInterceptor.java   Source Code and License 6 votes vote down vote up
@Override
public void onRequestReceived(ChannelHandlerContext ctx, HttpRequest request) {

    HttpSessionThreadLocal.unset();

    Collection<Cookie> cookies = Utils.getCookies(HttpSessionImpl.SESSION_ID_KEY, request);
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            String jsessionId = cookie.value();
            HttpSession s = HttpSessionThreadLocal.getSessionStore().findSession(jsessionId);
            if (s != null) {
                HttpSessionThreadLocal.set(s);
                this.sessionRequestedByCookie = true;
                break;
            }
        }
    }
}
 
Example 4
Project: CloudNet   File: WebsiteDocumentation.java   Source Code and License 6 votes vote down vote up
@Override
public FullHttpResponse get(ChannelHandlerContext channelHandlerContext, QueryDecoder queryDecoder, PathProvider path, HttpRequest httpRequest) throws Exception
{
    CloudNet.getLogger().debug("HTTP Request from " + channelHandlerContext.channel().remoteAddress());

    StringBuilder stringBuilder = new StringBuilder();

    try (InputStream inputStream = WebsiteDocumentation.class.getClassLoader().getResourceAsStream("files/api-doc.txt");
         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)))
    {
        String input;
        while ((input = bufferedReader.readLine()) != null)
        {
            stringBuilder.append(input).append(System.lineSeparator());
        }
    }

    String output = stringBuilder.substring(0);
    ByteBuf byteBuf = Unpooled.wrappedBuffer(output.getBytes(StandardCharsets.UTF_8));
    FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), HttpResponseStatus.OK, byteBuf);
    fullHttpResponse.headers().set("Content-Type", "text/plain");
    return fullHttpResponse;
}
 
Example 5
Project: bromium   File: RequestToPageLoadingEventConverterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void ifEventWithSuppliedValueMatchesTheUriThenEventIsReturned() throws MalformedURLException, UnsupportedEncodingException {
    ActionsFilter actionsFilter = createMocks(false);

    HttpRequest httpRequest = mock(HttpRequest.class);
    when(httpRequest.getUri()).thenReturn(EXPECTED_URL);

    RequestToPageLoadingEventConverter requestToPageLoadingEventConverter =
            new RequestToPageLoadingEventConverter(BASE_URL, actionsFilter);

    Map<String, String> expected = ImmutableMap.of(EVENT, EXAMPLE_EVENT_NAME);
    Optional<Map<String, String>> actual = requestToPageLoadingEventConverter.convert(httpRequest);

    assertTrue(actual.isPresent());
    assertEquals(expected, actual.get());
}
 
Example 6
Project: hadoop   File: WebHdfsHandler.java   Source Code and License 6 votes vote down vote up
public void handle(ChannelHandlerContext ctx, HttpRequest req)
  throws IOException, URISyntaxException {
  String op = params.op();
  HttpMethod method = req.getMethod();
  if (PutOpParam.Op.CREATE.name().equalsIgnoreCase(op)
    && method == PUT) {
    onCreate(ctx);
  } else if (PostOpParam.Op.APPEND.name().equalsIgnoreCase(op)
    && method == POST) {
    onAppend(ctx);
  } else if (GetOpParam.Op.OPEN.name().equalsIgnoreCase(op)
    && method == GET) {
    onOpen(ctx);
  } else if(GetOpParam.Op.GETFILECHECKSUM.name().equalsIgnoreCase(op)
    && method == GET) {
    onGetFileChecksum(ctx);
  } else {
    throw new IllegalArgumentException("Invalid operation " + op);
  }
}
 
Example 7
Project: bromium   File: RecordRequestFilter.java   Source Code and License 6 votes vote down vote up
@Override
public HttpResponse filterRequest(HttpRequest httpRequest, HttpMessageContents httpMessageContents, HttpMessageInfo httpMessageInfo) {
    for (EventDetector eventDetector: eventDetectors) {
        if (eventDetector.canDetectPredicate().test(httpRequest)) {
            try {
                Optional<Map<String, String>> optionalEvent = eventDetector.getConverter().convert(httpRequest);

                if (optionalEvent.isPresent()) {
                    Map<String, String> event = optionalEvent.get();
                    recordingState.storeTestCaseStep(event);
                    logger.info("Recorded event {}", event);
                }

            } catch (UnsupportedEncodingException | MalformedURLException e) {
                logger.error("Error while trying to convert test case step", e);
            }
        }
    }

    return null;
}
 
Example 8
Project: hadoop   File: WebHdfsHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void channelRead0(final ChannelHandlerContext ctx,
                         final HttpRequest req) throws Exception {
  Preconditions.checkArgument(req.getUri().startsWith(WEBHDFS_PREFIX));
  QueryStringDecoder queryString = new QueryStringDecoder(req.getUri());
  params = new ParameterParser(queryString, conf);
  DataNodeUGIProvider ugiProvider = new DataNodeUGIProvider(params);
  ugi = ugiProvider.ugi();
  path = params.path();

  injectToken();
  ugi.doAs(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      handle(ctx, req);
      return null;
    }
  });
}
 
Example 9
Project: bromium   File: DefaultModule.java   Source Code and License 6 votes vote down vote up
@CheckedProvides(IOProvider.class)
public ResponseFilter getResponseFilter(@Named(COMMAND) String command,
                                        ReplayingState replayingState,
                                        @Named(SHOULD_INJECT_JS_PREDICATE) Predicate<HttpRequest> httpRequestPredicate,
                                        @Named(RECORDING_JAVASCRIPT_CODE) IOProvider<String>
                                                    recordingJavascriptCodeProvider,
                                        @Named(REPLAYING_JAVASCRIPT_CODE) IOProvider<String>
                                                    replayingJavascriptCodeProvider) throws IOException {
    switch (command) {
        case RECORD:
            return new RecordResponseFilter(recordingJavascriptCodeProvider.get(), httpRequestPredicate);
        case REPLAY:
            return new ReplayResponseFilter(replayingJavascriptCodeProvider.get(), replayingState, httpRequestPredicate);
        default:
            throw new NoSuchCommandException();
    }
}
 
Example 10
Project: bromium   File: RecordRequestFilterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void doesNotAddToStateIfConverterReturnsEmpty() throws MalformedURLException, UnsupportedEncodingException {
    HttpRequest httpRequest = mock(HttpRequest.class);
    Map<String, String> event = getEvent();
    when(httpRequest.getUri()).thenReturn(SUBMIT_EVENT_URL + "?event=mockEvent&text=mockText");
    Predicate<HttpRequest> httpRequestPredicate = mock(Predicate.class);
    when(httpRequestPredicate.test(httpRequest)).thenReturn(true);
    RecordingState recordingState = mock(RecordingState.class);
    HttpRequestToTestCaseStepConverter httpRequestToTestCaseStepConverter = mock(HttpRequestToTestCaseStepConverter.class);
    when(httpRequestToTestCaseStepConverter.convert(httpRequest)).thenReturn(Optional.empty());
    EventDetector eventDetector = mock(EventDetector.class);
    when(eventDetector.canDetectPredicate()).thenReturn(httpRequestPredicate);
    when(eventDetector.getConverter()).thenReturn(httpRequestToTestCaseStepConverter);
    List<EventDetector> eventDetectors = Arrays.asList(eventDetector);
    RecordRequestFilter requestFilter = new RecordRequestFilter(recordingState, eventDetectors);
    requestFilter.filterRequest(httpRequest, mock(HttpMessageContents.class), mock(HttpMessageInfo.class));

    verify(recordingState, never()).storeTestCaseStep(event);
}
 
Example 11
Project: bromium   File: RecordRequestFilterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void doesNotAddToQueueIfEncodingIsUnsupporte() throws MalformedURLException, UnsupportedEncodingException {
    HttpRequest httpRequest = mock(HttpRequest.class);
    when(httpRequest.getUri()).thenReturn("blabla" + SUBMIT_EVENT_URL);
    RecordingState recordingState = mock(RecordingState.class);
    Predicate<HttpRequest> httpRequestPredicate = mock(Predicate.class);
    when(httpRequestPredicate.test(httpRequest)).thenReturn(true);
    HttpRequestToTestCaseStepConverter httpRequestToTestCaseStepConverter = mock(HttpRequestToTestCaseStepConverter.class);
    when(httpRequestToTestCaseStepConverter.convert(httpRequest)).thenThrow(new UnsupportedEncodingException());
    EventDetector eventDetector = mock(EventDetector.class);
    when(eventDetector.canDetectPredicate()).thenReturn(httpRequestPredicate);
    when(eventDetector.getConverter()).thenReturn(httpRequestToTestCaseStepConverter);
    List<EventDetector> eventDetectors = Arrays.asList(eventDetector);
    RecordRequestFilter requestFilter = new RecordRequestFilter(recordingState, eventDetectors);
    requestFilter.filterRequest(httpRequest, mock(HttpMessageContents.class), mock(HttpMessageInfo.class));
    verify(recordingState, never()).storeTestCaseStep(anyMap());
}
 
Example 12
Project: elasticsearch_my   File: Netty4CorsHandler.java   Source Code and License 6 votes vote down vote up
public static void setCorsResponseHeaders(HttpRequest request, HttpResponse resp, Netty4CorsConfig config) {
    if (!config.isCorsSupportEnabled()) {
        return;
    }
    String originHeader = request.headers().get(HttpHeaderNames.ORIGIN);
    if (!Strings.isNullOrEmpty(originHeader)) {
        final String originHeaderVal;
        if (config.isAnyOriginSupported()) {
            originHeaderVal = ANY_ORIGIN;
        } else if (config.isOriginAllowed(originHeader) || isSameOrigin(originHeader, request.headers().get(HttpHeaderNames.HOST))) {
            originHeaderVal = originHeader;
        } else {
            originHeaderVal = null;
        }
        if (originHeaderVal != null) {
            resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderVal);
        }
    }
    if (config.isCredentialsAllowed()) {
        resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    }
}
 
Example 13
Project: teslog   File: HttpHelloWorldServerHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        boolean keepAlive = HttpUtil.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }
    }
}
 
Example 14
Project: mqttserver   File: HttpRequestHandler.java   Source Code and License 6 votes vote down vote up
private static void sendHttpResponse(ChannelHandlerContext ctx,
		HttpRequest req, FullHttpResponse res) {
	// Generate an error page if response getStatus code is not OK (200).
	if (res.getStatus().code() != 200) {
		ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
				CharsetUtil.UTF_8);
		res.content().writeBytes(buf);
		buf.release();
		setContentLength(res, res.content().readableBytes());
	}

	// Send the response and close the connection if necessary.
	ChannelFuture f = ctx.writeAndFlush(res);
	if (!isKeepAlive(req) || res.getStatus().code() != 200) {
		f.addListener(ChannelFutureListener.CLOSE);
	}
}
 
Example 15
Project: bromium   File: RecordRequestFilterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void doesNotAddRequestIfNotRequired() {
    HttpRequest httpRequest = mock(HttpRequest.class);
    when(httpRequest.getUri()).thenReturn("http://something/" + "?event=mockEvent&text=mockText");
    RecordingState recordingState = mock(RecordingState.class);
    Predicate<HttpRequest> httpRequestPredicate = mock(Predicate.class);
    when(httpRequestPredicate.test(httpRequest)).thenReturn(false);
    HttpRequestToTestCaseStepConverter httpRequestToTestCaseStepConverter = mock(HttpRequestToTestCaseStepConverter.class);
    EventDetector eventDetector = mock(EventDetector.class);
    when(eventDetector.canDetectPredicate()).thenReturn(httpRequestPredicate);
    when(eventDetector.getConverter()).thenReturn(httpRequestToTestCaseStepConverter);
    List<EventDetector> eventDetectors = Arrays.asList(eventDetector);
    RecordRequestFilter requestFilter = new RecordRequestFilter(recordingState, eventDetectors);
    requestFilter.filterRequest(httpRequest, mock(HttpMessageContents.class), mock(HttpMessageInfo.class));
    verify(recordingState, never()).storeTestCaseStep(anyMap());
}
 
Example 16
Project: util4j   File: NettyHttpClient.java   Source Code and License 6 votes vote down vote up
/**
 * 同步请求
 * @param host
 * @param port
 * @param request
 * @return 超时返回null
 */
public HttpResponse syncRequest(String host,int port,HttpRequest request)
{
	HttpResponse response=null;
	synchronized (request) {
		if(response==null)
		{
			HttpListener listener=new HttpListener(request);
			NettyClient client=new NettyClient(config,new InetSocketAddress(host, port),new HttpClientInitHandler(listener));
			client.start();
			response=listener.waitResponse();//阻塞等待结果
			client.stop();
		}
	}
	return response;
}
 
Example 17
Project: proxyee-down   File: HttpRequestInfo.java   Source Code and License 6 votes vote down vote up
public static HttpRequest adapter(HttpRequest httpRequest) {
  if (httpRequest instanceof DefaultHttpRequest) {
    HttpVer version;
    if (httpRequest.protocolVersion().minorVersion() == 0) {
      version = HttpVer.HTTP_1_0;
    } else {
      version = HttpVer.HTTP_1_1;
    }
    HttpHeadsInfo httpHeadsInfo = new HttpHeadsInfo();
    for (Entry<String, String> entry : httpRequest.headers()) {
      httpHeadsInfo.set(entry.getKey(), entry.getValue());
    }
    return new HttpRequestInfo(version, httpRequest.method().toString(), httpRequest.uri(),
        httpHeadsInfo, null);
  }
  return httpRequest;
}
 
Example 18
Project: bromium   File: GetHtmlFromCurrentHostPredicateTest.java   Source Code and License 5 votes vote down vote up
@Test
public void whenTheHostIsTheSameThenNotChangingURLRequest() throws URISyntaxException {
    URI uri = new URI("http://tenniskafe.com");
    HttpHeaders httpHeaders = mock(HttpHeaders.class);
    when(httpHeaders.get("Accept")).thenReturn("application/json");
    HttpRequest httpRequest = mock(HttpRequest.class);
    when(httpRequest.getUri()).thenReturn("http://tenniskafe.com/atp");
    when(httpRequest.headers()).thenReturn(httpHeaders);
    when(httpRequest.getMethod()).thenReturn(HttpMethod.GET);

    GetHtmlFromCurrentHostPredicate getHtmlFromCurrentHostPredicate = new GetHtmlFromCurrentHostPredicate(uri);
    assertFalse(getHtmlFromCurrentHostPredicate.test(httpRequest));
}
 
Example 19
Project: tasfe-framework   File: Utils.java   Source Code and License 5 votes vote down vote up
public static final Collection<Cookie> getCookies(String name, HttpRequest request) {
    String cookieString = request.headers().get(COOKIE);
    if (cookieString != null) {
        List<Cookie> foundCookie = new ArrayList<Cookie>();
        // 不验证name 和 value
        Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString);
        for (Cookie cookie : cookies) {
            if (cookie.name().equals(name))
                foundCookie.add(cookie);
        }

        return foundCookie;
    }
    return null;
}
 
Example 20
Project: util4j   File: NettyHttpClient.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
		NettyHttpClient client=new NettyHttpClient();
		long time=System.currentTimeMillis();
		HttpRequest request=new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/baidu?tn=monline_6_dg&ie=utf-8&wd=netty+http客户端");
		HttpResponse response=client.syncRequest("www.baidu.com", 80, request);
		System.out.println(System.currentTimeMillis()-time);
		System.out.println(response);
		FullHttpResponse rsp=(FullHttpResponse) response;
		System.out.println("content:"+rsp.content().toString(CharsetUtil.UTF_8));
//		new Scanner(System.in).nextLine();
	}
 
Example 21
Project: bromium   File: RequestToPageLoadingEventConverterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void ifActionIsNotExposedButTheUrlIsDifferentThenEmptyOptionalIsReturned() throws MalformedURLException, UnsupportedEncodingException {
    ActionsFilter actionsFilter = createMocks(false);

    HttpRequest httpRequest = mock(HttpRequest.class);
    when(httpRequest.getUri()).thenReturn(URL_THAT_IS_NOT_EQUAL_TO_EXPECTED);

    RequestToPageLoadingEventConverter requestToPageLoadingEventConverter =
            new RequestToPageLoadingEventConverter(BASE_URL, actionsFilter);

    Optional<Map<String, String>> expected = Optional.empty();
    Optional<Map<String, String>> actual = requestToPageLoadingEventConverter.convert(httpRequest);

    assertEquals(expected, actual);
}
 
Example 22
Project: bromium   File: UriContainsStringPredicateTest.java   Source Code and License 5 votes vote down vote up
@Test
public void ifDoesNotContainSubmitUrlThenEventIsNotSubmitted() {
    String url = "http://something.com";
    HttpRequest httpRequest = mock(HttpRequest.class);
    when(httpRequest.getUri()).thenReturn(url);
    UriContainsStringPredicate uriContainsStringPredicate = new UriContainsStringPredicate(SUBMIT_EVENT_URL);
    assertFalse(uriContainsStringPredicate.test(httpRequest));
}
 
Example 23
Project: redant   File: CookieManager.java   Source Code and License 5 votes vote down vote up
/**
 * 删除一个Cookie
 * @param name
 * @return
 */
@Deprecated
public static boolean deleteCookie(String name) {
    HttpRequest request = DataHolder.getHttpRequest();
    HttpResponse response = DataHolder.getHttpResponse();
    return CookieHelper.deleteCookie(request,response,name);
}
 
Example 24
Project: redant   File: CookieHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 设置所有的Cookie
 * @param request
 * @param response
 */
public static void setCookies(HttpRequest request,HttpResponse response){
    Set<Cookie> cookies = getCookies(request);
    if (!cookies.isEmpty()) {
        for (Cookie cookie : cookies) {
            setCookie(response,cookie);
        }
    }
}
 
Example 25
Project: redant   File: CookieHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 删除一个Cookie
 * @param request
 * @param response
 * @param name
 * @return
 */
public static boolean deleteCookie(HttpRequest request,HttpResponse response,String name) {
    Cookie cookie = getCookie(request,name);
    if(cookie!=null){
        cookie.setMaxAge(0);
        cookie.setPath("/");
        setCookie(response,cookie);
        return true;
    }
    return false;
}
 
Example 26
Project: redant   File: DefaultCookieRender.java   Source Code and License 5 votes vote down vote up
@Override
public boolean deleteCookie(String name) {
    if(response==null){
        response = response();
    }
    HttpRequest request = DataHolder.getHttpRequest();
    return CookieHelper.deleteCookie(request,response,name);
}
 
Example 27
Project: push-network-proxies   File: MockingFCMProxyServer.java   Source Code and License 5 votes vote down vote up
public HttpProxyServer start() {

        return DefaultHttpProxyServer.bootstrap()
            .withAddress(new InetSocketAddress(host, port))
            .withFiltersSource(new HttpFiltersSourceAdapter() {

                @Override
                public HttpFilters filterRequest(HttpRequest originalRequest) {

                    return new HttpFiltersAdapter(originalRequest) {

                        final String mockedAddress = mockServer + ":" + mockPort;

                        @Override
                        public HttpResponse clientToProxyRequest(HttpObject httpObject) {

                            final HttpRequest request = (HttpRequest) httpObject;

                            if (request.getUri().contains("google")) {
                                request.setUri(mockedAddress);
                            }

                            super.clientToProxyRequest(request);

                            return null;
                        }
                    };
                }
            }).start();
    }
 
Example 28
Project: mqttserver   File: HttpJsonpTransport.java   Source Code and License 5 votes vote down vote up
private static void sendFullHttpOKResponse(ChannelHandlerContext ctx,
		HttpRequest req, String result) {
	ByteBuf content = ctx.alloc().directBuffer()
			.writeBytes(result.getBytes());
	FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK,
			content);

	res.headers().set(CONTENT_TYPE, HEADER_CONTENT_TYPE);
	setContentLength(res, content.readableBytes());

	sendHttpResponse(ctx, req, res);
}
 
Example 29
Project: bromium   File: RecordThroughTheRecordRequestFilterIT.java   Source Code and License 5 votes vote down vote up
@Override
public void run(RecordingSimulatorModule recordingSimulatorModule) {
    RequestFilter recordRequestFilter = recordingSimulatorModule.getRecordRequestFilter();
    HttpMessageContents httpMessageContents = mock(HttpMessageContents.class);
    HttpMessageInfo httpMessageInfo = mock(HttpMessageInfo.class);

    for (Map<String, String> testCaseStep: expected) {
        String queryString = URLUtils.toQueryString(testCaseStep);
        HttpRequest httpRequest = mock(HttpRequest.class, RETURNS_DEEP_STUBS);
        when(httpRequest.getUri()).thenReturn(SUBMIT_EVENT_URL + queryString);
        when(httpRequest.getMethod()).thenReturn(HttpMethod.GET);
        when(httpRequest.headers().get(ACCEPT)).thenReturn(HTML);
        recordRequestFilter.filterRequest(httpRequest, httpMessageContents, httpMessageInfo);
    }
}
 
Example 30
Project: libcwfincore   File: GdaxExchangeSession.java   Source Code and License 5 votes vote down vote up
public void sendRequest(ChannelFuture channelFuture, HttpRequest request) throws GeneralSecurityException {
    if (channelFuture.isDone()) {
        sendRequest(channelFuture.channel(), request);
    } else {
        channelFuture.addListener(future -> sendRequest(channelFuture.channel(), request));
    }
}
 
Example 31
Project: bromium   File: GetHtmlFromCurrentHostPredicateTest.java   Source Code and License 5 votes vote down vote up
@Test
public void ifRequestIsNotGetThenItIsFalse() throws URISyntaxException {
    URI uri = new URI("http://tenniskafe.com");
    HttpHeaders httpHeaders = mock(HttpHeaders.class);
    when(httpHeaders.get("Accept")).thenReturn("application/html");
    HttpRequest httpRequest = mock(HttpRequest.class);
    when(httpRequest.getUri()).thenReturn("http://tenniskafe.com");
    when(httpRequest.headers()).thenReturn(httpHeaders);
    when(httpRequest.getMethod()).thenReturn(HttpMethod.POST);

    GetHtmlFromCurrentHostPredicate getHtmlFromCurrentHostPredicate = new GetHtmlFromCurrentHostPredicate(uri);
    assertFalse(getHtmlFromCurrentHostPredicate.test(httpRequest));
}
 
Example 32
Project: bromium   File: RequestToPageLoadingEventConverterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void exceptionIsThrownIfBaseUrlDoesNotMatch() throws MalformedURLException, UnsupportedEncodingException {
    ActionsFilter actionsFilter = createMocks(false);

    HttpRequest httpRequest = mock(HttpRequest.class);
    when(httpRequest.getUri()).thenReturn(WRONG_URL);

    RequestToPageLoadingEventConverter requestToPageLoadingEventConverter =
            new RequestToPageLoadingEventConverter(BASE_URL, actionsFilter);

    expectedException.expect(IllegalArgumentException.class);
    requestToPageLoadingEventConverter.convert(httpRequest);
}
 
Example 33
Project: bromium   File: GetHtmlFromCurrentHostPredicate.java   Source Code and License 5 votes vote down vote up
@Override
public boolean test(HttpRequest httpRequest) {
    boolean methodIsGet = httpRequest.getMethod().equals(HttpMethod.GET);
    boolean expectsHtmlContent = httpRequest.headers().get(ACCEPT).contains(Constants.HTML);
    boolean isFromCurrentBaseUrl = httpRequest.getUri().contains(baseURI.getHost());
    return expectsHtmlContent && isFromCurrentBaseUrl && methodIsGet;
}
 
Example 34
Project: aws-sdk-java-v2   File: RunnableRequest.java   Source Code and License 5 votes vote down vote up
private void makeRequest(HttpRequest request) {
    log.debug("Writing request: {}", request);
    channel.pipeline().addFirst(new WriteTimeoutHandler(context.configuration().writeTimeout()));
    channel.writeAndFlush(new StreamedRequest(request, context.sdkRequestProvider(), channel))
           .addListener(wireCall -> {
               ChannelUtils.removeIfExists(channel.pipeline(), WriteTimeoutHandler.class);
               if (wireCall.isSuccess()) {
                   channel.pipeline().addFirst(new ReadTimeoutHandler(context.configuration().readTimeout()));
                   // Auto-read is turned off so trigger an explicit read to give control to HttpStreamsClientHandler
                   channel.read();
               } else {
                   handleFailure(() -> "Failed to make request to " + endpoint(), wireCall.cause());
               }
           });
}
 
Example 35
Project: aws-sdk-java-v2   File: RequestAdapter.java   Source Code and License 5 votes vote down vote up
public HttpRequest adapt(SdkHttpRequest sdkRequest) {
    String uri = sdkRequest.getUri().toString();
    HttpMethod method = toNettyHttpMethod(sdkRequest.method());
    HttpHeaders headers = new DefaultHttpHeaders();
    DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, uri, headers);
    sdkRequest.headers().forEach(request.headers()::add);
    return request;
}
 
Example 36
Project: onedatashare   File: HTTPBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * Prepares request message to be sent.
 * 
 * @param path specific file path under this host
 * @return Message to be sent
 */
protected HttpRequest prepareRequest(String method, String path) {
  HttpRequest request = new DefaultFullHttpRequest( 
      HttpVersion.HTTP_1_1, HttpMethod.valueOf(method), path);
  request.headers().set(HttpHeaders.Names.HOST, this.uri.host());
  request.headers().set(HttpHeaders.Names.USER_AGENT, "Stork");

  return request;
}
 
Example 37
Project: bromium   File: EventDetectorImplTest.java   Source Code and License 5 votes vote down vote up
@Test
public void packagesPredicateAndConverter() {
    Predicate<HttpRequest> expectedPredicate = mock(Predicate.class);
    HttpRequestToTestCaseStepConverter expectedConverter = mock(HttpRequestToTestCaseStepConverter.class);

    EventDetector eventDetector = new EventDetectorImpl(expectedPredicate, expectedConverter);

    assertEquals(expectedPredicate, eventDetector.canDetectPredicate());
    assertEquals(expectedConverter, eventDetector.getConverter());
}
 
Example 38
Project: bromium   File: ReplayingStateTest.java   Source Code and License 5 votes vote down vote up
@Test
public void httpQueueIsEmptyInTheBeginningAndRemainsEmptyIfURIIsNotInWhiteList() {
    ReplayingState replayingState = new ReplayingState(baseURI);
    assertTrue(replayingState.httpRequestQueueIsEmpty());
    HttpRequest httpRequest = mock(HttpRequest.class);
    when(httpRequest.getUri()).thenReturn(exampleURIFromAnotherHost);
    replayingState.addHttpRequestToQueue(httpRequest);
    assertTrue(replayingState.httpRequestQueueIsEmpty());
}
 
Example 39
Project: bromium   File: RecordResponseFilterTest.java   Source Code and License 5 votes vote down vote up
private void baseTest(boolean predicateReturnValue) {
    HttpRequest httpRequest = mock(HttpRequest.class);
    HttpResponse httpResponse = mock(HttpResponse.class);
    httpMessageContents = mock(HttpMessageContents.class);
    when(httpMessageContents.getTextContents()).thenReturn(htmlContent);
    HttpMessageInfo httpMessageInfo = mock(HttpMessageInfo.class);
    when(httpMessageInfo.getOriginalRequest()).thenReturn(httpRequest);

    Predicate<HttpRequest> predicate = mock(Predicate.class);
    when(predicate.test(httpRequest)).thenReturn(predicateReturnValue);

    RecordResponseFilter recordResponseFilter = new RecordResponseFilter(injectionCode, predicate);
    recordResponseFilter.filterResponse(httpResponse, httpMessageContents, httpMessageInfo);
}
 
Example 40
Project: libcwfincore   File: GdaxExchangeSession.java   Source Code and License 5 votes vote down vote up
private void addAuthHeaders(HttpRequest request) throws GeneralSecurityException {
    String timestamp = String.valueOf(clockProvider.get().instant().getEpochSecond());
    HttpMethod method = request.method();
    String urlTxt = request.uri();
    ByteBuffer body = null;
    if (request instanceof FullHttpRequest) {
        body = ((FullHttpRequest) request).content().nioBuffer();
    }
    String signature = computeAccessSignature(timestamp, method, urlTxt, body);

    request.headers().add("CB-ACCESS-KEY", apiKey);
    request.headers().add("CB-ACCESS-SIGN", signature);
    request.headers().add("CB-ACCESS-TIMESTAMP", timestamp);
    request.headers().add("CB-ACCESS-PASSPHRASE", new String(passphrase));
}