001package com.nimbusds.oauth2.sdk.token;
002
003
004import net.jcip.annotations.Immutable;
005
006import net.minidev.json.JSONObject;
007
008import com.nimbusds.oauth2.sdk.util.JSONObjectUtils;
009import com.nimbusds.oauth2.sdk.ParseException;
010
011
012/**
013 * Refresh token.
014 *
015 * <p>Related specifications:
016 *
017 * <ul>
018 *     <li>OAuth 2.0 (RFC 6749), section 1.5.
019 * </ul>
020 */
021@Immutable
022public final class RefreshToken extends Token {
023
024
025        /**
026         * Creates a new refresh token with a randomly generated 256-bit 
027         * (32-byte) value, Base64URL-encoded.
028         */
029        public RefreshToken() {
030        
031                this(32);
032        }       
033
034
035        /**
036         * Creates a new refresh token with a randomly generated value of the 
037         * specified length, Base64URL-encoded.
038         *
039         * @param byteLength The byte length of the value to generate. Must be
040         *                   greater than one.
041         */
042        public RefreshToken(final int byteLength) {
043        
044                super(byteLength);
045        }
046
047
048        /**
049         * Creates a new refresh token with the specified value.
050         *
051         * @param value The refresh token value. Must not be {@code null} or 
052         *              empty string.
053         */
054        public RefreshToken(final String value) {
055        
056                super(value);
057        }
058
059
060        @Override
061        public JSONObject toJSONObject() {
062
063                JSONObject o = new JSONObject();
064
065                o.put("refresh_token", getValue());
066                
067                return o;
068        }
069
070
071        /**
072         * Parses a refresh token from a JSON object access token response.
073         *
074         * @param jsonObject The JSON object to parse. Must not be 
075         *                   {@code null}.
076         *
077         * @return The refresh token, {@code null} if not found.
078         *
079         * @throws ParseException If the JSON object couldn't be parsed to a
080         *                        refresh token.
081         */
082        public static RefreshToken parse(final JSONObject jsonObject)
083                throws ParseException {
084
085                // Parse value
086                if (! jsonObject.containsKey("refresh_token"))
087                        return null;
088
089                String value = JSONObjectUtils.getString(jsonObject, "refresh_token");
090
091                return new RefreshToken(value);
092        }
093
094
095        @Override
096        public boolean equals(final Object object) {
097        
098                return object instanceof RefreshToken &&
099                       this.toString().equals(object.toString());
100        }
101}