@Override
 public void rerunFacebookCollection(String code) {
   Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
   WebTarget webResource = client.target(fetchMainUrl + "/facebook/rerun?code=" + code);
   Response clientResponse = webResource.request(MediaType.APPLICATION_JSON).get();
   Map<String, String> result = clientResponse.readEntity(Map.class);
 }
  @Test
  public void testCustomerResource() throws Exception {
    System.out.println("*** Create a new Customer ***");
    Customer newCustomer = new Customer();
    newCustomer.setFirstName("Bill");
    newCustomer.setLastName("Burke");
    newCustomer.setStreet("256 Clarendon Street");
    newCustomer.setCity("Boston");
    newCustomer.setState("MA");
    newCustomer.setZip("02115");
    newCustomer.setCountry("USA");

    Response response =
        client
            .target("http://localhost:8080/services/customers")
            .request()
            .post(Entity.xml(newCustomer));
    if (response.getStatus() != 201) throw new RuntimeException("Failed to create");
    String location = response.getLocation().toString();
    System.out.println("Location: " + location);
    response.close();

    System.out.println("*** GET XML Created Customer **");
    String xml =
        client.target(location).request().accept(MediaType.APPLICATION_XML_TYPE).get(String.class);
    System.out.println(xml);

    System.out.println("*** GET JSON Created Customer **");
    String json =
        client.target(location).request().accept(MediaType.APPLICATION_JSON_TYPE).get(String.class);
    System.out.println(json);
  }
Example #3
0
  /**
   * Used for injecting a test client in unit tests
   *
   * @param authenticationType The type of authentication to use in the request
   * @param client A specific client object to use for the request
   */
  protected JerseyClient(
      final ClientFactory.AuthenticationType authenticationType, final Client client) {
    this.client =
        client
            .register(GZipEncoder.class)
            .register(EncodingFilter.class)
            .register(createMoxyJsonResolver());

    switch (authenticationType) {
      case PREEMPTIVE_BASIC:
        client.register(HttpAuthenticationFeature.basicBuilder().build());
        break;

      case NON_PREEMPTIVE_BASIC:
        client.register(HttpAuthenticationFeature.basicBuilder().nonPreemptive().build());
        break;

      case DIGEST:
        client.register(HttpAuthenticationFeature.digest());
        break;

      case NON_PREEMPTIVE_BASIC_DIGEST:
        client.register(HttpAuthenticationFeature.universalBuilder().build());

      case NONE:
      default:
    }
  }
  @POST
  @Path("/save")
  public RewardDTO saveReward(@Context HttpHeaders httpHeaders, RewardDTO reward) {
    /*try
    {
    String path = new File(".").getCanonicalPath();
    }
    catch(Exception e)
            {
    }*/
    String token = httpHeaders.getRequestHeader("X_REST_USER").get(0);
    ClientConfig config = new ClientConfig();
    Client client = ClientBuilder.newClient(config);

    String entity =
        client
            .target(URL_SERVICIO)
            .path(reward.getBuyerId().toString())
            .request(MediaType.APPLICATION_JSON)
            .header("X_REST_USER", token)
            .get(String.class);

    System.out.println(entity);
    JsonParser parser = new JsonParser();
    JsonObject object = (JsonObject) parser.parse(entity);
    JsonElement column = object.get("id");
    String id = column.getAsString();
    System.out.println(id);
    reward.setBuyerId(Long.parseLong(id));
    createReward(reward);
    return reward;
  }
 // when BookResource.getBooks uses:: @RolesAllowed(value={"admin"})
 // Then:: @Test(expected = javax.ws.rs.ForbiddenException.class)
 @Test
 public void testGetAll2() {
   final ClientConfig cc = getClientConfig();
   final Client client = ClientBuilder.newClient(cc);
   final Invocation.Builder invocationBuilder = client.target(BASE_URI).request();
   invocationBuilder.get(Books.class);
 }
