org.eclipse.jetty.http.HttpHeader Java Examples

The following examples show how to use org.eclipse.jetty.http.HttpHeader. 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: TestMasterDown.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private void sanityCheck() throws Exception {
  UserLoginSession ul = login();
  String authHeader =  HttpHeader.AUTHORIZATION.toString();
  String authToken = "_dremio" + ul.getToken();
  Space dg = expectSuccess(currentApiV2.path("space/DG").request(JSON).header(authHeader, authToken).buildGet(), Space.class);
  assertEquals(10, dg.getContents().getDatasets().size());
  expectSuccess(currentApiV2.path("/jobs").request(JSON).header(authHeader, authToken).buildGet(), JobsUI.class);

  SourceUI source = expectSuccess(currentApiV2.path("source/LocalFS1").request(JSON).header(authHeader, authToken).buildGet(), SourceUI.class);
  NamespaceTree ns = source.getContents();
  assertEquals("/source/LocalFS1", source.getResourcePath().toString());
  assertTrue(ns.getDatasets().size() + ns.getFolders().size() + ns.getFiles().size() > 0);

  String folderName = "folder_" + System.currentTimeMillis();
  expectSuccess((currentApiV2.path("space/DG/folder/").request(JSON).header(authHeader, authToken)).buildPost(Entity.json("{\"name\": \""+folderName+"\"}")), Folder.class);
}
 
Example #2
Source File: ReverseProxyServlet.java    From logbook-kai with MIT License 6 votes vote down vote up
@Override
protected void customizeProxyRequest(Request proxyRequest, HttpServletRequest request) {
    proxyRequest.onRequestContent(new RequestContentListener(request));

    if (!AppConfig.get().isUseProxy()) { // アップストリームプロキシがある場合は除外

        // HTTP/1.1 ならkeep-aliveを追加します
        if (proxyRequest.getVersion() == HttpVersion.HTTP_1_1) {
            proxyRequest.header(HttpHeader.CONNECTION, "keep-alive");
        }

        // Pragma: no-cache はプロキシ用なので Cache-Control: no-cache に変換します
        String pragma = proxyRequest.getHeaders().get(HttpHeader.PRAGMA);
        if ((pragma != null) && pragma.equals("no-cache")) {
            proxyRequest.header(HttpHeader.PRAGMA, null);
            if (!proxyRequest.getHeaders().containsKey(HttpHeader.CACHE_CONTROL.asString())) {
                proxyRequest.header(HttpHeader.CACHE_CONTROL, "no-cache");
            }
        }
    }

    String queryString = ((org.eclipse.jetty.server.Request) request).getQueryString();
    fixQueryString(proxyRequest, queryString);

    super.customizeProxyRequest(proxyRequest, request);
}
 
Example #3
Source File: BrooklynSecurityProviderFilterJersey.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("resource")
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    log.trace("BrooklynSecurityProviderFilterJersey.filter {}", requestContext);
    try {
        new BrooklynSecurityProviderFilterHelper().run(webRequest, mgmtC.getContext(ManagementContext.class));
    } catch (SecurityProviderDeniedAuthentication e) {
        Response rin = e.getResponse();
        if (rin==null) rin = Response.status(Status.UNAUTHORIZED).build();
        
        if (rin.getStatus()==Status.FOUND.getStatusCode()) {
            String location = rin.getHeaderString(HttpHeader.LOCATION.asString());
            if (location!=null) {
                log.trace("Redirect to {} for authentication",location);
                final UriBuilder uriBuilder = UriBuilder.fromPath(location);
                rin = Response.temporaryRedirect(uriBuilder.build()).entity("Authentication is required at "+location).build();
            } else {
                log.trace("Unauthorized");
                rin = Response.status(Status.UNAUTHORIZED).entity("Authentication is required").build();
            }
        }
        requestContext.abortWith(rin);
    }
}
 
