public static boolean authenticate() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet get = new HttpGet(Account.getAuthServer());

    get.addHeader("X-Auth-User", Account.getUsername());
    get.addHeader("X-Auth-Key", Account.getApiKey());

    try {
      HttpResponse resp = httpclient.execute(get);

      if (resp.getStatusLine().getStatusCode() == 204) {
        Account.setAuthToken(resp.getFirstHeader("X-Auth-Token").getValue());
        Account.setServerUrl(resp.getFirstHeader("X-Server-Management-Url").getValue());
        Account.setStorageUrl(resp.getFirstHeader("X-Storage-Url").getValue());
        Account.setStorageToken(resp.getFirstHeader("X-Storage-Token").getValue());
        Account.setCdnManagementUrl(resp.getFirstHeader("X-Cdn-Management-Url").getValue());
        return true;
      } else {
        return false;
      }
    } catch (ClientProtocolException cpe) {
      return false;
    } catch (IOException e) {
      return false;
    }
  }
  @Test
  public void testXForwardedSsl() throws Exception {
    setProxyHandler(false, false);
    TestHttpClient client = new TestHttpClient();

    try {
      client.setSSLContext(DefaultServer.getClientSSLContext());
      HttpGet get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/x-forwarded");

      HttpResponse result = client.execute(get);
      Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

      Assert.assertEquals(
          sslPort,
          Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue()));
      Assert.assertEquals(
          "https", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue());
      Assert.assertEquals(
          "localhost", result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue());
      Assert.assertEquals(
          DefaultServer.getDefaultServerAddress().getAddress().getHostAddress(),
          result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue());

    } finally {
      client.getConnectionManager().shutdown();
    }
  }
  @Test
  public void testSingletonService(@ArquillianResource(MyServiceServlet.class) URL baseURL)
      throws IOException, URISyntaxException {

    // URLs look like "http://IP:PORT/singleton/service"
    URI defaultURI = MyServiceServlet.createURI(baseURL, MyServiceActivator.DEFAULT_SERVICE_NAME);
    URI quorumURI = MyServiceServlet.createURI(baseURL, MyServiceActivator.QUORUM_SERVICE_NAME);

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
      HttpResponse response = client.execute(new HttpGet(defaultURI));
      try {
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(NODE_1, response.getFirstHeader("node").getValue());
      } finally {
        HttpClientUtils.closeQuietly(response);
      }

      // Service should be started regardless of whether a quorum was required.
      response = client.execute(new HttpGet(quorumURI));
      try {
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(NODE_1, response.getFirstHeader("node").getValue());
      } finally {
        HttpClientUtils.closeQuietly(response);
      }
    }
  }
  @Test
  @OperateOnDeployment(DEPLOYMENT_1)
  public void testSerialized(@ArquillianResource(SimpleServlet.class) URL baseURL)
      throws IOException, URISyntaxException {

    // returns the URL of the deployment (http://127.0.0.1:8180/distributable)
    URI uri = SimpleServlet.createURI(baseURL);

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
      HttpResponse response = client.execute(new HttpGet(uri));
      try {
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
        Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
      } finally {
        HttpClientUtils.closeQuietly(response);
      }

      response = client.execute(new HttpGet(uri));
      try {
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
        // This won't be true unless we have somewhere to which to replicate
        Assert.assertTrue(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
      } finally {
        HttpClientUtils.closeQuietly(response);
      }
    }
  }
