Java Code Examples for org.apache.http.HttpVersion#HTTP_1_1

The following examples show how to use org.apache.http.HttpVersion#HTTP_1_1 . 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: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar"));

    mockClient = Mockito.mock(SdkHttpClient.class);
    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("test payload".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    ClientConfiguration clientConfig = new ClientConfiguration();

    client = new GenericApiGatewayClientBuilder()
            .withClientConfiguration(clientConfig)
            .withCredentials(credentials)
            .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .withApiKey("12345")
            .withHttpClient(new AmazonHttpClient(clientConfig, mockClient, null))
            .build();
}
 
Example 2
Source File: MockHttpClient.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestDirector createClientRequestDirector(
    HttpRequestExecutor requestExec,
    ClientConnectionManager conman,
    ConnectionReuseStrategy reustrat,
    ConnectionKeepAliveStrategy kastrat,
    HttpRoutePlanner rouplan,
    HttpProcessor httpProcessor,
    HttpRequestRetryHandler retryHandler,
    RedirectHandler redirectHandler,
    AuthenticationHandler targetAuthHandler,
    AuthenticationHandler proxyAuthHandler,
    UserTokenHandler stateHandler,
    HttpParams params) {
  return new RequestDirector() {
    @Beta
    public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {
      return new BasicHttpResponse(HttpVersion.HTTP_1_1, responseCode, null);
    }
  };
}
 
Example 3
Source File: TracedResponseHandlerTest.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
private Segment segmentInResponseToCode(int code) {
    NoOpResponseHandler responseHandler = new NoOpResponseHandler();
    TracedResponseHandler<String> tracedResponseHandler = new TracedResponseHandler<>(responseHandler);
    HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, code, ""));

    Segment segment = AWSXRay.beginSegment("test");
    AWSXRay.beginSubsegment("someHttpCall");

    try {
        tracedResponseHandler.handleResponse(httpResponse);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    AWSXRay.endSubsegment();
    AWSXRay.endSegment();
    return segment;
}
 
Example 4
Source File: RequestHandler.java    From djl-demo with Apache License 2.0 6 votes vote down vote up
/** Handles URLs predicted as malicious. */
private void blockedMaliciousSiteRequested() {
    try {
        HttpResponse response =
                new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "MAL");
        HttpEntity httpEntity = new FileEntity(new File("index.html"), ContentType.WILDCARD);
        BufferedWriter bufferedWriter =
                new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
        bufferedWriter.write(response.getStatusLine().toString());
        String headers =
                "Proxy-agent: FilterProxy/1.0\r\n"
                        + httpEntity.getContentType().toString()
                        + "\r\n"
                        + "Content-Length: "
                        + httpEntity.getContentLength()
                        + "\r\n\r\n";
        bufferedWriter.write(headers);
        // Pass index.html content
        bufferedWriter.write(EntityUtils.toString(httpEntity));
        bufferedWriter.flush();
        bufferedWriter.close();
    } catch (IOException e) {
        logger.error("Error writing to client when requested a blocked site", e);
    }
}
 
Example 5
Source File: ConnectionReuseTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void headerRequest(HttpHost target, HttpRoute route, HttpClientConnection conn, PoolingHttpClientConnectionManager cm)
    throws IOException, HttpException {
  HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);

  req.addHeader("Host", target.getHostName());
  if (!conn.isOpen()) {
    // establish connection based on its route info
    cm.connect(conn, route, 1000, context);
    // and mark it as route complete
    cm.routeComplete(conn, route, context);
  }
  conn.sendRequestHeader(req);
  conn.flush();
  conn.receiveResponseHeader();
}
 
Example 6
Source File: DataBridgeWebClientTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBusinessObjectDataStorageFilesCreateResponse200ValidResponseHttpResponseThrowsExceptionOnClose() throws Exception
{
    CloseableHttpResponse httpResponse = new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "testReasonPhrase"), true);
    httpResponse.setEntity(new StringEntity(xmlHelper.objectToXml(new BusinessObjectDataStorageFilesCreateResponse())));

    executeWithoutLogging(DataBridgeWebClient.class, () -> {
        BusinessObjectDataStorageFilesCreateResponse businessObjectDataStorageFilesCreateResponse =
            dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse);
        assertNotNull("businessObjectDataStorageFilesCreateResponse", businessObjectDataStorageFilesCreateResponse);
    });
}
 
