Snippets
Created by
Gaurav Wasan
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | package com.ibm.cloudoe.samples;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.ibm.watson.developer_cloud.http.HttpHeaders;
import com.ibm.watson.developer_cloud.http.HttpStatus;
import com.ibm.watson.developer_cloud.service.BadRequestException;
import com.ibm.watson.developer_cloud.service.ConflictException;
import com.ibm.watson.developer_cloud.service.ForbiddenException;
import com.ibm.watson.developer_cloud.service.InternalServerErrorException;
import com.ibm.watson.developer_cloud.service.NotFoundException;
import com.ibm.watson.developer_cloud.service.RequestTooLargeException;
import com.ibm.watson.developer_cloud.service.ServiceResponseException;
import com.ibm.watson.developer_cloud.service.ServiceUnavailableException;
import com.ibm.watson.developer_cloud.service.TooManyRequestsException;
import com.ibm.watson.developer_cloud.service.UnauthorizedException;
import com.ibm.watson.developer_cloud.service.UnsupportedException;
import com.ibm.watson.developer_cloud.util.RequestUtil;
import com.ibm.watson.developer_cloud.util.ResponseUtil;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Request.Builder;
import com.squareup.okhttp.Response;
/**
* The Extended Text to Speech service to support the proxy server
*
* @version v1
* @author Gaurav Wasan
*/
public class ExtendedTextToSpeech extends com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech {
private int proxyPort = 54321;
private String proxyHost = "localhost";
private static final Logger log = Logger.getLogger(ExtendedTextToSpeech.class.getName());
private final OkHttpClient client;
public Proxy getCorporateProxy()
{
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
}
public ExtendedTextToSpeech()
{
client = configureHttpProxyClient();
}
/**
* Configures the HTTP client.
*
* @return the HTTP client
*/
public OkHttpClient configureHttpProxyClient() {
OkHttpClient client = super.configureHttpClient();
client.setProxy(this.getCorporateProxy());
return client;
}
/**
* Gets the user agent.
*
*
* @return the user agent
*/
private final String getUserAgent() {
return "watson-developer-cloud-java-sdk-2.9.0";
}
/**
* Execute the HTTP request.
*
* @param request the HTTP request
*
* @return the HTTP response
*/
protected Response execute(Request request) {
final Builder builder = request.newBuilder();
// Set service endpoint for relative paths
if (RequestUtil.isRelative(request)) {
builder.url(RequestUtil.replaceEndPoint(request.urlString(), getEndPoint()));
}
// Set User-Agent
builder.header(HttpHeaders.USER_AGENT, getUserAgent());
// Set Authentication
setAuthentication(builder);
final Request newRequest = builder.build();
Response response;
log.log(Level.FINEST, "Request to: " + newRequest.urlString());
try {
response = client.newCall(newRequest).execute();
} catch (final IOException e) {
log.log(Level.SEVERE, "IOException", e);
throw new RuntimeException(e);
}
if (response.isSuccessful()) {
return response;
}
final int status = response.code();
// There was a Client Error 4xx or a Server Error 5xx
// Get the error message and create the exception
final String error = getErrorMessage(response);
log.log(Level.SEVERE, newRequest.urlString() + ", status: " + status + ", error: " + error);
switch (status) {
case HttpStatus.BAD_REQUEST: // HTTP 400
throw new BadRequestException(error != null ? error : "Bad Request", response);
case HttpStatus.UNAUTHORIZED: // HTTP 401
throw new UnauthorizedException(
"Unauthorized: Access is denied due to invalid credentials", response);
case HttpStatus.FORBIDDEN: // HTTP 403
throw new ForbiddenException(error != null ? error
: "Forbidden: Service refuse the request", response);
case HttpStatus.NOT_FOUND: // HTTP 404
throw new NotFoundException(error != null ? error : "Not found", response);
case HttpStatus.NOT_ACCEPTABLE: // HTTP 406
throw new ForbiddenException(error != null ? error
: "Forbidden: Service refuse the request", response);
case HttpStatus.CONFLICT: // HTTP 409
throw new ConflictException(error != null ? error : "", response);
case HttpStatus.REQUEST_TOO_LONG: // HTTP 413
throw new RequestTooLargeException(error != null ? error
: "Request too large: The request entity is larger than the server is able to process",
response);
case HttpStatus.UNSUPPORTED_MEDIA_TYPE: // HTTP 415
throw new UnsupportedException(error != null ? error : "Unsupported Media Type", response);
case HttpStatus.TOO_MANY_REQUESTS: // HTTP 429
throw new TooManyRequestsException(error != null ? error : "Too many requests", response);
case HttpStatus.INTERNAL_SERVER_ERROR: // HTTP 500
throw new InternalServerErrorException(error != null ? error : "Internal Server Error",
response);
case HttpStatus.SERVICE_UNAVAILABLE: // HTTP 503
throw new ServiceUnavailableException(error != null ? error : "Service Unavailable",
response);
default: // other errors
throw new ServiceResponseException(status, error, response);
}
}
/**
* Gets the error message from a JSON response
*
* <pre>
* {
* code: 400
* error: 'bad request'
* }
* </pre>
*
* @param response the HTTP response
* @return the error message from the JSON object
*/
private String getErrorMessage(Response response) {
String error = ResponseUtil.getString(response);
try {
final JsonObject jsonObject = ResponseUtil.getJsonObject(error);
if (jsonObject.has("error")) {
error = jsonObject.get("error").getAsString();
} else if (jsonObject.has("error_message")) {
error = jsonObject.get("error_message").getAsString();
} else if (jsonObject.has("message")) {
error = jsonObject.get("message").getAsString();
}
} catch (final JsonIOException e) {
// Ignore JsonIOException and use fallback String version of response
} catch (final JsonSyntaxException e) {
// Ignore JsonSyntaxException and use fallback String version of response
}
return error;
}
}
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.