Esempio n. 5
0
  byte[] readBody(HttpResponse httpResponse) throws Exception {
    if (httpResponse == null) return null;
    httpEntity = httpResponse.getEntity();
    if (httpEntity == null) return null;

    Header zipHeader = httpResponse.getFirstHeader("zip");
    boolean zip = zipHeader != null && "true".equals(zipHeader.getValue());

    TimerMonitor timerMonitor = new TimerMonitor(this);
    timerMonitor.startSession();

    contentLengthHeader = httpResponse.getFirstHeader(CONTENT_LENGTH);

    try {
      byte[] bytes = readBody(contentLengthHeader);
      if (zip) bytes = new GZipIO().unzip(bytes);
      if (bytes == null || bytes.length < 1) return bytes;
      readData = bytes.length;
      return decodeResponse(bytes, httpEntity.getContentEncoding());
    } finally {
      if (httpEntity instanceof BasicManagedEntity) {
        BasicManagedEntity entity = (BasicManagedEntity) httpEntity;
        //        System.out.println(" hihi  da thay roi 2 " + entity);
        entity.releaseConnection();
      } else {
        if (httpEntity.getContent() != null) httpEntity.getContent().close();
      }
    }
  }
  @Test
  public void testReqriteHostHeader() throws Exception {
    setProxyHandler(true, false);
    TestHttpClient client = new TestHttpClient();

    try {
      HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/x-forwarded");
      get.addHeader(Headers.X_FORWARDED_FOR.toString(), "50.168.245.32");
      HttpResponse result = client.execute(get);
      Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

      Assert.assertEquals(
          port,
          Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue()));
      Assert.assertEquals(
          "http", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue());
      Assert.assertEquals(
          String.format("localhost:%d", port),
          result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue());
      Assert.assertEquals(
          DefaultServer.getDefaultServerAddress().getAddress().getHostAddress(),
          result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue());

    } finally {
      client.getConnectionManager().shutdown();
    }
  }
Esempio n. 7
0
  @Test
  public void testUpdate() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/001");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    OperationOutcome oo =
        ourCtx.newXmlParser().parseResource(OperationOutcome.class, responseContent);
    assertEquals("OODETAILS", oo.getIssueFirstRep().getDetails().getValue());

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("location").getValue());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("content-location").getValue());
  }
  @Test
  public void testUpdateWithoutConditionalUrl() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/2");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("location").getValue());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("content-location").getValue());

    assertEquals("Patient/2", new IdType(ourLastId).toUnqualified().getValue());
    assertEquals("Patient/2", ourLastIdParam.toUnqualified().getValue());
    assertNull(ourLastConditionalUrl);
  }
Esempio n. 9
0
  // TODO hmmm, overide resource?
  public Representation setRepresentationOf(HttpResponse response) {
    if (response.getFirstHeader("Location") == null) return this;

    Logger.getLogger(Representation.class.getName())
        .log(Level.INFO, "[Header] Location: " + response.getFirstHeader("Location").getValue());
    this.resource = new Resource(response.getFirstHeader("Location").getValue());
    return this;
  }
