Snippets

Gaurav Wasan ExtendedTextToSpeech

Created by Gaurav Wasan
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)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.