Example #4
Source File: ChaosHttpProxyTest.java    From chaos-http-proxy with Apache License 2.0 6 votes vote down vote up
@Test
public void testContentLengthNotStrippedByJettyBug() throws Exception {
    // Set up a handler that asserts the presence of a content-length
    httpBin.stop();
    final AtomicReference<Boolean> gotContentLength =
            new AtomicReference<>(false);
    setupHttpBin(new HttpBin(httpBinEndpoint, new HttpBinHandler() {
            @Override
            public void handle(String target, Request baseRequest,
                    HttpServletRequest request,
                    HttpServletResponse servletResponse)
                    throws IOException {
                if (request.getHeader(
                        HttpHeader.CONTENT_LENGTH.asString()) != null) {
                    gotContentLength.set(true);
                }
            }
        }));

    // The content has to be large-ish to exercise the bug
    client.POST(httpBinEndpoint + "/post")
            .content(new BytesContentProvider(new byte[65536]))
            .header(HttpHeader.CONTENT_LENGTH, String.valueOf(65536))
            .send();
    assertThat(gotContentLength.get()).isTrue();
}
 
Example #5
Source File: Response.java    From onedev with MIT License 6 votes vote down vote up
public void setHeader(HttpHeader name, String value)
{
    if (isMutable())
    {
        if (HttpHeader.CONTENT_TYPE == name)
            setContentType(value);
        else
        {
            _fields.put(name, value);

            if (HttpHeader.CONTENT_LENGTH == name)
            {
                if (value == null)
                    _contentLength = -1L;
                else
                    _contentLength = Long.parseLong(value);
            }
        }
    }
}
 
Example #6
Source File: AbstractSSOAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
protected Authentication returnUnauthorized(
    HttpServletRequest httpReq,
    HttpServletResponse httpRes,
    Map errorReason,
    String principalId,
    String logMessageTemplate
) throws ServerAuthException {
  if (getLog().isDebugEnabled()) {
    getLog().debug(logMessageTemplate, getRequestInfoForLogging(httpReq, principalId));
  }
  try {
    httpRes.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "dpm");
    httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    httpRes.setContentType("application/json");
    OBJECT_MAPPER.writeValue(httpRes.getWriter(), errorReason);
    return Authentication.SEND_FAILURE;
  } catch (IOException ex) {
    throw new ServerAuthException(Utils.format("Could send a Unauthorized (401) response: {}", ex.toString(), ex));
  }
}
 
Example #7
Source File: UrlRewriteServletFilterTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutboundHeaderRewrite() throws Exception {
  testSetUp( null );
  // Setup the server side request/response interaction.
  interaction.expect()
      .method( "GET" )
      .requestUrl( "http://mock-host:1/test-output-path-1" );
  interaction.respond()
      .status( 201 )
      .header( "Location", "http://mock-host:1/test-input-path" );
  interactions.add( interaction );
  // Create the client request.
  request.setMethod( "GET" );
  request.setURI( "/test-input-path" );
  //request.setVersion( "HTTP/1.1" );
  request.setHeader( "Host", "mock-host:1" );
  // Execute the request.
  response = TestUtils.execute( server, request );

  // Test the results.
  assertThat( response.getStatus(), is( 201 ) );
  assertThat( response.get( HttpHeader.LOCATION ), is( "http://mock-host:1/test-output-path-1" ) );
}
 
Example #8
Source File: AsyncHttpExecutableTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
private void fireResponse(CapturingRequest request, int errorCode, String responseText, int resultSize, ObservableObserver observer, boolean successfulResponse) throws InterruptedException {
    Response.CompleteListener listener = request.awaitSend(1000, TimeUnit.MILLISECONDS);
    assertNotNull(listener);
    InputStreamResponseListener responseListener = (InputStreamResponseListener) listener;

    Result result = mock(Result.class);
    Response response = mock(Response.class);
    when(result.getResponse()).thenReturn(response);
    when(result.isSucceeded()).thenReturn(successfulResponse);
    when(result.isFailed()).thenReturn(!successfulResponse);
    HttpFields headers = mock(HttpFields.class);
    when(response.getHeaders()).thenReturn(headers);
    when(headers.get(HttpHeader.CONTENT_LENGTH)).thenReturn(String.valueOf(resultSize));
    when(response.getStatus()).thenReturn(errorCode);
    when(response.getVersion()).thenReturn(HttpVersion.HTTP_1_1);

    // fire that event
    responseListener.onHeaders(response);
    responseListener.onContent(response, ByteBuffer.allocate(0));
    responseListener.onComplete(result);

    assertTrue(observer.getLatch().await(1000, TimeUnit.MILLISECONDS));
}
 
