Java Code Examples for org.eclipse.jetty.client.api.Request#header()

The following examples show how to use org.eclipse.jetty.client.api.Request#header() . 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: OAuthConnector.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void setAuthentication(@Nullable String clientId, @Nullable String clientSecret, Request request,
        Fields fields, boolean supportsBasicAuth) {
    logger.debug("Setting authentication for clientId {}. Using basic auth {}", clientId, supportsBasicAuth);
    if (supportsBasicAuth && clientSecret != null) {
        String authString = clientId + ":" + clientSecret;
        request.header(HttpHeader.AUTHORIZATION,
                "Basic " + Base64.getEncoder().encodeToString(authString.getBytes(StandardCharsets.UTF_8)));
    } else {
        if (clientId != null) {
            fields.add(CLIENT_ID, clientId);
        }
        if (clientSecret != null) {
            fields.add(CLIENT_SECRET, clientSecret);
        }
    }
}
 
Example 2
Source File: JettyXhrTransport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private static void addHttpHeaders(Request request, HttpHeaders headers) {
	for (String name : headers.keySet()) {
		for (String value : headers.get(name)) {
			request.header(name, value);
		}
	}
}
 
Example 3
Source File: ProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
private Request createProxyRequest(HttpServletRequest request, HttpServletResponse response, URI targetUri,
        ContentProvider contentProvider) {
    final Request proxyRequest = this._client.newRequest(targetUri)
            .method(HttpMethod.fromString(request.getMethod()))
            .version(HttpVersion.fromString(request.getProtocol()));

    // Copy headers
    for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
        String headerName = headerNames.nextElement();
        String lowerHeaderName = headerName.toLowerCase(Locale.ENGLISH);

        // Remove hop-by-hop headers
        if (HOP_HEADERS.contains(lowerHeaderName))
            continue;

        if ((this._hostHeader != null) && lowerHeaderName.equals("host"))
            continue;

        for (Enumeration<String> headerValues = request.getHeaders(headerName); headerValues.hasMoreElements();) {
            String headerValue = headerValues.nextElement();
            if (headerValue != null)
                proxyRequest.header(headerName, headerValue);
        }
    }

    // Force the Host header if configured
    if (this._hostHeader != null)
        proxyRequest.header(HttpHeader.HOST, this._hostHeader);

    proxyRequest.content(contentProvider);
    this.customizeProxyRequest(proxyRequest, request);
    proxyRequest.timeout(this.getTimeout(), TimeUnit.MILLISECONDS);
    return proxyRequest;
}
 
Example 4
Source File: ProxyServletService.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * If the URI contains user info in the form <code>user[:pass]@</code>, attempt to preempt the server
 * returning a 401 by providing Basic Authentication support in the initial request to the server.
 *
 * @param uri the URI which may contain user info
 * @param request the outgoing request to which an authorization header may be added
 */
void maybeAppendAuthHeader(URI uri, Request request) {
    if (uri != null && uri.getUserInfo() != null) {
        String[] userInfo = uri.getUserInfo().split(":");

        if (userInfo.length >= 1) {
            String user = userInfo[0];
            String password = userInfo.length >= 2 ? userInfo[1] : null;
            String authString = password != null ? user + ":" + password : user + ":";

            String basicAuthentication = "Basic " + B64Code.encode(authString, StringUtil.__ISO_8859_1);
            request.header(HttpHeader.AUTHORIZATION, basicAuthentication);
        }
    }
}
 
Example 5
Source File: JettyCougarRequestFactory.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
protected void addHeaders(Request request, List<Header> headers) {
    for (Header header : headers) {
        if (header.getValue() != null) {
            request.header(header.getName(), header.getValue());
        }
    }
}
 
Example 6
Source File: ProxyServletService.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * If the URI contains user info in the form <code>user[:pass]@</code>, attempt to preempt the server
 * returning a 401 by providing Basic Authentication support in the initial request to the server.
 *
 * @param uri the URI which may contain user info
 * @param request the outgoing request to which an authorization header may be added
 */
