Search in sources :

Example 61 with BasicHeader

use of org.apache.http.message.BasicHeader in project cxf by apache.

the class Client method main.

public static void main(String[] args) throws Exception {
    String keyStoreLoc = "src/main/config/clientKeystore.jks";
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(keyStoreLoc), "cspass".toCharArray());
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).loadKeyMaterial(keyStore, "ckpass".toCharArray()).build();
    /*
         * Send HTTP GET request to query customer info using portable HttpClient
         * object from Apache HttpComponents
         */
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslcontext);
    System.out.println("Sending HTTPS GET request to query customer info");
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sf).build();
    HttpGet httpget = new HttpGet(BASE_SERVICE_URL + "/123");
    BasicHeader bh = new BasicHeader("Accept", "text/xml");
    httpget.addHeader(bh);
    CloseableHttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    entity.writeTo(System.out);
    response.close();
    httpclient.close();
    /*
         *  Send HTTP PUT request to update customer info, using CXF WebClient method
         *  Note: if need to use basic authentication, use the WebClient.create(baseAddress,
         *  username,password,configFile) variant, where configFile can be null if you're
         *  not using certificates.
         */
    System.out.println("\n\nSending HTTPS PUT to update customer name");
    WebClient wc = WebClient.create(BASE_SERVICE_URL, CLIENT_CONFIG_FILE);
    Customer customer = new Customer();
    customer.setId(123);
    customer.setName("Mary");
    Response resp = wc.put(customer);
    /*
         *  Send HTTP POST request to add customer, using JAXRSClientProxy
         *  Note: if need to use basic authentication, use the JAXRSClientFactory.create(baseAddress,
         *  username,password,configFile) variant, where configFile can be null if you're
         *  not using certificates.
         */
    System.out.println("\n\nSending HTTPS POST request to add customer");
    CustomerService proxy = JAXRSClientFactory.create(BASE_SERVICE_URL, CustomerService.class, CLIENT_CONFIG_FILE);
    customer = new Customer();
    customer.setName("Jack");
    resp = wc.post(customer);
    System.out.println("\n");
    System.exit(0);
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) CustomerService(httpsdemo.common.CustomerService) HttpEntity(org.apache.http.HttpEntity) Customer(httpsdemo.common.Customer) HttpGet(org.apache.http.client.methods.HttpGet) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) WebClient(org.apache.cxf.jaxrs.client.WebClient) FileInputStream(java.io.FileInputStream) Response(javax.ws.rs.core.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BasicHeader(org.apache.http.message.BasicHeader)

Example 62 with BasicHeader

use of org.apache.http.message.BasicHeader in project uPortal by Jasig.

the class AuthorizationHeaderProvider method createHeader.

@Override
public Header createHeader(RenderRequest renderRequest, RenderResponse renderResponse) {
    // Username
    final String username = getUsername(renderRequest);
    // Attributes
    final Map<String, List<String>> attributes = new HashMap<>();
    final IPersonAttributes person = personAttributeDao.getPerson(username);
    if (person != null) {
        for (Entry<String, List<Object>> y : person.getAttributes().entrySet()) {
            final List<String> values = new ArrayList<>();
            for (Object value : y.getValue()) {
                if (value instanceof String) {
                    values.add((String) value);
                }
            }
            attributes.put(y.getKey(), values);
        }
    }
    logger.debug("Found the following user attributes for username='{}':  {}", username, attributes);
    // Groups
    final List<String> groups = new ArrayList<>();
    final IGroupMember groupMember = GroupService.getGroupMember(username, IPerson.class);
    if (groupMember != null) {
        Set<IEntityGroup> ancestors = groupMember.getAncestorGroups();
        for (IEntityGroup g : ancestors) {
            groups.add(g.getName());
        }
    }
    logger.debug("Found the following group affiliations for username='{}':  {}", username, groups);
    // Expiration of the Bearer token
    final PortletSession portletSession = renderRequest.getPortletSession();
    final Date expires = new Date(portletSession.getLastAccessedTime() + ((long) portletSession.getMaxInactiveInterval() * 1000L));
    // Authorization header
    final Bearer bearer = bearerService.createBearer(username, attributes, groups, expires);
    final Header rslt = new BasicHeader(Headers.AUTHORIZATION.getName(), Headers.BEARER_TOKEN_PREFIX + bearer.getEncryptedToken());
    logger.debug("Produced the following Authorization header for username='{}':  {}", username, rslt);
    return rslt;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Date(java.util.Date) IEntityGroup(org.apereo.portal.groups.IEntityGroup) IGroupMember(org.apereo.portal.groups.IGroupMember) IPersonAttributes(org.apereo.services.persondir.IPersonAttributes) PortletSession(javax.portlet.PortletSession) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) ArrayList(java.util.ArrayList) List(java.util.List) Bearer(org.apereo.portal.soffit.model.v1_0.Bearer) BasicHeader(org.apache.http.message.BasicHeader)

Example 63 with BasicHeader

use of org.apache.http.message.BasicHeader in project elasticsearch by elastic.

the class RequestLoggerTests method testResponseWarnings.

public void testResponseWarnings() throws Exception {
    HttpHost host = new HttpHost("localhost", 9200);
    HttpUriRequest request = randomHttpRequest(new URI("/index/type/_api"));
    int numWarnings = randomIntBetween(1, 5);
    StringBuilder expected = new StringBuilder("request [").append(request.getMethod()).append(" ").append(host).append("/index/type/_api] returned ").append(numWarnings).append(" warnings: ");
    Header[] warnings = new Header[numWarnings];
    for (int i = 0; i < numWarnings; i++) {
        String warning = "this is warning number " + i;
        warnings[i] = new BasicHeader("Warning", warning);
        if (i > 0) {
            expected.append(",");
        }
        expected.append("[").append(warning).append("]");
    }
    assertEquals(expected.toString(), RequestLogger.buildWarningMessage(request, host, warnings));
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) HttpHost(org.apache.http.HttpHost) URI(java.net.URI) BasicHeader(org.apache.http.message.BasicHeader)

Example 64 with BasicHeader

use of org.apache.http.message.BasicHeader in project elasticsearch by elastic.

the class RestClientTestUtil method randomHeaders.

/**
     * Create a random number of {@link Header}s.
     * Generated header names will either be the {@code baseName} plus its index, or exactly the provided {@code baseName} so that the
     * we test also support for multiple headers with same key and different values.
     */
static Header[] randomHeaders(Random random, final String baseName) {
    int numHeaders = RandomNumbers.randomIntBetween(random, 0, 5);
    final Header[] headers = new Header[numHeaders];
    for (int i = 0; i < numHeaders; i++) {
        String headerName = baseName;
        //randomly exercise the code path that supports multiple headers with same key
        if (random.nextBoolean()) {
            headerName = headerName + i;
        }
        headers[i] = new BasicHeader(headerName, RandomStrings.randomAsciiOfLengthBetween(random, 3, 10));
    }
    return headers;
}
Also used : BasicHeader(org.apache.http.message.BasicHeader) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader)