Example #6
0
  /**
   * Invokes the given request
   *
   * @param <R> the return type
   * @param request the request to invoke
   * @return the response
   * @throws Exception the exception
   */
  private <R> HttpResponse invoke(HttpRequest<R> request, boolean useNonStrictSSL)
      throws Exception {
    Client client = ClientFactory.create(useNonStrictSSL);
    WebTarget target = client.target(request.getEndpoint()).path(request.getPath());

    if (Boolean.getBoolean(HttpLoggingFilter.class.getName()))
      target.register(new HttpLoggingFilter(Logger.getLogger("os"), 10000));

    target = populateQueryParams(target, request);

    Invocation.Builder invocation = target.request(MediaType.APPLICATION_JSON);
    populateHeaders(invocation, request);

    Entity<?> entity =
        (request.getEntity() == null)
            ? null
            : Entity.entity(request.getEntity(), request.getContentType());
    try {
      if (entity != null) {
        return HttpResponse.wrap(invocation.method(request.getMethod().name(), entity));
      }
      if (HttpMethod.PUT == request.getMethod() || request.hasJson()) {
        return HttpResponse.wrap(
            invocation.method(
                request.getMethod().name(),
                Entity.entity(request.getJson(), ClientConstants.CONTENT_TYPE_JSON)));
      }
      return HttpResponse.wrap(invocation.method(request.getMethod().name()));
    } catch (ProcessingException pe) {
      throw new ConnectionException(pe.getMessage(), 0, pe);
    } catch (ClientErrorException e) {
      throw HttpResponse.mapException(
          e.getResponse().getStatusInfo().toString(), e.getResponse().getStatus(), e);
    }
  }
  @Test
  public void test_creating_cchat_during_customer_signup() {
    Client client = JerseyClientBuilder.createClient();
    HttpAuthenticationFeature feature =
        HttpAuthenticationFeature.basic("*****@*****.**", "password");
    client.register(feature);

    CChat cchat = new CChat("awais-zara");
    List<CChat> cchats = new ArrayList<CChat>();
    cchats.add(cchat);

    Customer customer = new Customer();
    customer.setUsername("*****@*****.**");
    customer.setPassword("password");
    customer.setCchat(cchats);

    Customer customerPersisted =
        client
            .target(String.format(REST_PRODUCT_SERVICE_URL, RULE.getLocalPort()))
            .path(new StringBuilder("/customer").append("/signup").toString())
            .request(MediaType.APPLICATION_JSON)
            .post(Entity.json(customer), Customer.class);

    assertThat(customerPersisted.getId()).isNotNull();
    assertThat(customerPersisted.getCchat().get(0).getId()).isNotNull();
    assertThat(customerPersisted.getCchat().get(0).getUniqueName())
        .isEqualToIgnoringCase("awais-zara");
  }
  private String randomQuote() {
    try {
      ClientConfig clientConfig = new ClientConfig();
      Client client = ClientBuilder.newClient(clientConfig);
      WebTarget service = client.target(getRemoteURI());

      String stringResult =
          service
              .queryParam("method", "getQuote")
              .queryParam("format", "json")
              .queryParam("lang", "en")
              .request()
              .get(String.class)
              .replaceAll("\'", "\\u0027");

      ObjectMapper m = new ObjectMapper();
      HashMap<String, String> result = new HashMap<>();
      result = m.readValue(stringResult, HashMap.class);
      String quote = result.get("quoteText");
      String author = result.get("quoteAuthor");

      return (author.equals("")) ? quote : quote + " (" + author + ")";
    } catch (Exception e) {
      e.printStackTrace();
      return "";
    }
  }
  private Client createClient(
      Environment environment,
      JerseyClientConfiguration configuration,
      String federationName,
      FederatedPeer peer)
      throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException,
          CertificateException {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
    trustManagerFactory.init(initializeTrustStore(peer.getName(), peer.getCertificate()));

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(
        null, trustManagerFactory.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));

    SSLConnectionSocketFactory sslConnectionSocketFactory =
        new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier());
    Registry<ConnectionSocketFactory> registry =
        RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory)
            .build();

    Client client =
        new JerseyClientBuilder(environment)
            .using(configuration)
            .using(registry)
            .build("FederatedClient");

    client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
    client.property(ClientProperties.READ_TIMEOUT, 10000);
    client.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);
    client.register(HttpAuthenticationFeature.basic(federationName, peer.getAuthenticationToken()));

    return client;
  }
  @BeforeClass
  public static void setUp() throws Exception {

    // the first three notes are known
    final NotesDAO notesDAO = NotesDAO.getInstance();
    notesDAO.clearNotes();

    Note note = new Note();
    note.setBody(TEST_BODY + '1');
    notesDAO.addNote(note);

    note = new Note();
    note.setBody(TEST_BODY + '2');
    notesDAO.addNote(note);

    note = new Note();
    note.setBody(TEST_BODY + '3');
    notesDAO.addNote(note);

    // start the server
    server = Main.startServer();
    // create the client
    Client c = ClientBuilder.newClient();

    target = c.target(Main.BASE_URI);
  }
  @DELETE
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  @Path("removerMensaje")
  public RespuestaMensajeDTO removerMensaje(MensajeDTO mensajeDTO) {

    RespuestaMensajeDTO respuestaMensajeDTO = new RespuestaMensajeDTO(0, "OK");

    UsuarioDTO usuarioDTO = new UsuarioDTO();
    usuarioDTO.setCodigo(mensajeDTO.getUsrdesde());

    Client client = ClientBuilder.newClient();
    WebTarget targetMensaje = client.target(servicioObtenerUsuarioSesion);
    RespuestaSeguridadDTO resuSeg =
        targetMensaje
            .request("application/json")
            .post(
                Entity.entity(usuarioDTO, MediaType.APPLICATION_JSON), RespuestaSeguridadDTO.class);

    System.out.println("RESU " + resuSeg.getCodigo());
    System.out.println("RESU " + resuSeg.getMensaje());

    if (resuSeg.getCodigo() == 0) {

      try {

        // Validar si el mensaje existe en el sistema
        Mensaje mensajeRemover = mensajeBeanLocal.encontrarPorId(Mensaje.class, mensajeDTO.getId());

        if (mensajeRemover != null) {

          if (mensajeRemover.getUsrdesde() == mensajeDTO.getUsrdesde()) {
            mensajeBeanLocal.remover(mensajeRemover, mensajeRemover.getId());
          } else {
            respuestaMensajeDTO.setCodigo(4);
            respuestaMensajeDTO.setMensaje(
                "El Mensaje con Id : "
                    + mensajeRemover.getId()
                    + " No pertence al Usuario "
                    + mensajeDTO.getUsrdesde());
          }

        } else {
          respuestaMensajeDTO.setCodigo(1);
          respuestaMensajeDTO.setMensaje("El Mensaje no existe en el sistema");
        }

      } catch (Exception e) {

        respuestaMensajeDTO.setCodigo(2);
        respuestaMensajeDTO.setMensaje("Hubo un error en el sistema");
      }

    } else {
      respuestaMensajeDTO.setCodigo(10);
      respuestaMensajeDTO.setMensaje(resuSeg.getMensaje());
    }

    return respuestaMensajeDTO;
  }
  private static void pedirEstadisticas() {

    System.out.println("Solicitando saldos al server");
    Client client = ClientBuilder.newClient();
    WebTarget target =
        client.target("http://localhost:8080").path("/tp2/apirest/calcular/estadisticas");

    Response response = target.request().get();

    if (response.getStatus() != 200) {
      System.out.println("ERROR - Al solicitar estadísticas - status: " + response.getStatus());
    }
    List<Estadistica> estadisticas = (List<Estadistica>) response.getEntity();
    System.out.println("Se obtuvieron " + estadisticas.size() + " estadísticas");

    for (Estadistica estaditica : estadisticas) {

      System.out.println(
          "UUID: "
              + estaditica.getUuid()
              + " - Créditos: "
              + estaditica.getCreditos()
              + " - Débitos: "
              + estaditica.getDebitos());
    }

    System.out.println("Fin de pedido de estdísticas");
  }
  private static void enviarMovimientos(List<Movimiento> movimientos) {
    System.out.println("Enviando " + movimientos.size() + " movimientos al calculador");
    Client client = ClientBuilder.newClient();

    WebTarget target =
        client.target("http://localhost:8080").path("/tp2/apirest/calcular/registro");

    int cantErrores = 0;
    for (Movimiento movimiento : movimientos) {

      try {
        Response response = target.request().post(Entity.json(movimiento));

        if (response.getStatus() != 200) {
          System.out.println("ERROR - STATUS NO ES 200 AL POSTEAR MOVIMIENTOS");
          cantErrores++;
        }

      } catch (Exception e) {
        e.printStackTrace();
        cantErrores++;
      }
    }

    if (cantErrores != 0) {
      System.out.println("ERROR - Ocurrieron " + cantErrores + " durante el posteo de datos");
    } else {
      System.out.println("OK - posteo de datos realizado con éxito");
    }

    System.out.println("Fin envio movimientos");
  }
  public String uploadImage(Part file) throws IOException {
    String imageURL = null;
    final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
    final StreamDataBodyPart stream = new StreamDataBodyPart("file", file.getInputStream());
    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
    final MultiPart multiPart =
        formDataMultiPart.field("fileName", file.getSubmittedFileName()).bodyPart(stream);
    if (multiPart instanceof FormDataMultiPart) {
      final FormDataMultiPart dataMultiPart = (FormDataMultiPart) multiPart;
      final WebTarget target = client.target(configuration.getFileUploadServiceEP());
      LOGGER.info("Connecting to file service on " + configuration.getFileUploadServiceEP());
      final Response response =
          target
              .request()
              .header(LoginBean.X_JWT_ASSERTION, getJWTToken())
              .post(Entity.entity(dataMultiPart, dataMultiPart.getMediaType()));
      LOGGER.info("Returned from file service " + configuration.getFileUploadServiceEP());
      if (Response.Status.OK.getStatusCode() == response.getStatus()) {
        imageURL = response.readEntity(String.class);
      } else {
        LOGGER.log(
            Level.SEVERE,
            "TXN service return code is  "
                + response.getStatus()
                + " , "
                + "hence can't proceed with the response");
      }
      formDataMultiPart.close();
      dataMultiPart.close();
      return imageURL;
    }

    return imageURL;
  }
  private Client build(
      String name, ExecutorService threadPool, ObjectMapper objectMapper, Validator validator) {
    final Client client =
        ClientBuilder.newClient(buildConfig(name, threadPool, objectMapper, validator));
    client.register(new JerseyIgnoreRequestUserAgentHeaderFilter());

    // Tie the client to server lifecycle
    if (environment != null) {
      environment
          .lifecycle()
          .manage(
              new Managed() {
                @Override
                public void start() throws Exception {}

                @Override
                public void stop() throws Exception {
                  client.close();
                }
              });
    }
    if (configuration.isGzipEnabled()) {
      client.register(new GZipDecoder());
      client.register(new ConfiguredGZipEncoder(configuration.isGzipEnabledForRequests()));
    }

    return client;
  }