void maybeAppendAuthHeader(URI uri, Request request) {
    if (uri != null && uri.getUserInfo() != null) {
        String[] userInfo = uri.getUserInfo().split(":");

        if (userInfo.length >= 1) {
            String user = userInfo[0];
            String password = userInfo.length >= 2 ? userInfo[1] : null;
            String authString = password != null ? user + ":" + password : user + ":";

            String basicAuthentication = "Basic " + B64Code.encode(authString, StringUtil.__ISO_8859_1);
            request.header(HttpHeader.AUTHORIZATION, basicAuthentication);
        }
    }
}
 
Example 7
Source File: ReverseProxyServlet.java    From logbook with MIT License 5 votes vote down vote up
@Override
protected void addProxyHeaders(HttpServletRequest clientRequest, Request proxyRequest) {
    if (AppConfig.get().isConnectionClose()) {
        // 通信エラーを抑止する Connection: closeヘッダを追加
        proxyRequest.header(HttpHeader.CONNECTION, "close");
    }
}
 
Example 8
Source File: HttpCertSigner.java    From athenz with Apache License 2.0 5 votes vote down vote up
ContentResponse processX509CertRequest(final String csr, final List<Integer> extKeyUsage,
        int expiryTime, int retryCount) {
    
    ContentResponse response = null;
    try {
        Request request = httpClient.POST(x509CertUri);
        request.header(HttpHeader.ACCEPT, CONTENT_JSON);
        request.header(HttpHeader.CONTENT_TYPE, CONTENT_JSON);
        
        X509CertSignObject csrCert = new X509CertSignObject();
        csrCert.setPem(csr);
        csrCert.setX509ExtKeyUsage(extKeyUsage);
        if (expiryTime > 0 && expiryTime < maxCertExpiryTimeMins) {
            csrCert.setExpiryTime(expiryTime);
        }
        request.content(new StringContentProvider(JSON.string(csrCert)), CONTENT_JSON);
        
        // our max timeout is going to be 30 seconds. By default
        // we're picking a small value to quickly recognize when
        // our idle connections are disconnected by certsigner but
        // we won't allow any connections taking longer than 30 secs
        
        long timeout = retryCount * requestTimeout;
        if (timeout > 30) {
            timeout = 30;
        }
        request.timeout(timeout, TimeUnit.SECONDS);
        response = request.send();
    } catch (Exception ex) {
        LOGGER.error("Unable to process x509 certificate request", ex);
    }
    return response;
}
 
Example 9
Source File: AdminProxyHandler.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
protected void addProxyHeaders(HttpServletRequest clientRequest, Request proxyRequest) {
    super.addProxyHeaders(clientRequest, proxyRequest);
    String user = (String) clientRequest.getAttribute(AuthenticationFilter.AuthenticatedRoleAttributeName);
    if (user != null) {
        proxyRequest.header("X-Original-Principal", user);
    }
}
 
Example 10
Source File: AdminProxyHandler.java    From pulsar with Apache License 2.0 5 votes vote down vote up
/**
 * Ensure the Authorization header is carried over after a 307 redirect
 * from brokers.
 */
@Override
protected Request copyRequest(HttpRequest oldRequest, URI newURI) {
    String authorization = oldRequest.getHeaders().get(HttpHeader.AUTHORIZATION);
    Request newRequest = super.copyRequest(oldRequest, newURI);
    if (authorization != null) {
        newRequest.header(HttpHeader.AUTHORIZATION, authorization);
    }

    return newRequest;
}
 
Example 11
Source File: KerberosPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean interceptInternodeRequest(Request request) {
  SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
  if (info != null && (info.getAction() == SolrDispatchFilter.Action.FORWARD ||
      info.getAction() == SolrDispatchFilter.Action.REMOTEQUERY)) {
    if (info.getUserPrincipal() != null) {
      if (log.isInfoEnabled()) {
        log.info("Setting original user principal: {}", info.getUserPrincipal().getName());
      }
      request.header(ORIGINAL_USER_PRINCIPAL_HEADER, info.getUserPrincipal().getName());
      return true;
    }
  }
  return false;
}
 
