/**
   * Tests partial Get requests.
   *
   * @throws IOException
   * @throws NoSuchAlgorithmException
   */
  @Test
  public void testGet() throws IOException, NoSuchAlgorithmException {
    Client client = new Client(Protocol.HTTP);

    // Test partial Get.
    Request request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/");
    StringRepresentation rep = new StringRepresentation("0123456789");
    try {
      DigesterRepresentation digester = new DigesterRepresentation(rep);
      // Such representation computes the digest while
      // consuming the wrapped representation.
      digester.exhaust();
      // Set the digest with the computed one
      digester.setDigest(digester.computeDigest());
      request.setEntity(digester);

      Response response = client.handle(request);

      assertEquals(Status.SUCCESS_OK, response.getStatus());
      digester = new DigesterRepresentation(response.getEntity());
      digester.exhaust();
      assertTrue(digester.checkDigest());

      client.stop();
    } catch (Exception e) {
      fail(e.getMessage());
    }
  }
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    String propertyFilePath = args.length > 0 ? args[0] : "jeevlet.properties";

    // Get configuration
    int listenPort =
        Integer.parseInt(ConfigUtils.getProps(propertyFilePath).getProperty(Config.LISTEN_PORT));
    String hostDomain = ConfigUtils.getProps(propertyFilePath).getProperty(Config.HOST_DOMAIN);

    // Prepare the request
    String url = "http://" + hostDomain + ":" + listenPort + "/";
    Request request = new Request(Method.GET, url);
    request.setEntity(Config.STOP_GEONETWORK, MediaType.TEXT_PLAIN);

    // Handle it using an HTTP client connector
    Client client = new Client(Protocol.HTTP);

    try {
      client.start();
      Response response = client.handle(request);
    } catch (Exception e) {
      System.err.println("ERROR: Not running!");
      e.printStackTrace();
    } finally {
      client.stop();
      System.out.println("GeoNetwork shutdown ...");
      System.exit(0);
    }
  }
  /**
   * Tests conditional ranges requests.
   *
   * @throws Exception
   */
  public void testConditionalRanges() throws Exception {
    Client client = new Client(Protocol.HTTP);

    // Test partial Get.
    Request request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testGet");
    Response response = client.handle(request);
    Tag entityTag = response.getEntity().getTag();

    request.setRanges(Arrays.asList(new Range(1, Range.SIZE_MAX)));
    request.getConditions().setRangeTag(entityTag);
    response = client.handle(request);
    assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
    assertEquals("234567890", response.getEntity().getText());
    assertEquals(10, response.getEntity().getSize());
    assertEquals(9, response.getEntity().getAvailableSize());
    assertEquals(1, response.getEntity().getRange().getIndex());
    assertEquals(9, response.getEntity().getRange().getSize());

    entityTag = new Tag(entityTag.getName() + "-test");
    request.setRanges(Arrays.asList(new Range(1, Range.SIZE_MAX)));
    request.getConditions().setRangeTag(entityTag);
    response = client.handle(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("1234567890", response.getEntity().getText());
    client.stop();
  }
Esempio n. 4
0
  public Object start(IApplicationContext ctx) throws Exception {
    log.info("Starting client");
    // A HOSTNAME VERIFIER THAT ACCEPTS EVERY HOSTS
    HostnameVerifier myhostnameverifier =
        new HostnameVerifier() {
          @Override
          public boolean verify(String urlHostName, SSLSession session) {
            return true;
          }
        };

    //
    // start restlet context
    context = new Context();
    context.getAttributes().put("sslContextFactory", new ClientSSLContextFactory());
    context.getAttributes().put("hostnameVerifier", myhostnameverifier);
    List<Protocol> list = new ArrayList<Protocol>();
    list.add(Protocol.HTTPS);
    Client client = new Client(context, list, HttpClientHelper.class.getName());
    context.setClientDispatcher(client);
    client.start();

    Adempiere.startup(true);
    org.compiere.AdempiereClient.main(new String[] {});
    return IApplication.EXIT_OK;
  }
  public Response sendRequest(Request request) throws IOException {
    injectCustomSecurityMechanism(request);

    if (log.isLoggable(Level.FINE)) {
      RestClientLogHelper.logHttpRequest(log, Level.FINE, request);
    }

    Client client = initClient();
    Response response = client.handle(request);

    if (log.isLoggable(Level.FINE)) {
      RestClientLogHelper.logHttpResponse(log, Level.FINE, response);
    }

    if (response.getStatus().isSuccess()) {
      return response;
    } else if (response.getStatus().equals(Status.CLIENT_ERROR_UNAUTHORIZED)) {
      // retry request with additional authentication
      Request retryRequest = createChallengeResponse(response);
      return sendRequest(retryRequest);
    }

    throw new RepositoryException(
        "Encountered error while retrieving http response (HttpStatus: "
            + response.getStatus()
            + ", Body: "
            + response.getEntity().getText()
            + ")");
  }
Esempio n. 6
0
  public static void main(String[] args) throws Exception {
    // Create and configure HTTPS client
    Client client = new Client(new Context(), Protocol.HTTPS);
    Series<Parameter> parameters = client.getContext().getParameters();
    parameters.add("truststorePath", "certs/client-truststore.jks");
    parameters.add("truststorePassword", "password");
    parameters.add("truststoreType", "JKS");

    // Create and configure client resource
    ClientResource clientResource =
        new ClientResource("https://localhost:8183/accounts/chunkylover53/mails/123");
    clientResource.setNext(client);

    // Preemptively configure the authentication credentials
    ChallengeResponse authentication =
        new ChallengeResponse(ChallengeScheme.HTTP_BASIC, "chunkylover53", "pwd");
    clientResource.setChallengeResponse(authentication);

    // Communicate with remote resource
    MailResource mailClient = clientResource.wrap(MailResource.class);
    Mail m = mailClient.retrieve();
    System.out.println("Subject: " + m.getSubject());
    System.out.println("Content: " + m.getContent());

    // Store HTTPS client
    client.stop();
  }
Esempio n. 7
0
 @Override
 public void handle(Request request, Response response) {
   // Update URI of the incoming request
   request.setResourceRef("http://localhost:8182/");
   // Create a basic HTTP client
   Client client = new Client(Protocol.HTTP);
   // Let the client handle the request and response
   client.handle(request, response);
 }
Esempio n. 8
0
 public void handle(Request request, Response response) {
   if (request.getProtocol().equals(Protocol.HTTP)) {
     List<Protocol> protocols = Arrays.asList(Protocol.HTTP);
     String helperClass = HttpClientHelper.class.getName();
     Client client = new Client(null, protocols, helperClass);
     client.handle(request, response);
   } else {
     new Client(request.getProtocol()).handle(request, response);
   }
 };
Esempio n. 9
0
  /**
   * Creates a new helper for a given client connector.
   *
   * @param client The client to help.
   * @param helperClass Optional helper class name.
   * @return The new helper.
   */
  @SuppressWarnings("unchecked")
  public ConnectorHelper<Client> createHelper(Client client, String helperClass) {
    ConnectorHelper<Client> result = null;

    if (client.getProtocols().size() > 0) {
      ConnectorHelper<Client> connector = null;
      for (final Iterator<ConnectorHelper<Client>> iter = getRegisteredClients().iterator();
          (result == null) && iter.hasNext(); ) {
        connector = iter.next();

        if (connector.getProtocols().containsAll(client.getProtocols())) {
          if ((helperClass == null)
              || connector.getClass().getCanonicalName().equals(helperClass)) {
            try {
              result = connector.getClass().getConstructor(Client.class).newInstance(client);
            } catch (Exception e) {
              Context.getCurrentLogger()
                  .log(
                      Level.SEVERE,
                      "Exception during the instantiation of the client connector.",
                      e);
            }
          }
        }
      }

      if (result == null) {
        // Couldn't find a matching connector
        StringBuilder sb = new StringBuilder();
        sb.append("No available client connector supports the required protocols: ");

        for (Protocol p : client.getProtocols()) {
          sb.append("'").append(p.getName()).append("' ");
        }

        sb.append(". Please add the JAR of a matching connector to your classpath.");

        if (Edition.CURRENT == Edition.ANDROID) {
          sb.append(" Then, register this connector helper manually.");
        }

        Context.getCurrentLogger().log(Level.WARNING, sb.toString());
      }
    }

    return result;
  }
Esempio n. 10
0
  public CtssResourceClient(String endpoint) {
    // parse csv output from ctss-resource-v1 service
    Client client = new Client(Protocol.HTTP);
    Response response = client.get(endpoint);

    // Parse the response into a SystemDTO object
    Representation output = response.getEntity();
    InputStream in = null;
    try {
      in = output.getStream();
      byte[] b = new byte[1024];
      String resources = "";
      while ((in.read(b)) > -1) {
        resources += new String(b);
      }
      if (resources != null && !resources.equals("")) {
        for (String line : resources.split("\n")) {
          if (line.startsWith("Site")) continue;
          log.debug("Processing line " + line);
          String[] values = line.split(",");
          if (values.length == 1) continue;
          ComputeDTO sysDto = new ComputeDTO();
          sysDto.setSite(values[0].replaceAll("\"", ""));
          sysDto.setResourceId(values[1].replaceAll("\"", ""));
          sysDto.setTgcdbName(values[2].replaceAll("\"", ""));
          sysDto.setName(
              values[3].replaceAll("\"", "").equals("")
                  ? values[1]
                  : values[3].replaceAll("\"", ""));
          sysDto.setType("compute");
          sysDto.setStatus(Service.UP);
          //				sysDto.setGridftpHostname(values[4].replaceAll("\"", ""));

          ctssSystems.add(sysDto);
        }
      }
    } catch (Exception e) {
      log.debug("Failed to retrieve output from " + endpoint, e);
    } finally {
      try {
        in.close();
      } catch (Exception e) {
        log.error(e);
      }
    }
  }
  @Test
  public void testPutTriple() throws Exception {
    final Client client = new Client(Protocol.HTTP);
    final Reference reference = new Reference("http://localhost/clue/triples");
    reference.setHostPort(port);

    final Request request = new Request(Method.PUT, reference);
    request.setChallengeResponse(getChallengeResponse());

    final Weapon weapon = WeaponEnum.CANDLESTICK.getWeapon();
    final Suspect suspect = SuspectEnum.PEACOCK.getSuspect();
    final Room room = RoomEnum.BILLIARDROOM.getRoom();

    request.setEntity(new JacksonRepresentation<Triple>(new Triple(room, suspect, weapon)));
    System.out.println(request.getEntityAsText());
    client.handle(request);

    assertEquals(323, getRemainingCount());
  }
  /**
   * Tests ranges.
   *
   * @throws Exception
   */
  public void testRanges() throws Exception {
    Client client = new Client(Protocol.HTTP);
    Request request;
    Response response;

    // Test "range" header.
    request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/test?range=0-500");
    request.setRanges(Arrays.asList(new Range(0, 500)));
    response = client.handle(request);
    assertTrue(response.getStatus().isSuccess());
    response.getEntity().exhaust();

    request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/test?range=-500");
    request.setRanges(Arrays.asList(new Range(Range.INDEX_LAST, 500)));
    response = client.handle(request);
    assertTrue(response.getStatus().isSuccess());
    response.getEntity().exhaust();

    request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/test?range=500-");
    request.setRanges(Arrays.asList(new Range(500, Range.SIZE_MAX)));
    response = client.handle(request);
    assertTrue(response.getStatus().isSuccess());
    response.getEntity().exhaust();

    request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/test?range=500-1000");
    request.setRanges(Arrays.asList(new Range(500, 500)));

    response = client.handle(request);
    assertTrue(response.getStatus().isSuccess());
    response.getEntity().exhaust();

    // Multiple ranges are not supported yet.
    // request = new Request(Method.GET, "http://localhost:" + TEST_PORT
    // + "/test?range=500-1000&range=500-");
    // request.setRanges(Arrays.asList(new Range(500, 500), new Range(500,
    // Range.SIZE_MAX)));
    // assertTrue(client.handle(request).getStatus().isSuccess());

    // client.stop();

  }
  public void writeRawData(String path, byte[] data) throws IOException {
    while (path.startsWith("/")) {
      path = path.substring(1);
    }

    Request rr = createRequest(Method.PUT, path);

    ByteArrayRepresentation entity = new ByteArrayRepresentation(MediaType.APPLICATION_XML, data);

    rr.setEntity(entity);

    Response response = client.handle(rr);

    if (!response.getStatus().isSuccess()) {
      throw new IOException("The response was not successful: " + response.getStatus());
    }
  }
  public byte[] readRawData(String path) throws IOException {
    while (path.startsWith("/")) {
      path = path.substring(1);
    }

    Request rr = createRequest(Method.GET, path);

    Response response = client.handle(rr);

    if (response.getStatus().isSuccess() && response.isEntityAvailable()) {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      response.getEntity().write(baos);

      return baos.toByteArray();
    } else if (response.getStatus().equals(Status.CLIENT_ERROR_NOT_FOUND)) {
      return null;
    } else {
      throw new IOException("The response was not successful: " + response.getStatus());
    }
  }
Esempio n. 15
0
  /** Returns a full representation for a given variant. */
  @Override
  public Representation represent(Variant variant) throws ResourceException {

    String endPoint;

    if (version == 1) {
      jsonRequestString =
          "{getMedicationFacts:{criteria:{queryId:\"20100411011010\",\"senderId\":\"Adapter Assembly Service\",\"interactionId\":\"QUPC_IN043100UV\",\"triggerEventCode\":\"QUPC_TE043100UV0\",\"patientId\":\""
              + patientId
              + "\",\"careProvisionCode\":\"HISTMEDLIST\",\"careRecordStartTimePeriod\":\""
              + fromDate
              + "\",\"careRecordEndTimePeriod\":\""
              + toDate
              + "\"}}}";

      endPoint = this.getProperty("JSONPojoFactServiceEndpoint");

    } else {
      jsonRequestString =
          "{\"getMedicationFacts\":{\"criteria\":{\"queryId\":\"20100411011010\",\"senderId\":\"Adapter Assembly Service\",\"interactionId\":\"QUPC_IN043100UV\",\"triggerEventCode\":\"QUPC_TE043100UV01\","
              + "\"careRecordPayload\":{\"patientId\":\""
              + patientId
              + "\",\"careProvisionCode\":\"HISTMEDLIST\",\"careRecordStartTimePeriod\":\""
              + fromDate
              + "\",\"careRecordEndTimePeriod\":\""
              + toDate
              + "\"}}}}";

      endPoint = this.getProperty("JSONPojoFactServiceEndpointV2");
    }

    try {
      Client client = new Client(Protocol.HTTP);
      client.setConnectTimeout(10);

      Request request =
          new Request(
              Method.POST, new Reference(endPoint), new StringRepresentation(jsonRequestString));
      Response response = client.handle(request);

      if (response.getStatus().isSuccess()) {
        String rep = response.getEntity().getText();
        JSONObject jo = new JSONObject(rep);
        Object omf = jo.get("medicationFact");
        if (!(omf instanceof JSONArray)) {
          JSONArray joa = new JSONArray();
          joa.put(omf);
          jo.remove("medicationFact");
          jo.put("medicationFact", joa);
          rep = jo.toString();
        }
        Representation representation = new StringRepresentation(rep, MediaType.APPLICATION_JSON);

        return representation;
      } else {
        throw new ResourceException(
            Status.SERVER_ERROR_INTERNAL,
            "Error during call to JSONPojoFactServiceEndpoint, Status = "
                + response.getStatus().getDescription());
      }
    } catch (ResourceException e) {
      throw e;
    } catch (Exception e) {
      Logger.getLogger(AllergiesResource.class.getName()).log(Level.SEVERE, null, e);
      throw new ResourceException(
          Status.SERVER_ERROR_INTERNAL, "Error calling JSONPojoFactServiceEndpoint", e);
    }
  }
  public void testTemplateFilter() {
    try {
      // Create a temporary directory for the tests
      this.testDir = new File(System.getProperty("java.io.tmpdir"), "TemplateFilterTestCase");
      deleteDir(this.testDir);
      this.testDir.mkdir();

      // Create temporary template files
      // Will be templated
      final File testFileFm1 = new File(this.testDir, "testFm1.txt.fmt");
      FileWriter fw = new FileWriter(testFileFm1);
      fw.write("Method=${m}/Authority=${ra}");
      fw.close();

      // Will not be templated
      final File testFileFm2 = new File(this.testDir, "testFm2.txt");
      fw = new FileWriter(testFileFm2);
      fw.write("Method=${m}/Authority=${ra}");
      fw.close();

      // Will be templated
      final File testFileVl1 = new File(this.testDir, "testVl1.txt.vm");
      fw = new FileWriter(testFileVl1);
      fw.write("Method=${m}/Path=${rp}");
      fw.close();

      // Will not be templated
      final File testFileVl2 = new File(this.testDir, "testVl2.txt");
      fw = new FileWriter(testFileVl2);
      fw.write("Method=${m}/Path=${rp}");
      fw.close();

      // Create a new component
      final Component component = new Component();
      component.getServers().add(Protocol.HTTP, 8182);
      component.getClients().add(Protocol.FILE);

      // Create an application filtered with Freemarker
      final MyFreemakerApplication freemarkerApplication = new MyFreemakerApplication(this.testDir);
      // Create an application filtered with Velocity
      final MyVelocityApplication velocityApplication = new MyVelocityApplication(this.testDir);

      // Attach the applications to the component and start it
      component.getDefaultHost().attach("/freemarker", freemarkerApplication);
      component.getDefaultHost().attach("/velocity", velocityApplication);

      // Now, let's start the component!
      component.start();

      // Allow extensions tunneling
      freemarkerApplication.getTunnelService().setExtensionsTunnel(true);
      velocityApplication.getTunnelService().setExtensionsTunnel(true);
      final Client client = new Client(Protocol.HTTP);
      Response response = client.get("http://localhost:8182/freemarker/" + testFileFm1.getName());
      if (response.isEntityAvailable()) {
        assertEquals(response.getEntity().getText(), "Method=GET/Authority=localhost:8182");
      }
      response = client.get("http://localhost:8182/freemarker/" + testFileFm2.getName());
      assertTrue(response.getStatus().isSuccess());
      if (response.isEntityAvailable()) {
        assertEquals(response.getEntity().getText(), "Method=${m}/Authority=${ra}");
      }

      response = client.get("http://localhost:8182/velocity/" + testFileVl1.getName());
      if (response.isEntityAvailable()) {
        assertEquals(response.getEntity().getText(), "Method=GET/Path=/velocity/testVl1");
      }
      response = client.get("http://localhost:8182/velocity/" + testFileVl2.getName());
      assertTrue(response.getStatus().isSuccess());
      if (response.isEntityAvailable()) {
        assertEquals(response.getEntity().getText(), "Method=${m}/Path=${rp}");
      }
      // Now, let's stop the component!
      component.stop();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * Tests partial Put requests.
   *
   * @throws Exception
   */
  public void testPut() throws Exception {
    if (!SystemUtils.isWindows()) {
      Request request;
      Response response;

      BioUtils.delete(testDir, true);
      Client client = new Client(new Context(), Protocol.HTTP);
      client.getContext().getParameters().add("tracing", "true");

      // PUT on a file that does not exist
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("1234567890"));
      request.setRanges(Arrays.asList(new Range(0, 10)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("1234567890", response.getEntity().getText());

      // Partial PUT on a file, the provided representation overflowed the
      // existing file
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("0000000000"));
      request.setRanges(Arrays.asList(new Range(1, 10)));
      response = client.handle(request);
      System.out.println(response.getStatus() + " / " + response.getStatus().getThrowable());
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10000000000", response.getEntity().getText());

      // Partial PUT on a file that does not exists, the provided range
      // does not start at the 0 index.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai2.txt");
      request.setEntity(new StringRepresentation("0000000000"));
      request.setRanges(Arrays.asList(new Range(1, 10)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      request.setMethod(Method.GET);
      response = client.handle(request);
      assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
      assertEquals("0000000000", response.getEntity().getText());

      // Partial PUT on a file, simple range
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("22"));
      request.setRanges(Arrays.asList(new Range(2, 2)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10220000000", response.getEntity().getText());

      // Partial PUT on a file, the provided representation will be padded
      // at the very end of the file.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("888"));
      request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10220000888", response.getEntity().getText());

      // Partial PUT on a file that does not exist, the range does not
      // specify the range size.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai3.txt");
      request.setEntity(new StringRepresentation("888"));
      request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      request.setMethod(Method.GET);
      response = client.handle(request);
      assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
      assertEquals("888", response.getEntity().getText());

      // Partial PUT on a file, the provided representation will be padded
      // just before the end of the file.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("99"));
      request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10220000998", response.getEntity().getText());

      request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setRanges(Arrays.asList(new Range(3, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
      assertEquals("20000998", response.getEntity().getText());

      BioUtils.delete(testDir, true);
      client.stop();
    }
  }
  /**
   * Tests partial Get requests.
   *
   * @throws Exception
   */
  public void testGet() throws Exception {
    Client client = new Client(Protocol.HTTP);

    // Test partial Get.
    Request request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testGet");
    Response response;

    response = client.handle(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("1234567890", response.getEntity().getText());
    assertEquals(10, response.getEntity().getSize());
    assertEquals(10, response.getEntity().getAvailableSize());

    request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testGet");
    request.setRanges(Arrays.asList(new Range(0, 10)));
    response = client.handle(request);
    assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
    assertEquals("1234567890", response.getEntity().getText());
    assertEquals(10, response.getEntity().getSize());
    assertEquals(10, response.getEntity().getAvailableSize());
    assertEquals(0, response.getEntity().getRange().getIndex());
    assertEquals(10, response.getEntity().getRange().getSize());

    request.setRanges(Arrays.asList(new Range(Range.INDEX_FIRST, 2)));
    response = client.handle(request);
    assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
    assertEquals("12", response.getEntity().getText());
    assertEquals(10, response.getEntity().getSize());
    assertEquals(2, response.getEntity().getAvailableSize());
    assertEquals(0, response.getEntity().getRange().getIndex());
    assertEquals(2, response.getEntity().getRange().getSize());

    request.setRanges(Arrays.asList(new Range(2, 2)));
    response = client.handle(request);
    assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
    assertEquals("34", response.getEntity().getText());
    assertEquals(10, response.getEntity().getSize());
    assertEquals(2, response.getEntity().getAvailableSize());
    assertEquals(2, response.getEntity().getRange().getIndex());
    assertEquals(2, response.getEntity().getRange().getSize());

    request.setRanges(Arrays.asList(new Range(2, 7)));
    response = client.handle(request);
    assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
    assertEquals("3456789", response.getEntity().getText());
    assertEquals(10, response.getEntity().getSize());
    assertEquals(7, response.getEntity().getAvailableSize());
    assertEquals(2, response.getEntity().getRange().getIndex());
    assertEquals(7, response.getEntity().getRange().getSize());

    request.setRanges(Arrays.asList(new Range(Range.INDEX_LAST, 7)));
    response = client.handle(request);
    assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
    assertEquals("4567890", response.getEntity().getText());
    assertEquals(10, response.getEntity().getSize());
    assertEquals(7, response.getEntity().getAvailableSize());
    assertEquals(3, response.getEntity().getRange().getIndex());
    assertEquals(7, response.getEntity().getRange().getSize());

    request.setRanges(Arrays.asList(new Range(2, Range.SIZE_MAX)));
    response = client.handle(request);
    assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
    assertEquals("34567890", response.getEntity().getText());
    assertEquals(10, response.getEntity().getSize());
    assertEquals(8, response.getEntity().getAvailableSize());
    assertEquals(2, response.getEntity().getRange().getIndex());
    assertEquals(8, response.getEntity().getRange().getSize());

    request.setRanges(Arrays.asList(new Range(2, 1000)));
    response = client.handle(request);
    assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
    assertEquals("34567890", response.getEntity().getText());
    assertEquals(10, response.getEntity().getSize());
    assertEquals(8, response.getEntity().getAvailableSize());
    assertEquals(2, response.getEntity().getRange().getIndex());
    assertEquals(8, response.getEntity().getRange().getSize());

    client.stop();
  }