Esempio n. 10
0
  private void configureAdViewUsingHeadersFromHttpResponse(HttpResponse response) {
    // Print the ad network type to the console.
    Header ntHeader = response.getFirstHeader("X-Networktype");
    if (ntHeader != null) Log.i("MoPub", "Fetching ad network type: " + ntHeader.getValue());

    // Set the redirect URL prefix: navigating to any matching URLs will send us to the browser.
    Header rdHeader = response.getFirstHeader("X-Launchpage");
    if (rdHeader != null) mRedirectUrl = rdHeader.getValue();
    else mRedirectUrl = null;

    // Set the URL that is prepended to links for click-tracking purposes.
    Header ctHeader = response.getFirstHeader("X-Clickthrough");
    if (ctHeader != null) mClickthroughUrl = ctHeader.getValue();
    else mClickthroughUrl = null;

    // Set the fall-back URL to be used if the current request fails.
    Header flHeader = response.getFirstHeader("X-Failurl");
    if (flHeader != null) mFailUrl = flHeader.getValue();
    else mFailUrl = null;

    // Set the URL to be used for impression tracking.
    Header imHeader = response.getFirstHeader("X-Imptracker");
    if (imHeader != null) mImpressionUrl = imHeader.getValue();
    else mImpressionUrl = null;

    // Set the webview's scrollability.
    Header scHeader = response.getFirstHeader("X-Scrollable");
    boolean enabled = false;
    if (scHeader != null) enabled = scHeader.getValue().equals("1");
    setWebViewScrollingEnabled(enabled);

    // Set the width and height.
    Header wHeader = response.getFirstHeader("X-Width");
    Header hHeader = response.getFirstHeader("X-Height");
    if (wHeader != null && hHeader != null) {
      mWidth = Integer.parseInt(wHeader.getValue().trim());
      mHeight = Integer.parseInt(hHeader.getValue().trim());
    } else {
      mWidth = 0;
      mHeight = 0;
    }

    // Set the auto-refresh time. A timer will be scheduled upon ad success or failure.
    Header rtHeader = response.getFirstHeader("X-Refreshtime");
    if (rtHeader != null) {
      mRefreshTimeMilliseconds = Long.valueOf(rtHeader.getValue()) * 1000;
      if (mRefreshTimeMilliseconds < MINIMUM_REFRESH_TIME_MILLISECONDS) {
        mRefreshTimeMilliseconds = MINIMUM_REFRESH_TIME_MILLISECONDS;
      }
    } else mRefreshTimeMilliseconds = 0;

    // Set the allowed orientations for this ad.
    Header orHeader = response.getFirstHeader("X-Orientation");
    mAdOrientation = (orHeader != null) ? orHeader.getValue() : null;
  }
Esempio n. 11
0
  private LoadUrlTaskResult loadAdFromNetwork(String url) throws Exception {
    HttpGet httpget = new HttpGet(url);
    httpget.addHeader("User-Agent", mUserAgent);

    HttpClient httpclient = getAdViewHttpClient();
    mResponse = httpclient.execute(httpget);
    HttpEntity entity = mResponse.getEntity();

    // Anything but a 200 OK is an invalid response.
    if (mResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK
        || entity == null
        || entity.getContentLength() == 0) {
      throw new Exception("MoPub server returned invalid response.");
    }

    // Ensure that the ad type header is valid and not "clear".
    Header atHeader = mResponse.getFirstHeader("X-Adtype");
    if (atHeader == null || atHeader.getValue().equals("clear")) {
      throw new Exception("MoPub server returned no ad.");
    }

    configureAdViewUsingHeadersFromHttpResponse(mResponse);

    // Handle custom event ad type.
    if (atHeader.getValue().equals("custom")) {
      Log.i("MoPub", "Performing custom event.");
      Header cmHeader = mResponse.getFirstHeader("X-Customselector");
      mIsLoading = false;
      return new PerformCustomEventTaskResult(cmHeader);
    }
    // Handle native SDK ad type.
    else if (!atHeader.getValue().equals("html")) {
      Log.i("MoPub", "Loading native ad");
      Header npHeader = mResponse.getFirstHeader("X-Nativeparams");
      if (npHeader != null) {
        mIsLoading = false;
        HashMap<String, String> paramsHash = new HashMap<String, String>();
        paramsHash.put("X-Adtype", atHeader.getValue());
        paramsHash.put("X-Nativeparams", npHeader.getValue());
        Header ftHeader = mResponse.getFirstHeader("X-Fulladtype");
        if (ftHeader != null) paramsHash.put("X-Fulladtype", ftHeader.getValue());
        return new LoadNativeAdTaskResult(paramsHash);
      } else throw new Exception("Could not load native ad; MoPub provided no parameters.");
    }

    // Handle HTML ad.
    InputStream is = entity.getContent();
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = is.read(b)) != -1; ) {
      out.append(new String(b, 0, n));
    }
    return new LoadHtmlAdTaskResult(out.toString());
  }