Example 7
Source File: DataBridgeWebClientTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBusinessObjectDataStorageFilesCreateResponse200ValidResponse() throws Exception
{
    CloseableHttpResponse httpResponse = new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "testReasonPhrase"), false);
    httpResponse.setEntity(new StringEntity(xmlHelper.objectToXml(new BusinessObjectDataStorageFilesCreateResponse())));
    BusinessObjectDataStorageFilesCreateResponse businessObjectDataStorageFilesCreateResponse =
        dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse);
    assertNotNull("businessObjectDataStorageFilesCreateResponse", businessObjectDataStorageFilesCreateResponse);
}
 
Example 8
Source File: SimpleHttpFetcher.java    From ache with Apache License 2.0 5 votes vote down vote up
public SimpleHttpFetcher(int maxThreads, UserAgent userAgent) {
    super(maxThreads, userAgent);

    _httpVersion = HttpVersion.HTTP_1_1;
    _socketTimeout = DEFAULT_SOCKET_TIMEOUT;
    _connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
    _maxRetryCount = DEFAULT_MAX_RETRY_COUNT;

    // Just to be explicit, we rely on lazy initialization of this so that
    // we don't have to worry about serializing it.
    _httpClient = null;
}
 
Example 9
Source File: ControlPointApiClientTest.java    From find with MIT License 5 votes vote down vote up
/**
 * Create a simple HTTP response object.
 */
public static HttpResponse buildResponse(
    final int statusCode, final String statusMessage, final String body
) {
    final BasicHttpResponse response =
        new BasicHttpResponse(HttpVersion.HTTP_1_1, statusCode, statusMessage);
    response.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
    return response;
}
 
Example 10
Source File: JWTClientUtilTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Test(description = "Test get response string.")
public void testGetResponseString() throws IOException {
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null);
    BasicHttpEntity httpEntity = new BasicHttpEntity();
    httpEntity.setContent(new ByteArrayInputStream("test message".getBytes(StandardCharsets.UTF_8.name())));
    response.setEntity(httpEntity);
    String result = JWTClientUtil.getResponseString(response);
    Assert.assertEquals(result, "test message");
}
 
Example 11
Source File: HttpServerConformanceTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
void execute() throws Throwable {
    requestVersion = HttpVersion.HTTP_1_0;
    runTest(this);

    requestVersion = HttpVersion.HTTP_1_1;
    runTest(this);

    executorService.shutdown();
}
 
Example 12
Source File: FakeHttpStack.java    From openshop.io-android with MIT License 5 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> stringStringMap) throws IOException, AuthFailureError {
    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    List<Header> headers = defaultHeaders();
    response.setHeaders(headers.toArray(new Header[headers.size()]));
    //response.setLocale(Locale.JAPAN);
    response.setEntity(createEntity(request));
    return response;
}
 
Example 13
Source File: RetryPolicyTestBase.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse execute(HttpUriRequest request) throws IOException,
        ClientProtocolException {
    return new BasicHttpResponse(new BasicStatusLine(
            HttpVersion.HTTP_1_1,
            statusCode,
            reasonPhrase));
}
 
Example 14
Source File: DataBridgeWebClientTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBusinessObjectDataStorageFilesCreateResponse400BadContentThrows() throws Exception
{
    int expectedStatusCode = 400;
    String expectedReasonPhrase = "testReasonPhrase";
    String expectedErrorMessage = "invalid xml";

    CloseableHttpResponse httpResponse =
        new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, expectedStatusCode, expectedReasonPhrase), false);
    httpResponse.setEntity(new StringEntity(expectedErrorMessage));
    try
    {
        executeWithoutLogging(DataBridgeWebClient.class, () -> {
            dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse);
        });
        Assert.fail("expected HttpErrorResponseException, but no exception was thrown");
    }
    catch (Exception e)
    {
        assertEquals("thrown exception type", HttpErrorResponseException.class, e.getClass());

        HttpErrorResponseException httpErrorResponseException = (HttpErrorResponseException) e;
        assertEquals("httpErrorResponseException responseMessage", expectedErrorMessage, httpErrorResponseException.getResponseMessage());
        assertEquals("httpErrorResponseException statusCode", expectedStatusCode, httpErrorResponseException.getStatusCode());
        assertEquals("httpErrorResponseException statusDescription", expectedReasonPhrase, httpErrorResponseException.getStatusDescription());
        assertEquals("httpErrorResponseException message", "Failed to add storage files", httpErrorResponseException.getMessage());
    }
}
 