Example #9
Source File: MultiSessionAttributeAdapter.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private static Response buildExceptionResponse(SessionErrors error_status, HttpServletRequest optionalRequest, String message) {
    String mediaType;
    String responseData;

    if(requestIsHtml(optionalRequest)){
        mediaType = MediaType.TEXT_HTML;
        StringBuilder sb = new StringBuilder("<p>")
                .append(message)
                .append("</p>\n")
                .append("<p>")
                .append("Please go <a href=\"")
                .append(optionalRequest.getRequestURL())
                .append("\">here</a> to refresh.")
                .append("</p>");
        responseData = sb.toString();
    }else{
        mediaType = MediaType.APPLICATION_JSON;
        JsonObject jsonEntity = new JsonObject();
        jsonEntity.addProperty(error_status.toString(), true);
        responseData = jsonEntity.toString();
    }
    return Response.status(Response.Status.FORBIDDEN)
            .header(HttpHeader.CONTENT_TYPE.asString(), mediaType)
            .entity(responseData).build();
}
 
Example #10
Source File: OAuthConnector.java    From openhab-core 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 #11
Source File: JwtAuthenticatorTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testRedirect() throws IOException, ServerAuthException {
  JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN);

  HttpServletRequest request = mock(HttpServletRequest.class);
  expect(request.getMethod()).andReturn(HttpMethod.GET.asString());
  expect(request.getQueryString()).andReturn(null);
  expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(null);
  expect(request.getCookies()).andReturn(new Cookie[] {});
  expect(request.getRequestURL()).andReturn(new StringBuffer(CRUISE_CONTROL_ENDPOINT));

  HttpServletResponse response = mock(HttpServletResponse.class);
  response.sendRedirect(TOKEN_PROVIDER.replace(JwtAuthenticator.REDIRECT_URL, CRUISE_CONTROL_ENDPOINT));
  expectLastCall().andVoid();

  replay(request, response);
  Authentication actualAuthentication = authenticator.validateRequest(request, response, true);
  verify(request, response);
  assertEquals(Authentication.SEND_CONTINUE, actualAuthentication);
}
 
Example #12
Source File: AvaticaSpnegoAuthenticator.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
/**
 * Jetty has a bug in which if there is an Authorization header sent by a client which is
 * not of the Negotiate type, Jetty does not send the challenge to negotiate. This works
 * around that issue, forcing the challenge to be sent. Will require investigation on
 * upgrade to a newer version of Jetty.
 */
Authentication sendChallengeIfNecessary(Authentication computedAuth, ServletRequest request,
    ServletResponse response) throws IOException {
  if (computedAuth == Authentication.UNAUTHENTICATED) {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    String header = req.getHeader(HttpHeader.AUTHORIZATION.asString());
    // We have an authorization header, but it's not Negotiate
    if (header != null && !header.startsWith(HttpHeader.NEGOTIATE.asString())) {
      LOG.debug("Client sent Authorization header that was not for Negotiate,"
          + " sending challenge anyways.");
      if (DeferredAuthentication.isDeferred(res)) {
        return Authentication.UNAUTHENTICATED;
      }

      res.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), HttpHeader.NEGOTIATE.asString());
      res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return Authentication.SEND_CONTINUE;
    }
  }
  return computedAuth;
}
 
Example #13
Source File: Http2SolrClient.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void decorateRequest(Request req, @SuppressWarnings({"rawtypes"})SolrRequest solrRequest) {
  req.header(HttpHeader.ACCEPT_ENCODING, null);
  if (solrRequest.getUserPrincipal() != null) {
    req.attribute(REQ_PRINCIPAL_KEY, solrRequest.getUserPrincipal());
  }

  setBasicAuthHeader(solrRequest, req);
  for (HttpListenerFactory factory : listenerFactory) {
    HttpListenerFactory.RequestResponseListener listener = factory.get();
    listener.onQueued(req);
    req.onRequestBegin(listener);
    req.onComplete(listener);
  }

  @SuppressWarnings({"unchecked"})
  Map<String, String> headers = solrRequest.getHeaders();
  if (headers != null) {
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      req.header(entry.getKey(), entry.getValue());
    }
  }
}
 