Esempio n. 12
0
 public static boolean isSupportRange(final HttpResponse response) {
   if (response == null) return false;
   Header header = response.getFirstHeader("Accept-Ranges");
   if (header != null) {
     return "bytes".equals(header.getValue());
   }
   header = response.getFirstHeader("Content-Range");
   if (header != null) {
     String value = header.getValue();
     return value != null && value.startsWith("bytes");
   }
   return false;
 }
  @Test
  @OperateOnDeployment(DEPLOYMENT_2) // For change, operate on the 2nd deployment first
  public void testSessionReplication(
      @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
      @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
      throws IOException, URISyntaxException {

    URI url1 = SimpleServlet.createURI(baseURL1);
    URI url2 = SimpleServlet.createURI(baseURL2);

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
      HttpResponse response = client.execute(new HttpGet(url1));
      try {
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
      } finally {
        HttpClientUtils.closeQuietly(response);
      }

      // Lets do this twice to have more debug info if failover is slow.
      response = client.execute(new HttpGet(url1));
      try {
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
      } finally {
        HttpClientUtils.closeQuietly(response);
      }

      // Lets wait for the session to replicate
      waitForReplication(GRACE_TIME_TO_REPLICATE);

      // Now check on the 2nd server
      response = client.execute(new HttpGet(url2));
      try {
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(3, Integer.parseInt(response.getFirstHeader("value").getValue()));
      } finally {
        HttpClientUtils.closeQuietly(response);
      }

      // Lets do one more check.
      response = client.execute(new HttpGet(url2));
      try {
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(4, Integer.parseInt(response.getFirstHeader("value").getValue()));
      } finally {
        HttpClientUtils.closeQuietly(response);
      }
    }
  }
 private String executeUrlWithAnswer(DefaultHttpClient client, String url, String message)
     throws IOException, InterruptedException {
   int maxWait = GRACE_TIME;
   while (maxWait > 0) {
     HttpResponse response = client.execute(new HttpGet(url));
     try {
       if (response.getStatusLine().getStatusCode() < 400
           || response.getStatusLine().getStatusCode() > 500) {
         assertEquals(200, response.getStatusLine().getStatusCode());
         Header header = response.getFirstHeader("answer");
         if (header != null) {
           return header.getValue();
         }
         throw new AssertionError(
             "assertExecuteUrlWithResult didn't get expected answer from executed url="
                 + url
                 + ", "
                 + message);
       }
     } finally {
       response.getEntity().getContent().close();
     }
     maxWait -= 100;
     Thread.sleep(100);
   }
   throw new AssertionError(
       "assertExecuteUrlWithResult Timed out trying to execute url=" + url + ", " + message);
 }
Esempio n. 15
0
  private void executeRequest(HttpUriRequest request, String url) {
    HttpClient client = new DefaultHttpClient();

    HttpResponse httpResponse;

    try {
      httpResponse = client.execute(request);
      responseCode = httpResponse.getStatusLine().getStatusCode();
      message = httpResponse.getStatusLine().getReasonPhrase();

      HttpEntity entity = httpResponse.getEntity();

      if (entity != null) {

        InputStream instream = entity.getContent();
        Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
          instream = new GZIPInputStream(instream);
        }
        response = convertStreamToString(instream);

        // Closing the input stream will trigger connection release
        instream.close();
      }

    } catch (ClientProtocolException e) {
      client.getConnectionManager().shutdown();
      e.printStackTrace();
    } catch (IOException e) {
      client.getConnectionManager().shutdown();
    }
  }
Esempio n. 16
0
  @Test
  public void testUpdateNoResponse() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.addCodedDiagnosis().addCoding().setCode("AAA");

    String encoded = ourCtx.newXmlParser().encodeResourceToString(dr);
    ourLog.info("OUT: {}", encoded);

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.setEntity(
        new StringEntity(encoded, ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);
    try {
      ourLog.info(IOUtils.toString(status.getEntity().getContent()));
      assertEquals(200, status.getStatusLine().getStatusCode());
      assertEquals(
          "http://localhost:" + ourPort + "/DiagnosticReport/001/_history/002",
          status.getFirstHeader("location").getValue());
    } finally {
      IOUtils.closeQuietly(status.getEntity().getContent());
    }
  }