Example 12
Source File: BasicAuthPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean interceptInternodeRequest(Request request) {
  if (forwardCredentials) {
    Object userToken = request.getAttributes().get(Http2SolrClient.REQ_PRINCIPAL_KEY);
    if (userToken instanceof BasicAuthUserPrincipal) {
      BasicAuthUserPrincipal principal = (BasicAuthUserPrincipal) userToken;
      String userPassBase64 = Base64.encodeBase64String((principal.getName() + ":" + principal.getPassword()).getBytes(StandardCharsets.UTF_8));
      request.header(HttpHeaders.AUTHORIZATION, "Basic " + userPassBase64);
      return true;
    }
  }
  return false;
}
 
Example 13
Source File: JWTAuthPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean interceptInternodeRequest(Request request) {
  Object userToken = request.getAttributes().get(Http2SolrClient.REQ_PRINCIPAL_KEY);
  if (userToken instanceof JWTPrincipal) {
    JWTPrincipal jwtPrincipal = (JWTPrincipal) userToken;
    request.header(HttpHeaders.AUTHORIZATION, "Bearer " + jwtPrincipal.getToken());
    return true;
  }
  return false;
}
 
Example 14
Source File: BaselineAsyncClientIdentityTokenResolver.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public void rewrite(List<IdentityToken> credentials, Request output) {
    if (credentials != null) {
        for (IdentityToken token : credentials) {
            try {
                String tokenName = SimpleIdentityTokenName.valueOf(token.getName()).name();
                output.header(TOKEN_PREFIX + tokenName, token.getValue());
            } catch (IllegalArgumentException e) { /*ignore*/ }
        }
    }
}
 
Example 15
Source File: LoginHelper.java    From EMP-Connector with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static BayeuxParameters login(URL loginEndpoint, String username, String password,
        BayeuxParameters parameters) throws Exception {
    HttpClient client = new HttpClient(parameters.sslContextFactory());
    try {
        client.getProxyConfiguration().getProxies().addAll(parameters.proxies());
        client.start();
        URL endpoint = new URL(loginEndpoint, getSoapUri());
        Request post = client.POST(endpoint.toURI());
        post.content(new ByteBufferContentProvider("text/xml", ByteBuffer.wrap(soapXmlForLogin(username, password))));
        post.header("SOAPAction", "''");
        post.header("PrettyPrint", "Yes");
        ContentResponse response = post.send();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
        spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();

        LoginResponseParser parser = new LoginResponseParser();
        saxParser.parse(new ByteArrayInputStream(response.getContent()), parser);

        String sessionId = parser.sessionId;
        if (sessionId == null || parser.serverUrl == null) { throw new ConnectException(
                String.format("Unable to login: %s", parser.faultstring)); }

        URL soapEndpoint = new URL(parser.serverUrl);
        String cometdEndpoint = Float.parseFloat(parameters.version()) < 37 ? COMETD_REPLAY_OLD : COMETD_REPLAY;
        URL replayEndpoint = new URL(soapEndpoint.getProtocol(), soapEndpoint.getHost(), soapEndpoint.getPort(),
                new StringBuilder().append(cometdEndpoint).append(parameters.version()).toString());
        return new DelegatingBayeuxParameters(parameters) {
            @Override
            public String bearerToken() {
                return sessionId;
            }

            @Override
            public URL endpoint() {
                return replayEndpoint;
            }
        };
    } finally {
        client.stop();
        client.destroy();
    }
}
 
Example 16
Source File: OcJettyHttpClient.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Override
public void put(Request carrier, String key, String value) {
  carrier.header(key, value);
}
 
