<commit_before>/**
 * Copyright IBM Corporation 2018
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

import Foundation

/**
   ### Service Overview
  The IBM Watson Tone Analyzer service uses linguistic analysis to detect emotional and language
  tones in written text. The service can analyze tone at both the document and sentence levels. You
  can use the service to understand how your written communications are perceived and then to
  improve the tone of your communications. Businesses can use the service to learn the tone of their
  customers' communications and to respond to each customer appropriately, or to understand and
  improve their customer conversations.
  ### API Usage
  The following information provides details about using the service to analyze tone:
  * **The tone method:** The service offers `GET` and `POST /v3/tone` methods that use the general
  purpose endpoint to analyze the tone of input content. The methods accept content in JSON, plain
  text, or HTML format.
  * **The tone_chat method:** The service offers a `POST /v3/tone_chat` method that uses the
  customer engagement endpoint to analyze the tone of customer service and customer support
  conversations. The method accepts content in JSON format.
  * **Authentication:** You authenticate to the service by using your service credentials. You can
  use your credentials to authenticate via a proxy server that resides in IBM Cloud, or you can use
  your credentials to obtain a token and contact the service directly. See [Service credentials for
  Watson
  services](https://console.bluemix.net/docs/services/watson/getting-started-credentials.html) and
  [Tokens for
  authentication](https://console.bluemix.net/docs/services/watson/getting-started-tokens.html).
  * **Request Logging:** By default, all Watson services log requests and their results. Data is
  collected only to improve the Watson services. If you do not want to share your data, set the
  header parameter `X-Watson-Learning-Opt-Out` to `true` for each request. Data is collected for any
  request that omits this header. See [Controlling request logging for Watson
  services](https://console.bluemix.net/docs/services/watson/getting-started-logging.html).

  For more information about the service, see [About Tone
  Analyzer](https://console.bluemix.net/docs/services/tone-analyzer/index.html).

  **Note:** Method descriptions apply to the latest version of the interface, `2017-09-21`. Where
  necessary, parameters and models describe differences between versions `2017-09-21` and
  `2016-05-19`.
 */
public class ToneAnalyzer {

    /// The base URL to use when contacting the service.
    public var serviceURL = "https://gateway.watsonplatform.net/tone-analyzer/api"

    /// The default HTTP headers for all requests to the service.
    public var defaultHeaders = [String: String]()

    private let credentials: Credentials
    private let domain = "com.ibm.watson.developer-cloud.ToneAnalyzerV3"
    private let version: String

    /**
     Create a `ToneAnalyzer` object.

     - parameter username: The username used to authenticate with the service.
     - parameter password: The password used to authenticate with the service.
     - parameter version: The release date of the version of the API to use. Specify the date
       in "YYYY-MM-DD" format.
     */
    public init(username: String, password: String, version: String) {
        self.credentials = .basicAuthentication(username: username, password: password)
        self.version = version
    }