Esempio n. 17
0
  /** {@inheritDoc} */
  @Override
  public boolean isRedirected(
      final HttpRequest request, final HttpResponse response, final HttpContext context)
      throws ProtocolException {
    if (response == null) {
      throw new IllegalArgumentException("HTTP response may not be null");
    }

    int statusCode = response.getStatusLine().getStatusCode();
    String method = request.getRequestLine().getMethod();
    Header locationHeader = response.getFirstHeader("location");
    switch (statusCode) {
      case HttpStatus.SC_MOVED_TEMPORARILY:
        return (method.equalsIgnoreCase(HttpGet.METHOD_NAME)
                || method.equalsIgnoreCase(HttpPost.METHOD_NAME)
                || method.equalsIgnoreCase(HttpHead.METHOD_NAME))
            && locationHeader != null;
      case HttpStatus.SC_MOVED_PERMANENTLY:
      case HttpStatus.SC_TEMPORARY_REDIRECT:
        return method.equalsIgnoreCase(HttpGet.METHOD_NAME)
            || method.equalsIgnoreCase(HttpHead.METHOD_NAME)
            || method.equalsIgnoreCase(HttpPost.METHOD_NAME);
      case HttpStatus.SC_SEE_OTHER:
        return true;
      default:
        return false;
    } // end of switch
  }
Esempio n. 18
0
 /** Reads the contents of HttpEntity into a byte[]. */
 private byte[] entityToBytes(HttpResponse httpResponse) throws IOException, ServerError {
   //    private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
   HttpEntity entity = httpResponse.getEntity();
   PoolingByteArrayOutputStream bytes =
       new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
   byte[] buffer = null;
   try {
     //            InputStream in = entity.getContent();
     Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
     InputStream in = entity.getContent();
     if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
       in = new GZIPInputStream(in);
     }
     if (in == null) {
       throw new ServerError();
     }
     buffer = mPool.getBuf(1024);
     int count;
     while ((count = in.read(buffer)) != -1) {
       bytes.write(buffer, 0, count);
     }
     return bytes.toByteArray();
   } finally {
     try {
       // Close the InputStream and release the resources by "consuming the content".
       entity.consumeContent();
     } catch (IOException e) {
       // This can happen if there was an exception above that left the entity in
       // an invalid state.
       VolleyLog.v("Error occured when calling consumingContent");
     }
     mPool.returnBuf(buffer);
     bytes.close();
   }
 }
  private Long retrieveLastUpdateDate(ArtifactVersionBean artifactVersionBean) {
    HttpClient httpClient = new DefaultHttpClient();
    String url =
        String.format(
            configurer.getArtifactVersionRepositoryPomUrl(),
            artifactVersionBean.getGroupId().replace(".", "/"),
            artifactVersionBean.getArtifactId(),
            artifactVersionBean.getVersion());
    HttpHead httpHead = new HttpHead(url);
    httpHead.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);

    // The possible errors here are considered as secondary and will not be seen by the user
    // We may want to reconsider it
    try {
      HttpResponse response = httpClient.execute(httpHead);
      Header lastUpdateDate = response.getFirstHeader(LAST_MODIFIED_HEADER);
      if (lastUpdateDate != null) {
        return DateUtil.parseDate(lastUpdateDate.getValue()).getTime();
      }
      LOGGER.error(
          "An error occurred while retrieving the last update date for "
              + artifactVersionBean.getId());
    } catch (Exception e) {
      LOGGER.error(
          "An error occurred while retrieving the last update date for "
              + artifactVersionBean.getId(),
          e);
    }
    return null;
  }
