RESTClient.java

  1. package org.jbehave.core.io.rest;

  2. import static java.text.MessageFormat.format;

  3. import org.glassfish.jersey.client.ClientConfig;
  4. import org.glassfish.jersey.client.ClientResponse;
  5. import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

  6. import jakarta.ws.rs.client.Client;
  7. import jakarta.ws.rs.client.ClientBuilder;
  8. import jakarta.ws.rs.client.Entity;

  9. /**
  10.  * Provides access to REST resources
  11.  */
  12. @SuppressWarnings("checkstyle:AbbreviationAsWordInName")
  13. public class RESTClient {

  14.     public enum Type {
  15.         JSON, XML
  16.     }

  17.     private static final String APPLICATION_TYPE = "application/{0}";
  18.     private String username;
  19.     private String password;
  20.     private Type type;

  21.     public RESTClient(Type type) {
  22.         this(type, null, null);
  23.     }

  24.     public RESTClient(Type type, String username, String password) {
  25.         this.type = type;
  26.         this.username = username;
  27.         this.password = password;
  28.     }

  29.     public Type getType() {
  30.         return type;
  31.     }

  32.     public String get(String uri) {
  33.         return client().target(uri).request(mediaType(type))
  34.                 .get(ClientResponse.class).getEntity().toString();
  35.     }

  36.     public void put(String uri, String entity) {
  37.         client().target(uri).request(mediaType(type))
  38.                 .put(Entity.entity(entity, mediaType(type)));
  39.     }

  40.     private String mediaType(Type type) {
  41.         return format(APPLICATION_TYPE, type.name().toLowerCase());
  42.     }

  43.     private Client client() {
  44.         ClientConfig clientConfig = new ClientConfig();
  45.         if (username != null) {
  46.             clientConfig.register(HttpAuthenticationFeature.basic(username, password));
  47.         }
  48.         return ClientBuilder.newClient(clientConfig);
  49.     }

  50. }