Example 15
Source File: DataBridgeWebClientTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBusinessObjectDataStorageFilesCreateResponse400Throws() throws Exception
{
    int expectedStatusCode = 400;
    String expectedReasonPhrase = "testReasonPhrase";
    String expectedErrorMessage = "testErrorMessage";

    ErrorInformation errorInformation = new ErrorInformation();
    errorInformation.setStatusCode(expectedStatusCode);
    errorInformation.setMessage(expectedErrorMessage);
    errorInformation.setStatusDescription(expectedReasonPhrase);

    String requestContent = xmlHelper.objectToXml(errorInformation);

    CloseableHttpResponse httpResponse =
        new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, expectedStatusCode, expectedReasonPhrase), false);
    httpResponse.setEntity(new StringEntity(requestContent));
    try
    {
        dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse);
        Assert.fail("expected HttpErrorResponseException, but no exception was thrown");
    }
    catch (Exception e)
    {
        assertEquals("thrown exception type", HttpErrorResponseException.class, e.getClass());

        HttpErrorResponseException httpErrorResponseException = (HttpErrorResponseException) e;
        assertEquals("httpErrorResponseException responseMessage", expectedErrorMessage, httpErrorResponseException.getResponseMessage());
        assertEquals("httpErrorResponseException statusCode", expectedStatusCode, httpErrorResponseException.getStatusCode());
        assertEquals("httpErrorResponseException statusDescription", expectedReasonPhrase, httpErrorResponseException.getStatusDescription());
        assertEquals("httpErrorResponseException message", "Failed to add storage files", httpErrorResponseException.getMessage());
    }
}
 
Example 16
Source File: MockHttpRequester.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
ExecuteBuilder<T> withResponse(int code, String status, String mimeType, String body) {
    BasicHttpResponse r = new BasicHttpResponse(
            new BasicStatusLine(HttpVersion.HTTP_1_1, code, status)
    );
    StringEntity e = new StringEntity(body, ContentType.create(mimeType, Charset.forName("UTF-8")));
    r.setEntity(e);
    return withResponse(r);
}
 
Example 17
Source File: DelayedResponseLevelRetryHandlerTest.java    From vespa with Apache License 2.0 4 votes vote down vote up
private static HttpResponse createResponse(int statusCode) {
    return new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, "reason phrase"));
}
 
Example 18
Source File: DirectoryAdapter.java    From emissary with Apache License 2.0 4 votes vote down vote up
/**
 * Handle the packaging and sending of an addPlaces call to a remote directory. Sends multiple keys on the same place
 * with the same cost/quality and description if the description, cost and quality lists are only size 1. Uses a
 * distinct description/cost/quality for each key when there are enough values
 *
 * @param parentDirectory the url portion of the parent directory location
 * @param entryList the list of directory entries to add
 * @param propagating true if going downstream
 * @return status of operation
 */
public EmissaryResponse outboundAddPlaces(final String parentDirectory, final List<DirectoryEntry> entryList, final boolean propagating) {
    if (disableAddPlaces) {
        BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "Not accepting remote add places");
        response.setEntity(EntityBuilder.create().setText("").setContentEncoding(MediaType.TEXT_PLAIN).build());
        return new EmissaryResponse(response);
    } else {
        final String parentDirectoryUrl = KeyManipulator.getServiceHostURL(parentDirectory);
        final HttpPost method = new HttpPost(parentDirectoryUrl + CONTEXT + "/RegisterPlace.action");

        final String parentLoc = KeyManipulator.getServiceLocation(parentDirectory);
        // Separate it out into lists
        final List<String> keyList = new ArrayList<String>();
        final List<String> descList = new ArrayList<String>();
        final List<Integer> costList = new ArrayList<Integer>();
        final List<Integer> qualityList = new ArrayList<Integer>();
        for (final DirectoryEntry d : entryList) {
            keyList.add(d.getKey());
            descList.add(d.getDescription());
            costList.add(Integer.valueOf(d.getCost()));
            qualityList.add(Integer.valueOf(d.getQuality()));
        }

        final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(TARGET_DIRECTORY, parentLoc));

        for (int count = 0; count < keyList.size(); count++) {
            nvps.add(new BasicNameValuePair(ADD_KEY + count, keyList.get(count)));
            // possibly use the single desc/cost/qual for each key
            if (descList.size() > count) {
                String desc = descList.get(count);
                if (desc == null) {
                    desc = "No description provided";
                }
                nvps.add(new BasicNameValuePair(ADD_DESCRIPTION + count, desc));
            }
            if (costList.size() > count) {
                nvps.add(new BasicNameValuePair(ADD_COST + count, costList.get(count).toString()));
            }
            if (qualityList.size() > count) {
                nvps.add(new BasicNameValuePair(ADD_QUALITY + count, qualityList.get(count).toString()));
            }
        }
        nvps.add(new BasicNameValuePair(ADD_PROPAGATION_FLAG, Boolean.toString(propagating)));
        method.setEntity(new UrlEncodedFormEntity(nvps, Charset.defaultCharset()));
        return send(method);
    }
}
 