Example #16
0
 public static WebTarget getService() {
   ClientConfig config = new ClientConfig();
   Client client = ClientBuilder.newClient(config);
   client.register(JacksonJaxbJsonProvider.class);
   WebTarget service = client.target(getBaseURI());
   return service;
 }
  @Bean
  public static WebTarget client() {

    final Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();

    return client.target("http://localhost:8080/spr-12188");
  }
 public void testErrorHandling() throws Exception {
   ErrorServlet.authError = null;
   Client client = ClientBuilder.newClient();
   // make sure
   Response response = client.target(APP_SERVER_BASE_URL + "/employee-sig/").request().get();
   response.close();
   SAML2ErrorResponseBuilder builder =
       new SAML2ErrorResponseBuilder()
           .destination(APP_SERVER_BASE_URL + "/employee-sig/saml")
           .issuer(AUTH_SERVER_URL + "/realms/demo")
           .status(JBossSAMLURIConstants.STATUS_REQUEST_DENIED.get());
   BaseSAML2BindingBuilder binding = new BaseSAML2BindingBuilder().relayState(null);
   Document document = builder.buildDocument();
   URI uri =
       binding
           .redirectBinding(document)
           .generateURI(APP_SERVER_BASE_URL + "/employee-sig/saml", false);
   response = client.target(uri).request().get();
   String errorPage = response.readEntity(String.class);
   response.close();
   Assert.assertTrue(errorPage.contains("Error Page"));
   client.close();
   Assert.assertNotNull(ErrorServlet.authError);
   SamlAuthenticationError error = (SamlAuthenticationError) ErrorServlet.authError;
   Assert.assertEquals(SamlAuthenticationError.Reason.ERROR_STATUS, error.getReason());
   Assert.assertNotNull(error.getStatus());
   ErrorServlet.authError = null;
 }