Esempio n. 20
0
  /**
   * Gets the destination of a redirection
   *
   * @return absolute URL of new location; null if not available
   */
  static URI getLocation(HttpRequest request, HttpResponse response, HttpContext context) {
    Header locationHdr = response.getFirstHeader("Location");
    if (locationHdr == null) {
      Log.e(TAG, "Received redirection without Location header, ignoring");
      return null;
    }
    try {
      URI location = URIUtils.parseURI(locationHdr.getValue(), false);

      // some servers don't return absolute URLs as required by RFC 2616
      if (!location.isAbsolute()) {
        Log.w(TAG, "Received invalid redirection to relative URL, repairing");
        URI originalURI = URIUtils.parseURI(request.getRequestLine().getUri(), false);
        if (!originalURI.isAbsolute()) {
          final HttpHost target = HttpClientContext.adapt(context).getTargetHost();
          if (target != null)
            originalURI = org.apache.http.client.utils.URIUtilsHC4.rewriteURI(originalURI, target);
          else return null;
        }
        return originalURI.resolve(location);
      }
      return location;
    } catch (URISyntaxException e) {
      Log.e(TAG, "Received redirection from/to invalid URI, ignoring", e);
    }
    return null;
  }
Esempio n. 21
0
 @Override
 public Message callBlockingMethod(
     @NotNull Descriptors.MethodDescriptor method,
     @Nullable RpcController controller,
     @NotNull Message request,
     @NotNull Message responsePrototype)
     throws ServiceException {
   try {
     final HttpUriRequest httpRequest = createRequest(method, request);
     final HttpResponse response = client.execute(httpRequest);
     if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
       try (final InputStream stream = response.getEntity().getContent()) {
         final Header encoding = response.getFirstHeader(HttpHeaders.CONTENT_ENCODING);
         final Charset charset;
         if (encoding != null && Charset.isSupported(encoding.getValue())) {
           charset = Charset.forName(encoding.getValue());
         } else {
           charset = StandardCharsets.UTF_8;
         }
         return format.read(responsePrototype.toBuilder(), stream, charset).build();
       }
     }
     return null;
   } catch (Exception e) {
     throw new ServiceException(e);
   }
 }
Esempio n. 22
0
  public static void headerRequest() {
    try {

      HttpClient client = HttpClientBuilder.create().build();
      HttpGet request = new HttpGet("http://mkyong.com");
      HttpResponse response = client.execute(request);

      System.out.println("Printing Response Header...\n");

      Header[] headers = response.getAllHeaders();
      for (Header header : headers) {
        System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue());
      }

      System.out.println("\nGet Response Header By Key ...\n");
      String server = response.getFirstHeader("Server").getValue();
      if (server == null) {
        System.out.println("Key 'Server' is not found!");
      } else {
        System.out.println("Server - " + server);
      }
      System.out.println("\n Done");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 23
0
 /**
  * 获取跳转路径
  *
  * @param response
  * @return
  */
 public String getRedirectLocation(HttpResponse response) {
   Header locationHeader = response.getFirstHeader("Location");
   if (locationHeader == null) {
     return null;
   }
   return locationHeader.getValue();
 }
    @Override
    public Result<T> list() throws EvrythngException {

      if (getCommand().getMethod() != Method.GET) {
        throw new EvrythngClientException("The list() method is only available for GET requests.");
      }

      logger.debug("Call list. For type : {}", getCommand().getResponseType().getType());

      // Issue the command "manually" to get the response object.
      TypedResponseWithEntity<T> bundle = getCommand().bundle();
      HttpResponse response = bundle.response();
      Utils.assertStatus(response, getCommand().getExpectedResponseStatus());
      T ret = bundle.entity();

      // Parse the total result count.
      Header header = response.getFirstHeader(ApiConfiguration.HTTP_HEADER_RESULT_COUNT);
      long n;
      if (header == null) {
        throw new EvrythngClientException(
            "The response contains no " + ApiConfiguration.HTTP_HEADER_RESULT_COUNT + " header.");
      }
      try {
        n = Long.parseLong(header.getValue());
      } catch (NumberFormatException e) {
        throw new EvrythngClientException(
            "The response's "
                + ApiConfiguration.HTTP_HEADER_RESULT_COUNT
                + " header could not be parsed.");
      }
      logger.debug("Total number of items: {}", n);

      return new Result<>(ret, n);
    }
Esempio n. 25
0
  @Test
  public void testUpdateWithVersion() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.getIdentifier().setValue("001");

    HttpPut httpPut = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPut.addHeader("Content-Location", "/DiagnosticReport/001/_history/004");
    httpPut.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPut);
    IOUtils.closeQuietly(status.getEntity().getContent());

    // String responseContent =
    // IOUtils.toString(status.getEntity().getContent());
    // ourLog.info("Response was:\n{}", responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/DiagnosticReport/001/_history/002",
        status.getFirstHeader("Location").getValue());
  }
