001package com.nimbusds.openid.connect.provider.spi.grants;
002
003
004import net.minidev.json.JSONObject;
005
006import com.nimbusds.oauth2.sdk.ParseException;
007import com.nimbusds.oauth2.sdk.util.JSONObjectUtils;
008
009
010/**
011 * Base token specification.
012 */
013public class TokenSpec {
014
015
016        /**
017         * The token lifetime, in seconds. Zero if permanent / not specified.
018         */
019        private final long lifetime;
020
021
022        /**
023         * Creates a new token specification.
024         *
025         * @param lifetime The token lifetime, in seconds. Zero implies
026         *                 permanent or not specified (to apply the default
027         *                 configured token lifetime), depending on the token
028         *                 type. Must not be negative integer.
029         */
030        public TokenSpec(final long lifetime) {
031
032                if (lifetime < 0l) {
033                        throw new IllegalArgumentException("The token lifetime must not be negative");
034                }
035
036                this.lifetime = lifetime;
037        }
038
039
040        /**
041         * Returns the token lifetime.
042         *
043         * @return The token lifetime, in seconds. Zero implies permanent or
044         *         not specified (to apply the default configured token
045         *         lifetime), depending on the token type. Must not be negative
046         *         integer.
047         */
048        public long getLifetime() {
049
050                return lifetime;
051        }
052
053
054        /**
055         * Returns a JSON object representation of this token specification.
056         *
057         * @return The JSON object.
058         */
059        public JSONObject toJSONObject() {
060
061                JSONObject o = new JSONObject();
062
063                if (lifetime > 0l) {
064                        o.put("lifetime", lifetime);
065                }
066
067                return o;
068        }
069
070
071        /**
072         * Parses a token specification from the specified JSON object.
073         *
074         * @param o The JSON object. Must not be {@code null}.
075         *
076         * @return The token specification.
077         *
078         * @throws ParseException If parsing failed.
079         */
080        public static TokenSpec parse(final JSONObject o)
081                throws ParseException {
082
083                long lifetime = 0l;
084
085                if (o.containsKey("lifetime")) {
086                        lifetime = JSONObjectUtils.getLong(o, "lifetime");
087                }
088
089                return new TokenSpec(lifetime);
090        }
091}