    /**
     If the response or data represents an error returned by the Tone Analyzer service,
     then return NSError with information about the error that occured. Otherwise, return nil.

     - parameter response: the URL response returned from the service.
     - parameter data: Raw data returned from the service that may represent an error.
     */
    private func responseToError(response: HTTPURLResponse?, data: Data?) -> NSError? {

        // First check http status code in response
        if let response = response {
            if (200..<300).contains(response.statusCode) {
                return nil
            }
        }

        // ensure data is not nil
        guard let data = data else {
            if let code = response?.statusCode {
                return NSError(domain: domain, code: code, userInfo: nil)
            }
            return nil  // RestKit will generate error for this case
        }

        do {
            let json = try JSONWrapper(data: data)
            let code = response?.statusCode ?? 400
            let message = try json.getString(at: "error")
            var userInfo = [NSLocalizedDescriptionKey: message]
            let help = try? json.getString(at: "help")
            let description = try? json.getString(at: "description")
            if let recoverySuggestion = help ?? description {
                userInfo[NSLocalizedRecoverySuggestionErrorKey] = recoverySuggestion
            }
            return NSError(domain: domain, code: code, userInfo: userInfo)<commit_msg>Parse error messages<commit_after>/**
 * Copyright IBM Corporation 2018
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

import Foundation

/**
   ### Service Overview
  The IBM Watson Tone Analyzer service uses linguistic analysis to detect emotional and language
  tones in written text. The service can analyze tone at both the document and sentence levels. You
  can use the service to understand how your written communications are perceived and then to
  improve the tone of your communications. Businesses can use the service to learn the tone of their
  customers' communications and to respond to each customer appropriately, or to understand and
  improve their customer conversations.
  ### API Usage
  The following information provides details about using the service to analyze tone:
  * **The tone method:** The service offers `GET` and `POST /v3/tone` methods that use the general
  purpose endpoint to analyze the tone of input content. The methods accept content in JSON, plain
  text, or HTML format.
  * **The tone_chat method:** The service offers a `POST /v3/tone_chat` method that uses the
  customer engagement endpoint to analyze the tone of customer service and customer support
  conversations. The method accepts content in JSON format.
  * **Authentication:** You authenticate to the service by using your service credentials. You can
  use your credentials to authenticate via a proxy server that resides in IBM Cloud, or you can use
  your credentials to obtain a token and contact the service directly. See [Service credentials for
  Watson
  services](https://console.bluemix.net/docs/services/watson/getting-started-credentials.html) and
  [Tokens for
  authentication](https://console.bluemix.net/docs/services/watson/getting-started-tokens.html).
  * **Request Logging:** By default, all Watson services log requests and their results. Data is
  collected only to improve the Watson services. If you do not want to share your data, set the
  header parameter `X-Watson-Learning-Opt-Out` to `true` for each request. Data is collected for any
  request that omits this header. See [Controlling request logging for Watson
  services](https://console.bluemix.net/docs/services/watson/getting-started-logging.html).

  For more information about the service, see [About Tone
  Analyzer](https://console.bluemix.net/docs/services/tone-analyzer/index.html).

  **Note:** Method descriptions apply to the latest version of the interface, `2017-09-21`. Where
  necessary, parameters and models describe differences between versions `2017-09-21` and
  `2016-05-19`.
 */
public class ToneAnalyzer {

    /// The base URL to use when contacting the service.
    public var serviceURL = "https://gateway.watsonplatform.net/tone-analyzer/api"

    /// The default HTTP headers for all requests to the service.
    public var defaultHeaders = [String: String]()

    private let credentials: Credentials
    private let domain = "com.ibm.watson.developer-cloud.ToneAnalyzerV3"
    private let version: String

    /**
     Create a `ToneAnalyzer` object.

     - parameter username: The username used to authenticate with the service.
     - parameter password: The password used to authenticate with the service.
     - parameter version: The release date of the version of the API to use. Specify the date
       in "YYYY-MM-DD" format.
     */
    public init(username: String, password: String, version: String) {
        self.credentials = .basicAuthentication(username: username, password: password)
        self.version = version
    }

    /**
     If the response or data represents an error returned by the Tone Analyzer service,
     then return NSError with information about the error that occured. Otherwise, return nil.

     - parameter response: the URL response returned from the service.
     - parameter data: Raw data returned from the service that may represent an error.
     */
    private func responseToError(response: HTTPURLResponse?, data: Data?) -> NSError? {

        // First check http status code in response
        if let response = response {
            if (200..<300).contains(response.statusCode) {
                return nil
            }
        }

        // ensure data is not nil
        guard let data = data else {
            if let code = response?.statusCode {
                return NSError(domain: domain, code: code, userInfo: nil)
            }
            return nil  // RestKit will generate error for this case
        }

        do {
            let json = try JSONWrapper(data: data)
            let code = response?.statusCode ?? 400
            let message = try json.getString(at: "error")
            let userInfo = [NSLocalizedDescriptionKey: message]
            return NSError(domain: domain, code: code, userInfo: userInfo)
{'fraction_non_alphanumeric': 0.07086614173228346, 'fraction_numerical': 0.008057132393334554, 'mean_word_length': 3.196311947752593, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 10, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '354801', 'n_tokens_mistral': 2793, 'n_tokens_neox': 2635, 'n_words': 1258}