Esempio n. 26
0
  @RequestMapping(value = "/kkn1234/create", method = RequestMethod.POST)
  public String formSubmit(@ModelAttribute User user, Model model)
      throws MalformedURLException, IOException {
    model.addAttribute("user", user);
    HttpPost post =
        new HttpPost(
            "http://ec2-52-4-138-196.compute-1.amazonaws.com/magento/index.php/customer/account/createpost/");
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient =
        HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("firstname", user.getFirstName()));
    nameValuePairs.add(new BasicNameValuePair("lastname", user.getLastName()));
    nameValuePairs.add(new BasicNameValuePair("email", user.getEmail()));
    nameValuePairs.add(new BasicNameValuePair("password", user.getPassword()));
    nameValuePairs.add(new BasicNameValuePair("confirmation", user.getConfirmation()));

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(post);
    response = httpclient.execute(post);
    System.out.println("Status code is " + response.getStatusLine().getStatusCode());
    System.out.println(response.toString());
    System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++");
    System.out.println(response.getFirstHeader("Location"));
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
    EntityUtils.consume(response.getEntity());

    /*File newTextFile = new File("C:\\Users\\Kris\\Desktop\\temp.html");
    FileWriter fileWriter = new FileWriter(newTextFile);
    fileWriter.write(response.toString());
    fileWriter.close();*/
    return "result";
  }
 protected void ssoLogin1(SimpleObject context) {
   Request req1 = ContextUtil.getRequest(context);
   Integer scode = (Integer) req1.getExtra(Request.STATUS_CODE);
   if (HttpUtil.isMovedStatusCode(scode)) {
     HttpResponse resp = ContextUtil.getResponse(context);
     Header h1 = resp.getFirstHeader("Location");
     String nexturl = h1.getValue();
     if (nexturl == null) {
       logger.error("Error : No Redirect URL");
     } else {
       Request req = new Request(nexturl);
       req.setCharset(UAM_CHAR_SET);
       req.addObjservers(
           new AbstractProcessorObserver(util, WaringConstaint.ZGDX_7) {
             @Override
             public void afterRequest(SimpleObject context) {
               ssoLogin1(context);
             }
           });
       spider.addRequest(req);
     }
   } else {
     endSSOLogin(context);
   }
 }
 protected void parseLoginPage(SimpleObject context, final String prefix, final String phone) {
   Request req1 = ContextUtil.getRequest(context);
   Integer scode = (Integer) req1.getExtra(Request.STATUS_CODE);
   // DebugUtil.printCookieData(ContextUtil.getCookieStore(context), null);
   if (HttpUtil.isMovedStatusCode(scode)) {
     HttpResponse resp = ContextUtil.getResponse(context);
     Header h1 = resp.getFirstHeader("Location");
     String nexturl = h1.getValue();
     if (nexturl == null) {
       logger.error("Error : No Redirect URL");
     } else {
       nexturl = fixedFullUrl(nexturl);
       Request req = new Request(nexturl.replaceAll(" ", "%20"));
       req.setCharset(UAM_CHAR_SET);
       req.putHeader("Referer", "http://www.189.cn/dqmh/login/loginJT.jsp");
       req.addObjservers(
           new AbstractProcessorObserver(util, WaringConstaint.ZGDX_2) {
             @Override
             public void afterRequest(SimpleObject context) {
               parseLoginPage(context, prefix, phone);
             }
           });
       spider.addRequest(req);
     }
   } else {
     if (prefix != null) {
       // com.lkb.debug.DebugUtil.printCookieData(ContextUtil.getCookieStore(context), null);
       saveVerifyImage(context, prefix, phone);
     } else {
       parseLoginStep2(context);
     }
   }
 }