Example #19
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet TestServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
    Client client = ClientBuilder.newClient();
    client.register(MyReader.class).register(MyWriter.class);

    WebTarget target =
        client.target(
            "http://"
                + request.getServerName()
                + ":"
                + request.getServerPort()
                + request.getContextPath()
                + "/webresources/endpoint");
    System.out.println("POST request");
    MyObject mo =
        target
            .request()
            .post(
                Entity.entity(new MyObject("Duke", 18), MediaType.APPLICATION_JSON),
                MyObject.class);
    out.println("Received response: " + mo.getName() + ", " + mo.getAge() + "<br><br>");

    out.println("Check server.log for client/server interceptor output.");
    out.println("</body>");
    out.println("</html>");
  }
Example #20
0
  @Test
  public void testGetLegacyPodcasts()
      throws JsonGenerationException, JsonMappingException, IOException {

    ClientConfig clientConfig = new ClientConfig();
    clientConfig.register(JacksonFeature.class);

    Client client = ClientBuilder.newClient(clientConfig);

    WebTarget webTarget =
        client.target("http://localhost:8888/demo-rest-jersey-spring/legacy/podcasts/");

    Builder request = webTarget.request();
    request.header("Content-type", MediaType.APPLICATION_JSON);

    Response response = request.get();
    Assert.assertTrue(response.getStatus() == 200);

    List<Podcast> podcasts = response.readEntity(new GenericType<List<Podcast>>() {});

    ObjectMapper mapper = new ObjectMapper();
    System.out.print(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(podcasts));

    Assert.assertTrue("At least one podcast is present in the LEGACY", podcasts.size() > 0);
  }
  @Before
  public void setUp() {

    RegionCache regionCache = new RegionCache();
    regionCache.clear();
    openStackRegion = new OpenStackRegionImpl();
    Client client = mock(Client.class);
    WebTarget webResource = mock(WebTarget.class);
    builder = mock(Invocation.Builder.class);
    clientResponse = mock(Response.class);
    Response clientResponseAdmin = mock(Response.class);

    // when
    when(webResource.request(MediaType.APPLICATION_JSON)).thenReturn(builder);
    when(builder.accept(MediaType.APPLICATION_JSON)).thenReturn(builder);

    when(client.target(anyString())).thenReturn(webResource);
    openStackRegion.setClient(client);
    systemPropertiesProvider = mock(SystemPropertiesProvider.class);
    openStackRegion.setSystemPropertiesProvider(systemPropertiesProvider);

    String responseJSON =
        "{\"access\": {\"token\": {\"issued_at\": \"2014-01-13T14:00:10.103025\", \"expires\": \"2014-01-14T14:00:09Z\","
            + "\"id\": \"ec3ecab46f0c4830ad2a5837fd0ad0d7\", \"tenant\": { \"description\": null, \"enabled\": true, \"id\": \"08bed031f6c54c9d9b35b42aa06b51c0\","
            + "\"name\": \"admin\" } },         \"serviceCatalog\": []}}}";

    when(builder.post(Entity.entity(anyString(), MediaType.APPLICATION_JSON)))
        .thenReturn(clientResponseAdmin);
    when(clientResponseAdmin.getStatus()).thenReturn(200);
    when(clientResponseAdmin.readEntity(String.class)).thenReturn(responseJSON);
  }
