| 1 | |
package org.jbehave.core.io.rest; |
| 2 | |
|
| 3 | |
import com.sun.jersey.api.client.Client; |
| 4 | |
import com.sun.jersey.api.client.ClientResponse; |
| 5 | |
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; |
| 6 | |
|
| 7 | |
import static java.text.MessageFormat.format; |
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
public class RESTClient { |
| 13 | |
|
| 14 | 5 | public enum Type { |
| 15 | 1 | JSON, XML |
| 16 | |
}; |
| 17 | |
|
| 18 | |
private static final String APPLICATION_TYPE = "application/{0}"; |
| 19 | |
private String username; |
| 20 | |
private String password; |
| 21 | |
private Type type; |
| 22 | |
|
| 23 | |
public RESTClient(Type type) { |
| 24 | 0 | this(type, null, null); |
| 25 | 0 | } |
| 26 | |
|
| 27 | 7 | public RESTClient(Type type, String username, String password) { |
| 28 | 7 | this.type = type; |
| 29 | 7 | this.username = username; |
| 30 | 7 | this.password = password; |
| 31 | 7 | } |
| 32 | |
|
| 33 | |
public Type getType() { |
| 34 | 0 | return type; |
| 35 | |
} |
| 36 | |
|
| 37 | |
public String get(String uri) { |
| 38 | 0 | return client().resource(uri).accept(format(APPLICATION_TYPE, type.name().toLowerCase())) |
| 39 | |
.get(ClientResponse.class).getEntity(String.class); |
| 40 | |
} |
| 41 | |
|
| 42 | |
public void put(String uri, String entity) { |
| 43 | 0 | client().resource(uri).type(format(APPLICATION_TYPE, type.name().toLowerCase())) |
| 44 | |
.put(ClientResponse.class, entity); |
| 45 | 0 | } |
| 46 | |
|
| 47 | |
private Client client() { |
| 48 | 0 | Client client = Client.create(); |
| 49 | 0 | if (username != null) { |
| 50 | 0 | client.addFilter(new HTTPBasicAuthFilter(username, password)); |
| 51 | |
} |
| 52 | 0 | return client; |
| 53 | |
} |
| 54 | |
|
| 55 | |
} |