Example 65 with BasicHeader

use of org.apache.http.message.BasicHeader in project dropwizard by dropwizard.

the class HttpClientBuilderTest method usesDefaultForNonPersistentConnections.

@Test
public void usesDefaultForNonPersistentConnections() throws Exception {
    configuration.setKeepAlive(Duration.seconds(1));
    assertThat(builder.using(configuration).createClient(apacheBuilder, connectionManager, "test")).isNotNull();
    final Field field = FieldUtils.getField(httpClientBuilderClass, "keepAliveStrategy", true);
    final DefaultConnectionKeepAliveStrategy strategy = (DefaultConnectionKeepAliveStrategy) field.get(apacheBuilder);
    final HttpContext context = mock(HttpContext.class);
    final HttpResponse response = mock(HttpResponse.class);
    final HeaderIterator iterator = new BasicListHeaderIterator(ImmutableList.of(new BasicHeader(HttpHeaders.CONNECTION, "timeout=50")), HttpHeaders.CONNECTION);
    when(response.headerIterator(HTTP.CONN_KEEP_ALIVE)).thenReturn(iterator);
    assertThat(strategy.getKeepAliveDuration(response, context)).isEqualTo(50000);
}
Also used : Field(java.lang.reflect.Field) DefaultConnectionKeepAliveStrategy(org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) BasicListHeaderIterator(org.apache.http.message.BasicListHeaderIterator) HttpResponse(org.apache.http.HttpResponse) HeaderIterator(org.apache.http.HeaderIterator) BasicListHeaderIterator(org.apache.http.message.BasicListHeaderIterator) BasicHeader(org.apache.http.message.BasicHeader) Test(org.junit.Test)

Aggregations

BasicHeader (org.apache.http.message.BasicHeader)128 Header (org.apache.http.Header)67 Test (org.junit.Test)29 List (java.util.List)21 HashMap (java.util.HashMap)19 HttpGet (org.apache.http.client.methods.HttpGet)18 BasicStatusLine (org.apache.http.message.BasicStatusLine)17 ProtocolVersion (org.apache.http.ProtocolVersion)16 StatusLine (org.apache.http.StatusLine)16 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)16 IOException (java.io.IOException)15 HttpURLConnection (java.net.HttpURLConnection)15 URL (java.net.URL)15 HttpResponse (org.apache.http.HttpResponse)15 Response (org.elasticsearch.client.Response)10 ArrayList (java.util.ArrayList)9 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)9 TestHttpResponse (org.robolectric.shadows.httpclient.TestHttpResponse)9 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)8 StringEntity (org.apache.http.entity.StringEntity)8