Example #22
0
  public void asyncCallback() {
    final Client client = ClientFactory.newClient();
    Invocation request =
        client.request("http://jaxrs.examples.org/jaxrsApplication/customers/{id}").get();
    request.pathParam("id", 123);

    // invoke a request in background
    client.queue(
        request,
        new InvocationCallback<Customer>() {

          @Override
          public void onComplete(Future<Customer> future) {
            // Do something
          }
        });

    // invoke another request in background
    Future<?> handle =
        request
            .pathParam("id", 456)
            .queue(
                new InvocationCallback<HttpResponse>() {

                  @Override
                  public void onComplete(Future<HttpResponse> future) {
                    // do something
                  }
                });
    handle.cancel(true);
  }
 @Test(expected = javax.ws.rs.NotAuthorizedException.class)
 public void testGetAll() {
   final ClientConfig cc = new ClientConfig();
   final Client client = ClientBuilder.newClient(cc);
   final Invocation.Builder invocationBuilder = client.target(BASE_URI).request();
   invocationBuilder.get(Books.class);
 }
  @Test
  public void call_server() throws Exception {
    String expectedSentence = "Hello Filibuster!";

    Client httpClient = mock(Client.class);
    WebTarget webTarget = mock(WebTarget.class);
    Invocation.Builder builder = mock(Invocation.Builder.class);
    String json = "{\"sound\":\"SGVsbG8gRmlsaWJ1c3RlciE=\"}";

    when(httpClient.target(anyString())).thenReturn(webTarget);
    when(webTarget.path(anyString())).thenReturn(webTarget);
    when(webTarget.queryParam(anyString(), anyString())).thenReturn(webTarget);
    when(webTarget.request(any(MediaType.class))).thenReturn(builder);
    when(builder.get(String.class)).thenReturn(json);

    String host = "localhost";
    int port = 80;
    SpeechClient client = new SpeechClient(httpClient, new ObjectMapper(), host, port);

    SynthesizedSound actual = client.synthesise(expectedSentence);

    assertThat(actual.getSound(), is(expectedSentence.getBytes()));

    verify(httpClient).target("http://localhost:80");
    verify(webTarget).path("synthesize");

    String encoded = Base64.getEncoder().encodeToString(expectedSentence.getBytes("UTF-8"));
    verify(webTarget).queryParam("sentence", encoded);

    verify(webTarget).request(MediaType.APPLICATION_JSON_TYPE);
    verify(builder).get(String.class);
  }
