Java 类io.netty.handler.codec.http.HttpRequest 实例源码

项目:bromium    文件:RequestToPageLoadingEventConverterTest.java   
@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);
}
项目:tasfe-framework    文件:HttpSessionInterceptor.java   
@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;
            }
        }
    }
}
项目:redant    文件:DataStorer.java   
@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);
}
项目:CloudNet    文件:WebsiteDocumentation.java   
@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;
}
项目:bromium    文件:RequestToPageLoadingEventConverterTest.java   
@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());
}
项目:hadoop    文件:WebHdfsHandler.java   
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);
  }
}
项目:bromium    文件:RecordRequestFilter.java   
@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;
}
项目:hadoop    文件:WebHdfsHandler.java   
@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;
    }
  });
}
项目:bromium    文件:DefaultModule.java   
@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();
    }
}
项目:bromium    文件:RecordRequestFilterTest.java   
@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);
}
项目:bromium    文件:RecordRequestFilterTest.java   
@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());
}
项目:elasticsearch_my    文件:Netty4CorsHandler.java   
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");
    }
}
项目:teslog    文件:HttpHelloWorldServerHandler.java   
@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);
        }
    }
}
项目:mqttserver    文件:HttpRequestHandler.java   
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);
    }
}
项目:bromium    文件:RecordRequestFilterTest.java   
@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());
}
项目:util4j    文件:NettyHttpClient.java   
/**
 * 同步请求
 * @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;
}
项目:proxyee-down    文件:HttpRequestInfo.java   
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;
}
项目:bromium    文件:GetHtmlFromCurrentHostPredicateTest.java   
@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));
}
项目:tasfe-framework    文件:Utils.java   
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;
}
项目:util4j    文件:NettyHttpClient.java   
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();
    }
项目:bromium    文件:RequestToPageLoadingEventConverterTest.java   
@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);
}
项目:bromium    文件:UriContainsStringPredicateTest.java   
@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));
}
项目:redant    文件:CookieManager.java   
/**
 * 删除一个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);
}
项目:redant    文件:CookieHelper.java   
/**
 * 设置所有的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);
        }
    }
}
项目:redant    文件:CookieHelper.java   
/**
 * 删除一个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;
}
项目:redant    文件:DefaultCookieRender.java   
@Override
public boolean deleteCookie(String name) {
    if(response==null){
        response = response();
    }
    HttpRequest request = DataHolder.getHttpRequest();
    return CookieHelper.deleteCookie(request,response,name);
}
项目:push-network-proxies    文件:MockingFCMProxyServer.java   
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();
    }
项目:mqttserver    文件:HttpJsonpTransport.java   
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);
}
项目:bromium    文件:RecordThroughTheRecordRequestFilterIT.java   
@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);
    }
}
项目:libcwfincore    文件:GdaxExchangeSession.java   
public void sendRequest(ChannelFuture channelFuture, HttpRequest request) throws GeneralSecurityException {
    if (channelFuture.isDone()) {
        sendRequest(channelFuture.channel(), request);
    } else {
        channelFuture.addListener(future -> sendRequest(channelFuture.channel(), request));
    }
}
项目:bromium    文件:GetHtmlFromCurrentHostPredicateTest.java   
@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));
}
项目:bromium    文件:RequestToPageLoadingEventConverterTest.java   
@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);
}
项目:bromium    文件:GetHtmlFromCurrentHostPredicate.java   
@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;
}
项目:aws-sdk-java-v2    文件:RunnableRequest.java   
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());
               }
           });
}
项目:aws-sdk-java-v2    文件:RequestAdapter.java   
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;
}
项目:onedatashare    文件:HTTPBuilder.java   
/**
 * 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;
}
项目:bromium    文件:EventDetectorImplTest.java   
@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());
}
项目:bromium    文件:ReplayingStateTest.java   
@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());
}
项目:bromium    文件:RecordResponseFilterTest.java   
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);
}
项目:libcwfincore    文件:GdaxExchangeSession.java   
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));
}