com.welemski.gobbler.Goblet Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of gobbler Show documentation
Show all versions of gobbler Show documentation
Gobbler is collection of convenience java classes to aid in consuming web services
The newest version!
/*
* The MIT License
*
* Copyright 2016 Lemuel Raganas.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.welemski.gobbler;
import com.welemski.wrench.delegate.ObjectDelegate;
import com.welemski.exception.HTTPBadRequestException;
import com.welemski.exception.HTTPForbiddenException;
import com.welemski.exception.HTTPMethodNotAllowedException;
import com.welemski.exception.HTTPNotFoundException;
import com.welemski.exception.HTTPServiceUnavailableException;
import com.welemski.exception.HTTPUnauthorizedException;
import com.welemski.exception.InternalErrorException;
import com.welemski.gobbler.delegate.AfterRequest;
import com.welemski.gobbler.delegate.BeforeRequest;
import com.welemski.gobbler.delegate.BuildURI;
import com.welemski.gobbler.delegate.ModifyHttpClient;
import com.welemski.gobbler.delegate.ResponseMaper;
import com.welemski.wrench.delegate.Delegable;
import com.welemski.wrench.delegate.Delegate;
import com.welemski.wrench.delegate.ErrorDelegate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
/**
* Convenience class for performing GET/POST request.
*
* @author welemski
*/
public class Goblet extends Delegable implements Chalice {
public static String kURISyntaxExceptionDelegate = "URISyntaxExceptionDelegate";
public static String kIOExceptionDelegate = "IOExceptionDelegate";
public static String kInterruptedExceptionDelegate = "InterruptedExceptionDelegate";
public static String kHTTPBadRequestException = "HTTPBadRequestException";
public static String kHTTPUnauthorizedException = "HTTPUnauthorizedException";
public static String kHTTPForbiddenException = "HTTPForbiddenException";
public static String kHTTPNotFoundException = "HTTPNotFoundException";
public static String kHTTPMethodNotAllowedException = "HTTPMethodNotAllowedException";
public static String kHTTPServiceUnavailableException = "kHTTPServiceUnavailableException";
public static String kInternalErrorException = "InternalErrorException";
public static String kUnsupportedEncodingException = "UnsupportedEncodingException";
public static String kAfterRequest = "AfterRequest";
public static String kBeforeRequest = "BeforeRequest";
public static String kBuildURI = "BuildURI";
public static String kModifyHttpClient = "ModifyHttpClient";
public static String kMapResponse = "MapResponse";
protected long timeout = 0;
protected String protocol = "http"; // Protocol to use
protected String host = "localhost"; // Server/domain
protected int port = 80; // Port to use
protected String method = "get";
protected String path = null;
protected String username = null;
protected String password = null;
protected boolean proxyRequired = false;
protected String proxyHost = null;
protected int proxyPort = 0;
protected String proxyUsername = null;
protected String proxyPassword = null;
protected String language = "en";
protected Map parameters = new HashMap<>();
protected List errors = new ArrayList<>();
protected GobletHeader headers = new GobletHeader();
protected HttpEntity httpEntity = null;
protected GobletResponse gobletResponse = new GobletResponse(404, "");
protected CloseableHttpClient httpClient = null;
protected ObjectDelegate didSend = null;
protected ObjectDelegate didEnd = null;
protected ErrorDelegate didError = null;
/**
* Creates a new Goblet class.
*/
public Goblet() {
}
/**
* Creates a new Goblet class.
*
* @param protocol the setProtocol to use: http|https
* @param host the server domain name
* @param port Port to use
*/
public Goblet(String protocol, String host, int port) {
this.protocol = protocol;
this.host = host;
this.port = port;
this.gobletResponse.setStatusCode(400);
}
public Goblet(String protocol, String host, int port, String path) {
this.protocol = protocol;
this.host = host;
this.port = port;
this.path = path;
this.gobletResponse.setStatusCode(400);
}
public Goblet(String fullUrlBasePath) {
try {
URIBuilder urib = new URIBuilder(fullUrlBasePath);
this.protocol = urib.getScheme();
this.host = urib.getHost();
this.port = urib.getPort();
this.path = urib.getPath();
this.gobletResponse.setStatusCode(400);
} catch (URISyntaxException ex) {
if (this.didError != null) {
this.didError.delegate(null, ex);
}
}
}
/**
* A helper methods to perform stuffs before the request happens, before the
* URL is even generated but the HttpClient is already initialized. Useful
* if you want to do custom configuration without the need to implement
* {@link Chalice Chalice} class, you just need to extends from this class.
*
* If you want to perform stuffs before the request happens without
* extending from this class, just add a
* {@link ObjectDelegate ObjectDelegate} implementation
*/
protected void beforeRequest() {
Delegate delegate = this.getDelegate(kBeforeRequest);
if (delegate != null) {
((BeforeRequest) delegate).delegate(this);
}
}
/**
* A helper methods to perform stuffs after the request happens. Useful if
* you want to do custom configuration without the need to implement
* {@link Chalice Chalice} class, you just need to extends from this class.
*
* If you want to perform stuffs after the request happens without extending
* from this class, just add a {@link ObjectDelegate ObjectDelegate}
* implementation
*/
protected void afterRequest() {
Delegate delegate = this.getDelegate(kAfterRequest);
if (delegate != null) {
((AfterRequest) delegate).delegate(this);
}
}
protected URI hostToUri(String host){
try {
URI uri = new URI(host);
if(uri.getHost() == null){
return null;
}
return uri;
} catch (URISyntaxException ex) {
if (this.didError != null) {
this.didError.delegate(this, ex);
}
return null;
}
}
protected void queryToParameters(String queryString){
this.parameters.clear();
String[] queries = queryString.split("&");
for(String query: queries){
String[] kvs = query.split("=");
this.parameters.put(kvs[0], kvs[1]);
}
}
/**
* Sets credentials to perform authorized only requests to the host/server
* web service.
*
* @param username The username used for performing basic authentication
* @param password The password used for performing basic authentication
* @return {@link Goblet Goblet}
*/
@Override
public Goblet setCredentials(String username, String password) {
this.username = username;
this.password = password;
return this;
}
/**
* Headers will be appended when performing http/https client request.
*
* @param name Header key used
* @param value Header value
* @return {@link Goblet Goblet}
*/
@Override
public Goblet setHeader(String name, String value) {
this.headers.put(name, value);
return this;
}
@Override
public Goblet setHeaders(Map keyValues) {
this.headers.putAll(headers);
return this;
}
@Override
public GobletHeader getHeaders() {
return this.headers;
}
/**
* Sets the setProtocol.
*
* @param protocol http|https
* @return {@link Goblet Goblet}
*/
@Override
public Goblet setProtocol(String protocol) {
this.protocol = protocol;
return this;
}
/**
* Set's the server host/domain
*
* Supports the following format:
* http://localhost:8080/path/to/my/page
* localhost:8080/path/to/my/page
* localhost/path/to/my/page
*
* @param host The host to connect to
* @return {@link Goblet Goblet }
*/
@Override
public Goblet setHost(String host) {
if (host == null || "".equals(host.trim())) {
return this;
}
URI uri = this.hostToUri(host);
if(uri == null){
uri = this.hostToUri(this.protocol.concat("://").concat(host));
}
if(uri != null){
this.host = uri.getHost();
this.port = uri.getPort() > 0 ? uri.getPort() : this.port;
this.protocol = uri.getScheme() != null ? uri.getScheme() : this.protocol;
this.path = uri.getPath() != null ? uri.getPath() : this.path;
if(uri.getQuery() != null){
this.queryToParameters(uri.getQuery());
}
return this;
}
if (host.contains(":")) {
String[] uris = host.split(":");
this.host = uris[0];
// Retrieve the port
String[] pathsWithPort = uris[1].split("/");
this.port = Integer.parseInt(pathsWithPort[0]);
// Retrieve paths
if(pathsWithPort.length >= 2){
String[] paths = new String[pathsWithPort.length - 1];
System.arraycopy(pathsWithPort, 1, paths, 0, paths.length);
this.path = "/".concat(String.join("/", paths));
}
return this;
}
if(host.contains("/")){
String[] pathsWithHost = host.split("/");
this.host = pathsWithHost[0];
// Retreive paths
if(pathsWithHost.length >= 2){
String[] paths = new String[pathsWithHost.length - 1];
System.arraycopy(pathsWithHost, 1, paths, 0, paths.length);
this.path = "/".concat(String.join("/",paths));
}
return this;
}
this.host = host;
return this;
}
/**
* Sets the port to use.
*
* @param port port number
* @return {@link Goblet Goblet}
*/
@Override
public Goblet setPort(int port) {
this.port = port;
return this;
}
/**
* The relative path
*
* @param path a path
* @return {@link Goblet Goblet}
*/
@Override
public Goblet setPath(String path) {
if(path == null){
this.path = path;
return this;
}
if(path.contains("?")){
String[] pathWithQuery = path.split("\\?");
this.path = pathWithQuery[0];
this.queryToParameters(pathWithQuery[1]);
return this;
}
this.path = path;
return this;
}
/**
* The type of request: "get|post|delete|put|head"
*
* @param method request type
* @return {@link Goblet Goblet}
*/
@Override
public Goblet setMethod(String method) {
this.method = method;
return this;
}
@Override
public Goblet setProxyHost(String host) {
URI uri = this.hostToUri(host);
if(uri != null){
this.proxyHost = uri.getHost();
this.proxyPort = uri.getPort();
return this;
}
if(host.contains(":")){
String[] hosts = host.split(":");
this.proxyHost = hosts[0];
this.proxyPort = Integer.parseInt(hosts[1]);
return this;
}
this.proxyHost = host;
return this;
}
@Override
public Goblet setProxyPort(int port) {
this.proxyPort = port;
return this;
}
@Override
public Goblet setProxyRequired(boolean bool) {
this.proxyRequired = bool;
return this;
}
/**
*
* @param name parameter name
* @param value parameter value
* @return {@link Goblet Goblet}
*/
@Override
public Goblet setParameter(String name, String value) {
this.parameters.put(name, value);
return this;
}
@Override
public Goblet setParameters(Map keyValues) {
keyValues.forEach((String key, String value) -> {
this.parameters.put(key, value);
});
return this;
}
/**
* @return the setProtocol
*/
@Override
public String getProtocol() {
return protocol;
}
/**
* @return the host
*/
@Override
public String getHost() {
return host;
}
/**
* @return the port
*/
@Override
public int getPort() {
return port;
}
@Override
public String getPath() {
return this.path;
}
/**
* @return the method
*/
@Override
public String getMethod() {
return method;
}
/**
* @return {@link String String}
*/
@Override
public String getUsername() {
return username;
}
/**
* @return {@link String String}
*/
@Override
public String getPassword() {
return password;
}
/**
* @return the proxyRequired
*/
@Override
public boolean isProxyRequired() {
return proxyRequired;
}
/**
* @return the proxyHost
*/
@Override
public String getProxyHost() {
return proxyHost;
}
/**
* @return the proxyPort
*/
@Override
public int getProxyPort() {
return proxyPort;
}
/**
* @return the language
*/
@Override
public String getLanguage() {
return language;
}
@Override
public List errors() {
return this.errors;
}
@Override
public Goblet didSend(ObjectDelegate didSend) {
this.didSend = didSend;
return this;
}
@Override
public Goblet didEnd(ObjectDelegate didEnd) {
this.didEnd = didEnd;
return this;
}
@Override
public Goblet didError(ErrorDelegate didError) {
this.didError = didError;
return this;
}
/**
* Performs gobble/get request. Use this method if you want to handle
* response errors
*
* @return boolean TRUE | FALSE
*/
@Override
public boolean gobble() {
if (this.didSend != null) {
this.didSend.delegate(this);
}
if ("post".equalsIgnoreCase(this.getMethod().trim())) {
return this.sendPostRequest();
}
if ("put".equalsIgnoreCase(this.getMethod().trim())) {
return this.sendPutRequest();
}
if ("delete".equalsIgnoreCase(this.getMethod().trim())) {
return this.sendDeleteRequest();
}
if ("head".equalsIgnoreCase(this.getMethod().trim())) {
return this.sendHeadRequest();
}
// Default: get
return this.sendGetRequest();
}
/**
* Performs send/get request, auto check response and throws appropriate
* error.
*
* Designed to be inside a try-catch block. A convenience class
* {@link GobletResponseSurrogate GobletResponseSurrogate} is specifically
* designed for this method do the all the dirty works in handling errors.
* All you need to do is process what is being returned.
*
* @throws com.welemski.exception.HTTPBadRequestException HTTPBadRequestException
* @throws com.welemski.exception.HTTPForbiddenException HTTPForbiddenException
* @throws com.welemski.exception.HTTPMethodNotAllowedException HTTPMethodNotAllowedException
* @throws com.welemski.exception.HTTPNotFoundException HTTPNotFoundException
* @throws com.welemski.exception.HTTPServiceUnavailableException HTTPServiceUnavailableException
* @throws com.welemski.exception.HTTPUnauthorizedException HTTPUnauthorizedException
* @throws com.welemski.exception.InternalErrorException InternalErrorException
* @return boolean TRUE | FALSE
*/
public boolean gulp() throws HTTPBadRequestException, HTTPForbiddenException, HTTPMethodNotAllowedException, HTTPNotFoundException, HTTPServiceUnavailableException, HTTPUnauthorizedException, InternalErrorException, Exception {
boolean success = this.gobble();
if (!success || this.gobletResponse.getStatusCode() != 200) {
switch (this.gobletResponse.getStatusCode()) {
case 400: {
// Bad request
HTTPBadRequestException ex = new HTTPBadRequestException();
this.invokeErrorDelegate(kHTTPBadRequestException, this, ex);
throw ex;
}
case 401: {
// Unauthorized
HTTPUnauthorizedException ex = new HTTPUnauthorizedException();
this.invokeErrorDelegate(kHTTPUnauthorizedException, this, ex);
throw ex;
}
case 403: {
// Forbidden
HTTPForbiddenException ex = new HTTPForbiddenException();
this.invokeErrorDelegate(kURISyntaxExceptionDelegate, this, ex);
throw ex;
}
case 404: {
// Not found
HTTPNotFoundException ex = new HTTPNotFoundException();
this.invokeErrorDelegate(kHTTPNotFoundException, this, ex);
throw ex;
}
case 405: {
// Method not allowed
HTTPMethodNotAllowedException ex = new HTTPMethodNotAllowedException();
this.invokeErrorDelegate(kHTTPMethodNotAllowedException, this, ex);
throw ex;
}
case 500: {
// Internal Error
InternalErrorException ex = new InternalErrorException();
this.invokeErrorDelegate(kInternalErrorException, this, ex);
throw ex;
}
case 503: {
// Service unavailable
HTTPServiceUnavailableException ex = new HTTPServiceUnavailableException();
this.invokeErrorDelegate(kHTTPServiceUnavailableException, this, ex);
throw ex;
}
default: {
// Unknown internal error
InternalErrorException ex = new InternalErrorException();
this.invokeErrorDelegate(kInternalErrorException, this, ex);
throw ex;
}
}
}
return true;
}
protected boolean sendGetRequest() {
try {
httpClient = this.createHttpClient();
this.beforeRequest();
URI uri = this.createURI();
HttpGet httpGet = new HttpGet(uri);
this.headers.forEach(httpGet::setHeader);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
String content = getResponseContent(httpResponse);
this.gobletResponse.setContent(content);
this.gobletResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
this.gobletResponse.setHttpResponse(httpResponse);
httpClient.close();
if (this.didEnd != null) {
this.didEnd.delegate(this);
}
this.afterRequest();
return true;
} catch (URISyntaxException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(400);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kURISyntaxExceptionDelegate, this, ex);
return false;
} catch (IOException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(500);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kIOExceptionDelegate, this, ex);
return false;
} catch (InterruptedException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(500);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kInterruptedExceptionDelegate, this, ex);
return false;
}
}
protected boolean sendPostRequest() {
try {
httpClient = this.createHttpClient();
this.beforeRequest();
URI uri = this.createURI();
HttpPost httpPost = new HttpPost(uri);
if (this.httpEntity != null) {
httpPost.setEntity(httpEntity);
}
this.headers.forEach(httpPost::setHeader);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
String content = getResponseContent(httpResponse);
this.gobletResponse.setContent(content);
this.gobletResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
this.gobletResponse.setHttpResponse(httpResponse);
httpClient.close();
if (this.didEnd != null) {
this.didEnd.delegate(this);
}
this.afterRequest();
return true;
} catch (URISyntaxException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(400);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kURISyntaxExceptionDelegate, this, ex);
return false;
} catch (IOException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(500);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kIOExceptionDelegate, this, ex);
return false;
} catch (InterruptedException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(500);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kInterruptedExceptionDelegate, this, ex);
return false;
}
}
protected boolean sendPutRequest() {
try {
httpClient = this.createHttpClient();
this.beforeRequest();
URI uri = this.createURI();
HttpPut httpPut = new HttpPut(uri);
if (this.httpEntity != null) {
httpPut.setEntity(httpEntity);
}
this.headers.forEach(httpPut::setHeader);
CloseableHttpResponse httpResponse = httpClient.execute(httpPut);
String content = getResponseContent(httpResponse);
this.gobletResponse.setContent(content);
this.gobletResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
this.gobletResponse.setHttpResponse(httpResponse);
httpClient.close();
if (this.didEnd != null) {
this.didEnd.delegate(this);
}
this.afterRequest();
return true;
} catch (URISyntaxException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(400);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kURISyntaxExceptionDelegate, this, ex);
return false;
} catch (IOException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(500);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kIOExceptionDelegate, this, ex);
return false;
} catch (InterruptedException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(500);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kInterruptedExceptionDelegate, this, ex);
return false;
}
}
protected boolean sendDeleteRequest() {
try {
httpClient = this.createHttpClient();
this.beforeRequest();
URI uri = this.createURI();
HttpDelete httpDelete = new HttpDelete(uri);
if (this.httpEntity != null) {
// Not supported in delete request
}
this.headers.forEach(httpDelete::setHeader);
CloseableHttpResponse httpResponse = httpClient.execute(httpDelete);
String content = getResponseContent(httpResponse);
this.gobletResponse.setContent(content);
this.gobletResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
this.gobletResponse.setHttpResponse(httpResponse);
httpClient.close();
if (this.didEnd != null) {
this.didEnd.delegate(this);
}
this.afterRequest();
return true;
} catch (URISyntaxException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(400);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kURISyntaxExceptionDelegate, this, ex);
return false;
} catch (IOException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(500);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kIOExceptionDelegate, this, ex);
return false;
} catch (InterruptedException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(500);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kInterruptedExceptionDelegate, this, ex);
return false;
}
}
protected boolean sendHeadRequest() {
try {
httpClient = this.createHttpClient();
this.beforeRequest();
URI uri = this.createURI();
HttpHead httpHead = new HttpHead(uri);
if (this.httpEntity != null) {
// Not supported in delete request
}
this.headers.forEach(httpHead::setHeader);
CloseableHttpResponse httpResponse = httpClient.execute(httpHead);
String content = getResponseContent(httpResponse);
this.gobletResponse.setContent(content);
this.gobletResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
this.gobletResponse.setHttpResponse(httpResponse);
httpClient.close();
if (this.didEnd != null) {
this.didEnd.delegate(this);
}
this.afterRequest();
return true;
} catch (URISyntaxException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(400);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kURISyntaxExceptionDelegate, this, ex);
return false;
} catch (IOException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(500);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kIOExceptionDelegate, this, ex);
return false;
} catch (InterruptedException ex) {
this.errors.add(ex);
this.gobletResponse.setStatusCode(500);
if (this.didError != null) {
this.didError.delegate(this, ex);
}
this.invokeErrorDelegate(kInterruptedExceptionDelegate, this, ex);
return false;
}
}
protected CloseableHttpClient createHttpClient() throws InterruptedException {
CredentialsProvider credentialProvider = null;
CloseableHttpClient localHttpClient = null;
if (this.username != null && this.password != null) {
credentialProvider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);
credentialProvider.setCredentials(AuthScope.ANY, credentials);
}
HttpClientBuilder httpBuilder = HttpClientBuilder.create();
if (this.isProxyRequired()) {
HttpHost httpHost = new HttpHost(this.getProxyHost(), this.getProxyPort());
httpBuilder.setProxy(httpHost);
}
if (credentialProvider != null) {
localHttpClient = httpBuilder.setDefaultCredentialsProvider(credentialProvider).build();
} else {
localHttpClient = httpBuilder.build();
}
Delegate modify = this.getDelegate(kModifyHttpClient);
if (modify != null) {
localHttpClient = ((ModifyHttpClient) modify).modify(localHttpClient, httpBuilder);
}
return localHttpClient;
}
protected String getResponseContent(HttpResponse httpResponse) {
if (this.hasDelegate(this.kMapResponse)) {
return ((ResponseMaper) this.getDelegate(this.kMapResponse)).map(httpResponse);
}
BufferedReader br = null;
try {
String line = "";
br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (IOException ex) {
return null;
} catch (UnsupportedOperationException ex) {
return null;
} finally {
try {
br.close();
} catch (IOException ex) {
}
}
}
protected URI createURI() throws URISyntaxException {
URIBuilder urib = new URIBuilder()
.setScheme(this.getProtocol())
.setHost(this.getHost())
.setPath(this.path);
this.parameters.forEach(urib::setParameter);
if (this.port > 0) {
urib.setPort(this.port);
}
Delegate delegate = this.getDelegate(kBuildURI);
if (delegate != null) {
urib = ((BuildURI) delegate).build(urib);
}
return urib.build();
}
@Override
public GobletResponse getResponse() {
return this.gobletResponse;
}
@Override
public Goblet clearParameters() {
this.parameters.clear();
return this;
}
@Override
public Goblet removeParameter(String name) {
this.parameters.remove(name);
return this;
}
@Override
public Goblet clearHeaders() {
this.headers.clear();
return this;
}
@Override
public Goblet removeHeader(String name) {
this.headers.remove(name);
return this;
}
@Override
public void clear() {
this.errors.clear();
this.parameters.clear();
this.headers.clear();
}
@Override
public void clearErrors() {
this.errors.clear();
}
/**
* @return the timeout
*/
public long getTimeout() {
return timeout;
}
/**
* @param timeout the timeout to set
*/
public void setTimeout(long timeout) {
this.timeout = timeout;
}
@Override
public Goblet didURISyntaxError(ErrorDelegate delegate) {
this.addDelegate(kURISyntaxExceptionDelegate, delegate);
return this;
}
@Override
public Goblet didIOError(ErrorDelegate delegate) {
this.addDelegate(kIOExceptionDelegate, delegate);
return this;
}
@Override
public Goblet didInterruptedError(ErrorDelegate delegate) {
this.addDelegate(kInterruptedExceptionDelegate, delegate);
return this;
}
@Override
public Goblet didBadRequestError(ErrorDelegate delegate) {
this.addDelegate(kHTTPBadRequestException, delegate);
return this;
}
@Override
public Goblet didForbiddenError(ErrorDelegate delegate) {
this.addDelegate(kHTTPForbiddenException, delegate);
return this;
}
@Override
public Goblet didUnauthorizedError(ErrorDelegate delegate) {
this.addDelegate(kHTTPUnauthorizedException, delegate);
return this;
}
@Override
public Goblet didMethodNotAllowedError(ErrorDelegate delegate) {
this.addDelegate(kHTTPMethodNotAllowedException, delegate);
return this;
}
@Override
public Goblet didInternalError(ErrorDelegate delegate) {
this.addDelegate(kInternalErrorException, delegate);
return this;
}
@Override
public CloseableHttpClient getHttpClient() {
return this.httpClient;
}
@Override
public Goblet setEntity(HttpEntity httpEntity) {
this.httpEntity = httpEntity;
return this;
}
@Override
public String getEndpoint() {
try {
return this.createURI().toString();
} catch (URISyntaxException ex) {
return null;
}
}
@Override
public Goblet doBefore(BeforeRequest beforeRequest) {
this.addDelegate(kBeforeRequest, beforeRequest);
return this;
}
@Override
public Goblet doAfter(AfterRequest afterRequest) {
this.addDelegate(kAfterRequest, afterRequest);
return this;
}
@Override
public Goblet modifyHttpClient(ModifyHttpClient modify) {
this.addDelegate(kModifyHttpClient, modify);
return this;
}
@Override
public Goblet buildURI(BuildURI build) {
this.addDelegate(kBuildURI, build);
return this;
}
@Override
public Goblet mapResponse(ResponseMaper map) {
this.addDelegate(this.kMapResponse, map);
return this;
}
@Override
public Chalice setBasicAuthorization(String username, String password) {
try {
String fieldValue = username.concat(":").concat(password);
byte[] encodedFieldValue = Base64.getEncoder().encode(fieldValue.getBytes("UTF-8"));
String basicAuth = "Basic ".concat(new String(encodedFieldValue, "UTF-8"));
this.headers.setHeader(HttpHeaders.AUTHORIZATION, basicAuth);
return this;
} catch (UnsupportedEncodingException ex) {
if (this.hasDelegate(kUnsupportedEncodingException)) {
((ErrorDelegate) this.getDelegate(kUnsupportedEncodingException)).delegate(this, ex);
}
return this;
}
}
@Override
public Chalice setProxyCredentials(String username, String password) {
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
System.setProperty("http.proxyUser", username);
System.setProperty("http.proxyPassword", password);
return this;
}
}