001/* 002 * oauth2-oidc-sdk 003 * 004 * Copyright 2012-2016, Connect2id Ltd and contributors. 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use 007 * this file except in compliance with the License. You may obtain a copy of the 008 * License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software distributed 013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 015 * specific language governing permissions and limitations under the License. 016 */ 017 018package com.nimbusds.oauth2.sdk; 019 020 021import com.nimbusds.oauth2.sdk.http.HTTPResponse; 022import net.minidev.json.JSONObject; 023 024 025/** 026 * Token endpoint response. This is the base abstract class for access token 027 * (success) and token error responses. 028 * 029 * <p>Related specifications: 030 * 031 * <ul> 032 * <li>OAuth 2.0 (RFC 6749), section 3.2. 033 * </ul> 034 */ 035public abstract class TokenResponse implements Response { 036 037 038 /** 039 * Casts this response to an access token response. 040 * 041 * @return The access token response. 042 */ 043 public AccessTokenResponse toSuccessResponse() { 044 045 return (AccessTokenResponse) this; 046 } 047 048 049 /** 050 * Casts this response to a token error response. 051 * 052 * @return The token error response. 053 */ 054 public TokenErrorResponse toErrorResponse() { 055 056 return (TokenErrorResponse) this; 057 } 058 059 060 /** 061 * Parses a token response from the specified JSON object. 062 * 063 * @param jsonObject The JSON object to parse. Must not be 064 * {@code null}. 065 * 066 * @return The access token or token error response. 067 * 068 * @throws ParseException If the JSON object couldn't be parsed to a 069 * token response. 070 */ 071 public static TokenResponse parse(final JSONObject jsonObject) 072 throws ParseException{ 073 074 if (jsonObject.containsKey("access_token")) 075 return AccessTokenResponse.parse(jsonObject); 076 else 077 return TokenErrorResponse.parse(jsonObject); 078 } 079 080 081 /** 082 * Parses a token response from the specified HTTP response. 083 * 084 * @param httpResponse The HTTP response. Must not be {@code null}. 085 * 086 * @return The access token or token error response. 087 * 088 * @throws ParseException If the HTTP response couldn't be parsed to a 089 * token response. 090 */ 091 public static TokenResponse parse(final HTTPResponse httpResponse) 092 throws ParseException { 093 094 if (httpResponse.getStatusCode() == HTTPResponse.SC_OK) 095 return AccessTokenResponse.parse(httpResponse); 096 else 097 return TokenErrorResponse.parse(httpResponse); 098 } 099}