Esempio n. 29
0
  @Override
  public void backchannelLogout(UserSessionModel userSession, ClientSessionModel clientSession) {
    ClientModel client = clientSession.getClient();
    SamlClient samlClient = new SamlClient(client);
    String logoutUrl = getLogoutServiceUrl(uriInfo, client, SAML_POST_BINDING);
    if (logoutUrl == null) {
      logger.warnv(
          "Can't do backchannel logout. No SingleLogoutService POST Binding registered for client: {1}",
          client.getClientId());
      return;
    }
    SAML2LogoutRequestBuilder logoutBuilder = createLogoutRequest(logoutUrl, clientSession, client);

    String logoutRequestString = null;
    try {
      JaxrsSAML2BindingBuilder binding = createBindingBuilder(samlClient);
      logoutRequestString = binding.postBinding(logoutBuilder.buildDocument()).encoded();
    } catch (Exception e) {
      logger.warn("failed to send saml logout", e);
      return;
    }

    HttpClient httpClient = session.getProvider(HttpClientProvider.class).getHttpClient();
    for (int i = 0; i < 2; i++) { // follow redirects once
      try {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(
            new BasicNameValuePair(GeneralConstants.SAML_REQUEST_KEY, logoutRequestString));
        formparams.add(
            new BasicNameValuePair("BACK_CHANNEL_LOGOUT", "BACK_CHANNEL_LOGOUT")); // for Picketlink
        // todo remove
        // this
        UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
        HttpPost post = new HttpPost(logoutUrl);
        post.setEntity(form);
        HttpResponse response = httpClient.execute(post);
        try {
          int status = response.getStatusLine().getStatusCode();
          if (status == 302 && !logoutUrl.endsWith("/")) {
            String redirect = response.getFirstHeader(HttpHeaders.LOCATION).getValue();
            String withSlash = logoutUrl + "/";
            if (withSlash.equals(redirect)) {
              logoutUrl = withSlash;
              continue;
            }
          }
        } finally {
          HttpEntity entity = response.getEntity();
          if (entity != null) {
            InputStream is = entity.getContent();
            if (is != null) is.close();
          }
        }
      } catch (IOException e) {
        logger.warn("failed to send saml logout", e);
      }
      break;
    }
  }
Esempio n. 30
-1
  @Test
  public void testGetAndCheckKey() throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://*****:*****@gmail.com"));
    nvps.add(new BasicNameValuePair("password", "Purbrick7"));
    post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    HttpResponse response = httpClient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
    HttpEntity entity = response.getEntity();
    String responseContent = IOUtils.toString(entity.getContent());
    System.out.println(response.getFirstHeader("Content-Type"));
    System.out.println(responseContent);

    JSONObject jsonObj = (JSONObject) new JSONParser().parse(responseContent);

    HttpPost post2 = new HttpPost("http://*****:*****@gmail.com"));
    nvps2.add(new BasicNameValuePair("authKey", (String) jsonObj.get("authKey")));
    post2.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8));

    HttpResponse response2 = httpClient.execute(post2);
    assertEquals(200, response2.getStatusLine().getStatusCode());
  }