// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
//     /**
//      * Returns the actual access token String.
//      *
//      * @return
//      *
//      * @throws ProtocolException
//      */
//     public CharSequence accessToken() throws ProtocolException;
// 
//     /**
//      * Returns the access token type.
//      *
//      * @return
//      *
//      * @throws ProtocolException
//      */
//     public CharSequence tokenType() throws ProtocolException;
// 
//     /**
//      * Returns whether the response also contained a refresh token.
//      *
//      * @return
//      */
//     public boolean hasRefreshToken();
// 
//     /**
//      * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
//      *
//      * @return
//      *
//      * @throws NoSuchElementException
//      *         If the token doesn't contain a refresh token.
//      * @throws ProtocolException
//      */
//     public CharSequence refreshToken() throws ProtocolException;
// 
//     /**
//      * Returns the expected expiration date of the access token.
//      *
//      * @return
//      *
//      * @throws ProtocolException
//      */
//     public DateTime expirationDate() throws ProtocolException;
// 
//     /**
//      * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
//      *
//      * @return An {@link OAuth2Scope}.
//      *
//      * @throws ProtocolException
//      */
//     public OAuth2Scope scope() throws ProtocolException;
// 
//     /**
//      * Returns a value stored in the token response under the {@code parameterName}.
//      *
//      * @param parameterName
//      *         the key under which the value is stored in the response
//      */
//     public Optional<CharSequence> extraParameter(final String parameterName);
// }
// 
// Path: src/main/java/org/dmfs/oauth2/client/errors/TokenRequestError.java
// public final class TokenRequestError extends ProtocolError
// {
//     private static final long serialVersionUID = 1L;
// 
//     private final String mErrorResponse;
// 
//     /**
//      * {@link JSONObject} is not a {@link Serializable}, so we mark it transient and restore it from String if necessary.
//      */
//     private transient JSONObject mErrorObject;
// 
// 
//     public TokenRequestError(JSONObject errorObject) throws JSONException
//     {
//         super(errorObject.getString("error"));
//         mErrorObject = errorObject;
//         mErrorResponse = errorObject.toString();
//     }
// 
// 
//     /**
//      * Returns the error code token that was returned by the server.
//      *
//      * @return A String containing the error code token.
//      */
//     public String error()
//     {
//         return errorObject().optString("error", "unknown");
//     }
// 
// 
//     /**
//      * Returns the error description that was returned by the server.
//      *
//      * @return A String containing the error description.
//      */
//     public String description()
//     {
//         return errorObject().optString("error_description", "");
//     }
// 
// 
//     /**
//      * Returns the optional error URI returned by the server.
//      *
//      * @return A URI pointing to a more descriptive error page or <code>null</code>.
//      */
//     public URI uri()
//     {
//         return errorObject().has("error_uri") ? URI.create(errorObject().optString("error_uri")) : null;
//     }
// 
// 
//     private JSONObject errorObject()
//     {
//         if (mErrorObject == null)
//         {
//             try
//             {
//                 mErrorObject = new JSONObject(mErrorResponse);
//             }
//             catch (JSONException e)
//             {
//                 throw new RuntimeException(String.format("Can't restore JSONObject from String", mErrorResponse), e);
//             }
//         }
//         return mErrorObject;
//     }
// }


import org.dmfs.httpessentials.client.HttpResponse;
import org.dmfs.httpessentials.client.HttpResponseHandler;
import org.dmfs.httpessentials.exceptions.ProtocolError;
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.httpessentials.responsehandlers.StringResponseHandler;
import org.dmfs.httpessentials.types.MediaType;
import org.dmfs.httpessentials.types.StructuredMediaType;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.dmfs.oauth2.client.errors.TokenRequestError;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
/*
 * Copyright 2016 dmfs GmbH
 *
 * 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.
 */

package org.dmfs.oauth2.client.http.responsehandlers;




/**
 * {@link HttpResponseHandler} for OAuth2 token request errors with status code 400.
 *
 * @author Marten Gajda
 */
public final class TokenErrorResponseHandler implements HttpResponseHandler<OAuth2AccessToken>
{
    private final static MediaType APPLICATION_JSON = new StructuredMediaType("application", "json");


    public TokenErrorResponseHandler()
    {
        // nothing to do here
    }