Example #14
Source File: RestBufferManager.java    From incubator-retired-htrace with Apache License 2.0 5 votes vote down vote up
/**
 * Create an HttpClient instance.
 *
 * @param connTimeout         The timeout to use for connecting.
 * @param idleTimeout         The idle timeout to use.
 */
static HttpClient createHttpClient(long connTimeout, long idleTimeout) {
  HttpClient httpClient = new HttpClient();
  httpClient.setUserAgentField(
      new HttpField(HttpHeader.USER_AGENT, "HTracedSpanReceiver"));
  httpClient.setConnectTimeout(connTimeout);
  httpClient.setIdleTimeout(idleTimeout);
  return httpClient;
}
 
Example #15
Source File: JettyResponseListener.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the value of the <code>Content-Type</code> header.
 * @return
 * @throws IOException
 */
public String getContentType() throws IOException {
	ensureResponse();
	
	final HttpFields headers = m_response.getHeaders();
	
	return headers.get(HttpHeader.CONTENT_TYPE);
}
 
Example #16
Source File: AssetServletTest.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 5 votes vote down vote up
@Test
public void guessesMimeTypes() throws Exception {
  response = makeRequest();
  assertThat(response.getStatus())
          .isEqualTo(200);
  assertThat(MimeTypes.CACHE.get(response.get(HttpHeader.CONTENT_TYPE)))
          .isEqualTo(MimeTypes.Type.TEXT_PLAIN_UTF_8);
}
 
Example #17
Source File: AssetServletTest.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 5 votes vote down vote up
@Test
public void servesCharset() throws Exception {
  response = makeRequest(DUMMY_SERVLET + "example.txt");
  assertThat(response.getStatus())
          .isEqualTo(200);
  assertThat(MimeTypes.CACHE.get(response.get(HttpHeader.CONTENT_TYPE)))
          .isEqualTo(MimeTypes.Type.TEXT_PLAIN_UTF_8);

  response = makeRequest(NOCHARSET_SERVLET + "example.txt");
  assertThat(response.getStatus())
          .isEqualTo(200);
  assertThat(response.get(HttpHeader.CONTENT_TYPE))
          .isEqualTo(MimeTypes.Type.TEXT_PLAIN.toString());
}
 
Example #18
Source File: AssetServletTest.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultsToHtml() throws Exception {
  response = makeRequest(DUMMY_SERVLET + "foo.bar");
  assertThat(response.getStatus())
          .isEqualTo(200);
  assertThat(MimeTypes.CACHE.get(response.get(HttpHeader.CONTENT_TYPE)))
          .isEqualTo(MimeTypes.Type.TEXT_HTML_UTF_8);
}
 
Example #19
Source File: ProxyServletServiceTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMaybeAppendAuthHeaderWithFullCredentials() throws URISyntaxException {
    Request request = mock(Request.class);
    URI uri = new URI("http://testuser:[email protected]:8080/content");
    service.maybeAppendAuthHeader(uri, request);
    verify(request).header(HttpHeader.AUTHORIZATION,
            "Basic " + B64Code.encode("testuser:testpassword", StringUtil.__ISO_8859_1));
}
 
Example #20
Source File: AssetServletTest.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 5 votes vote down vote up
@Test
public void addMimeMappings() throws Exception {
  response = makeRequest(MIME_SERVLET + "foo.bar");
  assertThat(response.getStatus())
          .isEqualTo(200);
  assertThat(response.get(HttpHeader.CONTENT_TYPE))
          .isEqualTo("application/bar");
}
 
Example #21
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 #22
Source File: HttpUtilTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testAuthentication() throws Exception {
    when(httpClientMock.newRequest("http://john:[email protected]/")).thenReturn(requestMock);
    mockResponse(HttpStatus.OK_200);

    String result = HttpUtil.executeUrl("GET", "http://john:[email protected]/", 500);

    assertEquals("Some content", result);

    verify(requestMock).header(HttpHeader.AUTHORIZATION, "Basic am9objpkb2U=");
}
 
Example #23
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 #24
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 #25
Source File: TestcaseRunner.java    From irontest with Apache License 2.0 5 votes vote down vote up
/**
 * Extract properties out of API response, and make the properties visible to the next test step run.
 */