Example 17
Source File: CountersLBSPolicy.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
     * Connect to an HTTP end point.
     * 
     * @param opts
     *            The connection options.
     * 
     * @return The connection.
     */
    static private JettyResponseListener doConnect(final HttpClient httpClient,
            final ConnectOptions opts) throws IOException {

        /*
         * Generate the fully formed and encoded URL.
         */
        // The requestURL (w/o URL query parameters).
        final String requestURL = opts.serviceURL;
        
        final StringBuilder urlString = new StringBuilder(requestURL);

        ConnectOptions.addQueryParams(urlString, opts.requestParams);

        if (log.isDebugEnabled()) {
            log.debug("*** Request ***");
            log.debug(requestURL);
            log.debug(opts.method);
            log.debug(urlString.toString());
        }

        Request request = null;
        try {

//            request = RemoteRepository.newRequest(httpClient, urlString.toString(),
//                    opts.method);
            request = httpClient.newRequest(urlString.toString()).method(
                  HttpMethod.GET);

            if (opts.requestHeaders != null) {

                for (Map.Entry<String, String> e : opts.requestHeaders
                        .entrySet()) {

                    request.header(e.getKey(), e.getValue());

                    if (log.isDebugEnabled())
                        log.debug(e.getKey() + ": " + e.getValue());

                }

            }
            
            if (opts.entity != null) {

            	final EntityContentProvider cp = new EntityContentProvider(opts.entity);
                request.content(cp, cp.getContentType());

            }

			final JettyResponseListener listener = new JettyResponseListener(
					request, TimeUnit.SECONDS.toMillis(300));

            request.send(listener);
            
            return listener;

        } catch (Throwable t) {
            /*
             * If something goes wrong, then close the http connection.
             * Otherwise, the connection will be closed by the caller.
             */
            try {
                
                if (request != null)
                    request.abort(t);
                
                
            } catch (Throwable t2) {
                log.warn(t2); // ignored.
            }
            throw new RuntimeException(requestURL + " : " + t, t);
        }

    }
 
Example 18
Source File: JettyCougarRequestFactory.java    From cougar with Apache License 2.0 4 votes vote down vote up
@Override
protected void addPostEntity(Request request, String postEntity, String contentType) {
    request.header(HttpHeader.CONTENT_TYPE, contentType +  "; charset=utf-8");
    request.content(new StringContentProvider(postEntity, UTF8));
}
 
Example 19
Source File: OAuthConnector.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
private Request getMethod(HttpClient httpClient, String tokenUrl) {
    Request request = httpClient.newRequest(tokenUrl).method(HttpMethod.POST);
    request.header(HttpHeader.ACCEPT, "application/json");
    request.header(HttpHeader.ACCEPT_CHARSET, "UTF-8");
    return request;
}
 
Example 20
Source File: CommandProxyServlet.java    From Scribengin with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void onResponseFailure(HttpServletRequest request, HttpServletResponse response, 
                                  Response proxyResponse, Throwable failure){
  //System.err.println("Response Failure!");
  this.setForwardingUrl();
  
  HttpClient c = null;
  try {
    c = this.createHttpClient();
  } catch (ServletException e1) {
    e1.printStackTrace();
  }
  
  final Request proxyRequest =  c.newRequest(this.forwardingUrl)
      .method(request.getMethod())
      .version(HttpVersion.fromString(request.getProtocol()));
  
  boolean hasContent = request.getContentLength() > 0 || request.getContentType() != null;
  for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();){
      String headerName = headerNames.nextElement();
      if (HttpHeader.TRANSFER_ENCODING.is(headerName))
          hasContent = true;
      for (Enumeration<String> headerValues = request.getHeaders(headerName); headerValues.hasMoreElements();){
          String headerValue = headerValues.nextElement();
          if (headerValue != null)
              proxyRequest.header(headerName, headerValue);
      }
  }

  // Add proxy headers
  addViaHeader(proxyRequest);
  addXForwardedHeaders(proxyRequest, request);

  final AsyncContext asyncContext = request.getAsyncContext();
  // We do not timeout the continuation, but the proxy request
  asyncContext.setTimeout(0);
  proxyRequest.timeout(getTimeout(), TimeUnit.MILLISECONDS);

  if (hasContent)
    try {
      proxyRequest.content(proxyRequestContent(proxyRequest, request));
    } catch (IOException e) {
      e.printStackTrace();
    }

  customizeProxyRequest(proxyRequest, request);

  proxyRequest.send(new ProxyResponseListener(request, response));
}