Example #25
0
 protected void testForbiddenImpersonation(String admin, String adminRealm) {
   Client client = createClient(admin, adminRealm);
   WebTarget impersonate = createImpersonateTarget(client);
   Response response = impersonate.request().post(null);
   response.close();
   client.close();
 }
  public static void main(String[] args) {

    URI uriAmazon =
        UriBuilder.fromUri("http://free.apisigning.com/onca/xml")
            .queryParam("Service", "AWSECommerceService")
            .queryParam("AWSAccessKeyId", "AKIAIYNLC7WME6YSY66A")
            .build();
    URI uriSearch = UriBuilder.fromUri(uriAmazon).queryParam("Operation", "ItemSearch").build();
    URI uriSearchBooks = UriBuilder.fromUri(uriSearch).queryParam("SearchIndex", "Books").build();
    Client client = ClientBuilder.newClient();

    URI uriSearchBooksByKeyword =
        UriBuilder.fromUri(uriSearchBooks).queryParam("Keywords", "Java EE 7").build();
    URI uriSearchBooksWithImages =
        UriBuilder.fromUri(uriSearchBooks)
            .queryParam("Condition", "All")
            .queryParam("ResponseGroup", "Images")
            .queryParam("Title", "Java EE 7")
            .build();

    System.out.println(uriSearchBooksByKeyword.toString());
    System.out.println(uriSearchBooksWithImages.toString());

    Response response = client.target(uriSearchBooksByKeyword).request().get();
    System.out.println(response.getStatus());
    response = client.target(uriSearchBooksWithImages).request().get();
    System.out.println(response.getStatus());
  }
  @Test // @Ignore
  public void shouldGetDoctors() throws IOException {

    URI uri = UriBuilder.fromUri("http://localhost/").port(8282).build();

    // Create an HTTP server listening at port 8282
    HttpServer server = HttpServer.create(new InetSocketAddress(uri.getPort()), 0);
    // Create a handler wrapping the JAX-RS application
    HttpHandler handler =
        RuntimeDelegate.getInstance()
            .createEndpoint(new TestApplicationConfig01(), HttpHandler.class);
    // Map JAX-RS handler to the server root
    server.createContext(uri.getPath(), handler);
    // Start the server
    server.start();

    Client client = ClientBuilder.newClient();

    // Valid URIs
    Response response = client.target("http://localhost:8282/doctor").request().get();
    assertEquals(200, response.getStatus());

    System.out.println(response.readEntity(String.class));

    // Stop HTTP server
    server.stop(0);
  }
  public String loadReport() {
    String url =
        "http://localhost:8080/ChuggaChugga/api/report/"
            + firstDate.getTime()
            + "/"
            + secondDate.getTime();

    Client client = ClientBuilder.newClient();
    WebTarget webTarget = client.register(JsonProcessingFeature.class).target(url);
    JsonArray jsonArray = webTarget.request(MediaType.APPLICATION_JSON_TYPE).get(JsonArray.class);

    for (JsonObject jsonObject : jsonArray.getValuesAs(JsonObject.class)) {
      Ticket.Builder ticketBuilder = Ticket.newBuilder();
      ticketBuilder
          .withUserFirstName(jsonObject.getString("userFirstName"))
          .withUserLastName(jsonObject.getString("userLastName"))
          .withTrainName(jsonObject.getString("trainName"))
          .withArrivalDate(jsonObject.getString("arrivalDate"))
          .withDepartureDate(jsonObject.getString("departureDate"))
          .withArrivalStation(jsonObject.getString("arrivalStation"))
          .withDepartureStation(jsonObject.getString("departureStation"))
          .build();

      result.add(ticketBuilder.build());
    }
    return "success";
  }
  public String getProfile(String id) {

    Client client = ClientBuilder.newClient();

    WebTarget target =
        client.target("http://130.237.84.200:8080/community/webapi/users/").path("/" + id);

    UserViewModel user = target.request(MediaType.APPLICATION_JSON).get(UserViewModel.class);

    this.id = id;
    this.username = user.getUsername();
    this.firstname = user.getFirstname();
    this.lastname = user.getLastname();
    this.country = user.getCountry();
    this.city = user.getCity();

    WebTarget logsTarget =
        client.target("http://130.237.84.200:8080/community/webapi/logs").path("/" + id);

    List list =
        client
            .target("http://130.237.84.200:8080/community/webapi/logs")
            .path("/" + id)
            .request(MediaType.APPLICATION_JSON)
            .get(new GenericType<List<LogViewModel>>() {});

    this.logs = list;

    return "profile.xhtml";
  }
  @Override
  public Boolean pushSMS(String collectionCode, SMS sms) {
    try {
      /** Rest call to Fetcher */
      Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();

      WebTarget webResource =
          client.target(
              fetchMainUrl + "/sms/endpoint/receive/" + URLEncoder.encode(collectionCode, "UTF-8"));

      ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();

      Response response =
          webResource
              .request(MediaType.APPLICATION_JSON)
              .post(Entity.json(objectMapper.writeValueAsString(sms)), Response.class);
      if (response.getStatus() != 200) {
        return false;
      } else {
        return true;
      }

    } catch (Exception e) {
      logger.error("Exception while pushing sms", e);
      return false;
    }
  }