    @Override
    public OAuth2AccessToken handleResponse(HttpResponse response) throws IOException, ProtocolError, ProtocolException
    {
        if (!APPLICATION_JSON.equals(response.responseEntity().contentType().value()))
        {
            throw new ProtocolException(
                    String.format("Illegal response content-type %s, exected %s",
                            response.responseEntity().contentType().value(), APPLICATION_JSON));
        }

        String responseString = new StringResponseHandler("UTF-8").handleResponse(response);
        try
        {
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
//     /**
//      * Returns the actual access token String.
//      *
//      * @return
//      *
//      * @throws ProtocolException
//      */
//     public CharSequence accessToken() throws ProtocolException;
// 
//     /**
//      * Returns the access token type.
//      *
//      * @return
//      *
//      * @throws ProtocolException
//      */
//     public CharSequence tokenType() throws ProtocolException;
// 
//     /**
//      * Returns whether the response also contained a refresh token.
//      *
//      * @return
//      */
//     public boolean hasRefreshToken();
// 
//     /**
//      * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
//      *
//      * @return
//      *
//      * @throws NoSuchElementException
//      *         If the token doesn't contain a refresh token.
//      * @throws ProtocolException
//      */
//     public CharSequence refreshToken() throws ProtocolException;
// 
//     /**
//      * Returns the expected expiration date of the access token.
//      *
//      * @return
//      *
//      * @throws ProtocolException
//      */
//     public DateTime expirationDate() throws ProtocolException;
// 
//     /**
//      * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
//      *
//      * @return An {@link OAuth2Scope}.
//      *
//      * @throws ProtocolException
//      */
//     public OAuth2Scope scope() throws ProtocolException;
// 
//     /**
//      * Returns a value stored in the token response under the {@code parameterName}.
//      *
//      * @param parameterName
//      *         the key under which the value is stored in the response
//      */
//     public Optional<CharSequence> extraParameter(final String parameterName);
// }
// 
// Path: src/main/java/org/dmfs/oauth2/client/errors/TokenRequestError.java
// public final class TokenRequestError extends ProtocolError
// {
//     private static final long serialVersionUID = 1L;
// 
//     private final String mErrorResponse;
// 
//     /**
//      * {@link JSONObject} is not a {@link Serializable}, so we mark it transient and restore it from String if necessary.
//      */
//     private transient JSONObject mErrorObject;
// 
// 
//     public TokenRequestError(JSONObject errorObject) throws JSONException
//     {
//         super(errorObject.getString("error"));
//         mErrorObject = errorObject;
//         mErrorResponse = errorObject.toString();
//     }
// 
// 
//     /**
//      * Returns the error code token that was returned by the server.
//      *
//      * @return A String containing the error code token.
//      */
//     public String error()
//     {
//         return errorObject().optString("error", "unknown");
//     }
// 
// 
//     /**
//      * Returns the error description that was returned by the server.
//      *
//      * @return A String containing the error description.
//      */
//     public String description()
//     {
//         return errorObject().optString("error_description", "");
//     }
// 
// 
//     /**
//      * Returns the optional error URI returned by the server.
//      *
//      * @return A URI pointing to a more descriptive error page or <code>null</code>.
//      */
//     public URI uri()
//     {
//         return errorObject().has("error_uri") ? URI.create(errorObject().optString("error_uri")) : null;
//     }
// 
// 
//     private JSONObject errorObject()
//     {
//         if (mErrorObject == null)
//         {
//             try
//             {
//                 mErrorObject = new JSONObject(mErrorResponse);
//             }
//             catch (JSONException e)
//             {
//                 throw new RuntimeException(String.format("Can't restore JSONObject from String", mErrorResponse), e);
//             }
//         }
//         return mErrorObject;
//     }
// }


// Path: src/main/java/org/dmfs/oauth2/client/http/responsehandlers/TokenErrorResponseHandler.java
import org.dmfs.httpessentials.client.HttpResponse;
import org.dmfs.httpessentials.client.HttpResponseHandler;
import org.dmfs.httpessentials.exceptions.ProtocolError;
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.httpessentials.responsehandlers.StringResponseHandler;
import org.dmfs.httpessentials.types.MediaType;
import org.dmfs.httpessentials.types.StructuredMediaType;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.dmfs.oauth2.client.errors.TokenRequestError;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;

/*
 * Copyright 2016 dmfs GmbH
 *
 * 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.
 */

package org.dmfs.oauth2.client.http.responsehandlers;




/**
 * {@link HttpResponseHandler} for OAuth2 token request errors with status code 400.
 *
 * @author Marten Gajda
 */
public final class TokenErrorResponseHandler implements HttpResponseHandler<OAuth2AccessToken>
{
    private final static MediaType APPLICATION_JSON = new StructuredMediaType("application", "json");


    public TokenErrorResponseHandler()
    {
        // nothing to do here
    }


    @Override
    public OAuth2AccessToken handleResponse(HttpResponse response) throws IOException, ProtocolError, ProtocolException
    {
        if (!APPLICATION_JSON.equals(response.responseEntity().contentType().value()))
        {
            throw new ProtocolException(
                    String.format("Illegal response content-type %s, exected %s",
                            response.responseEntity().contentType().value(), APPLICATION_JSON));
        }

        String responseString = new StringResponseHandler("UTF-8").handleResponse(response);
        try
        {
            throw new TokenRequestError(new JSONObject(responseString));