private Map<String, String> extractPropertiesOutOfAPIResponse(String teststepType,
                                                              List<PropertyExtractor> propertyExtractors,
                                                              Object apiResponse,
                                                              Map<String, String> referenceableStringProperties) throws Exception {
    Map<String, String> extractedProperties = new HashMap<>();
    for (PropertyExtractor propertyExtractor: propertyExtractors) {
        String propertyExtractionInput = null;
        if (Teststep.TYPE_HTTP.equals(teststepType)) {
            HTTPAPIResponse httpApiResponse = (HTTPAPIResponse) apiResponse;
            if (PropertyExtractor.TYPE_COOKIE.equals(propertyExtractor.getType())) {
                Optional<HTTPHeader> setCookieHeader = httpApiResponse.getHttpHeaders().stream()
                        .filter(httpHeader -> HttpHeader.SET_COOKIE.asString().equals(httpHeader.getName())).findFirst();
                propertyExtractionInput = setCookieHeader.isPresent() ? setCookieHeader.get().getValue() : null;
            } else {
                propertyExtractionInput = httpApiResponse.getHttpBody();
            }
        }

        PropertyExtractorRunner propertyExtractorRunner = PropertyExtractorRunnerFactory.getInstance().create(
                propertyExtractor, referenceableStringProperties);
        String propertyValue = propertyExtractorRunner.extract(propertyExtractionInput);
        extractedProperties.put(propertyExtractor.getPropertyName(), propertyValue);
    }

    return extractedProperties;
}
 
Example #26
Source File: ProxyServiceImpl.java    From moon-api-gateway with MIT License 5 votes vote down vote up
private boolean checkContentType(HttpFields responseHeaders) {
    if (responseHeaders.contains(HttpHeader.CONTENT_TYPE)) {
        String contentTypeValue = responseHeaders.get(HttpHeader.CONTENT_TYPE);
        return contentTypeValue.split(Constant.CONTENT_TYPE_EXTRACT_DELIMITER)[0]
                .equals(responseInfo.getRequestAccept().split(Constant.CONTENT_TYPE_EXTRACT_DELIMITER)[0]);
    }

    return false;
}
 
Example #27
Source File: CorsBasicAuthenticator.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    HttpServletRequest request = (HttpServletRequest) req;
    String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
    if (!RuntimeUtilities.isNullOrEmpty(credentials)) {
        ThreadContext.put("currentuser:credentials", credentials);
    }

    return super.validateRequest(req, res, mandatory);
}
 
Example #28
Source File: CcuGateway.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Main method for sending a TclRega script and parsing the XML result.
 */
@SuppressWarnings("unchecked")
private synchronized <T> T sendScript(String script, Class<T> clazz) throws IOException {
    try {
        script = StringUtils.trim(script);
        if (StringUtils.isEmpty(script)) {
            throw new RuntimeException("Homematic TclRegaScript is empty!");
        }
        if (logger.isTraceEnabled()) {
            logger.trace("TclRegaScript: {}", script);
        }

        StringContentProvider content = new StringContentProvider(script, config.getEncoding());
        ContentResponse response = httpClient.POST(config.getTclRegaUrl()).content(content)
                .timeout(config.getTimeout(), TimeUnit.SECONDS)
                .header(HttpHeader.CONTENT_TYPE, "text/plain;charset=" + config.getEncoding()).send();

        String result = new String(response.getContent(), config.getEncoding());
        result = StringUtils.substringBeforeLast(result, "<xml><exec>");
        if (logger.isTraceEnabled()) {
            logger.trace("Result TclRegaScript: {}", result);
        }

        return (T) xStream.fromXML(result);
    } catch (Exception ex) {
        throw new IOException(ex.getMessage(), ex);
    }
}
 
Example #29
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 #30
Source File: ProxyServletServiceTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMaybeAppendAuthHeaderWithoutCredentials() throws URISyntaxException {
    Request request = mock(Request.class);
    URI uri = new URI("http://127.0.0.1:8080/content");
    service.maybeAppendAuthHeader(uri, request);
    verify(request, never()).header(any(HttpHeader.class), anyString());
}