Example 19
Source File: MoveToAdapter.java    From emissary with Apache License 2.0 4 votes vote down vote up
/**
 * Send a moveTo call to a remote machine
 * 
 * @param place the four-tuple of the place we are heading to
 * @param agent the MobileAgent that is moving
 * @return status of operation including body if successful
 */
public EmissaryResponse outboundMoveTo(final String place, final IMobileAgent agent) {

    String url = null;

    // Move to actions can be load-balanced out to
    // a virtual IP address:port if so configured
    if (VIRTUAL_MOVETO_ADDR != null) {
        url = VIRTUAL_MOVETO_PROTOCOL + "://" + VIRTUAL_MOVETO_ADDR + "/";
    } else {
        url = KeyManipulator.getServiceHostURL(place);
    }
    url += CONTEXT + "/MoveTo.action";

    final HttpPost method = new HttpPost(url);
    method.setHeader("Content-type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
    final List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    nvps.add(new BasicNameValuePair(PLACE_NAME, place));
    nvps.add(new BasicNameValuePair(MOVE_ERROR_COUNT, Integer.toString(agent.getMoveErrorCount())));

    final DirectoryEntry[] iq = agent.getItineraryQueueItems();
    for (int j = 0; j < iq.length; j++) {
        nvps.add(new BasicNameValuePair(ITINERARY_ITEM, iq[j].getKey()));
    }

    try {
        // This is an 8859_1 String
        final String agentData = PayloadUtil.serializeToString(agent.getPayloadForTransport());
        nvps.add(new BasicNameValuePair(AGENT_SERIAL, agentData));
    } catch (IOException iox) {
        // TODO This will probably need looked at when redoing the moveTo
        logger.error("Cannot serialize agent data", iox);
        BasicHttpResponse response =
                new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Cannot serialize agent data");
        response.setEntity(EntityBuilder.create().setText("").setContentEncoding(MediaType.TEXT_PLAIN).build());
        return new EmissaryResponse(response);
    }

    method.setEntity(new UrlEncodedFormEntity(nvps, Charset.forName("8859_1")));

    // Add a cookie to the outbound header if we are posting
    // to the virtual IP for load balancing
    if (VIRTUAL_MOVETO_ADDR != null) {
        final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, KeyManipulator.getServiceClassname(place));
        cookie.setDomain(VIRTUAL_MOVETO_ADDR.substring(0, VIRTUAL_MOVETO_ADDR.indexOf(":")));
        cookie.setPath(COOKIE_PATH);
        return send(method, cookie);
    }
    return send(method);
}
 
Example 20
Source File: DapTestCommon.java    From tds with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public HttpResponse execute(HttpRequestBase rq) throws IOException {
  URI uri = rq.getURI();
  DapController controller = getController(uri);
  StandaloneMockMvcBuilder mvcbuilder = MockMvcBuilders.standaloneSetup(controller);
  mvcbuilder.setValidator(new TestServlet.NullValidator());
  MockMvc mockMvc = mvcbuilder.build();
  MockHttpServletRequestBuilder mockrb = MockMvcRequestBuilders.get(uri);
  // We need to use only the path part
  mockrb.servletPath(uri.getPath());
  // Move any headers from rq to mockrb
  Header[] headers = rq.getAllHeaders();
  for (int i = 0; i < headers.length; i++) {
    Header h = headers[i];
    mockrb.header(h.getName(), h.getValue());
  }
  // Since the url has the query parameters,
  // they will automatically be parsed and added
  // to the rb parameters.

  // Finally set the resource dir
  mockrb.requestAttr("RESOURCEDIR", this.resourcepath);

  // Now invoke the servlet
  MvcResult result;
  try {
    result = mockMvc.perform(mockrb).andReturn();
  } catch (Exception e) {
    throw new IOException(e);
  }

  // Collect the output
  MockHttpServletResponse res = result.getResponse();
  byte[] byteresult = res.getContentAsByteArray();

  // Convert to HttpResponse
  HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, res.getStatus(), "");
  if (response == null)
    throw new IOException("HTTPMethod.executeMock: Response was null");
  Collection<String> keys = res.getHeaderNames();
  // Move headers to the response
  for (String key : keys) {
    List<String> values = res.getHeaders(key);
    for (String v : values) {
      response.addHeader(key, v);
    }
  }
  ByteArrayEntity entity = new ByteArrayEntity(byteresult);
  String sct = res.getContentType();
  entity.setContentType(sct);
  response.setEntity(entity);
  return response;
}