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.id;
019
020
021import com.nimbusds.oauth2.sdk.util.StringUtils;
022import net.jcip.annotations.Immutable;
023
024
025/**
026 * Opaque value used to maintain state between a request and a callback. Also
027 * serves as a protection against XSRF attacks, among other uses.
028 */
029@Immutable
030public final class State extends Identifier {
031
032
033        /**
034         * Creates a new state with the specified value.
035         *
036         * @param value The state value. Must not be {@code null} or empty 
037         *              string.
038         */
039        public State(final String value) {
040        
041                super(value);
042        }
043
044
045        /**
046         * Creates a new state with a randomly generated value of the specified
047         * byte length, Base64URL-encoded.
048         *
049         * @param byteLength The byte length of the value to generate. Must be
050         *                   greater than one.
051         */
052        public State(final int byteLength) {
053        
054                super(byteLength);
055        }
056        
057        
058        /**
059         * Creates a new state with a randomly generated 256-bit (32-byte) 
060         * value, Base64URL-encoded.
061         */
062        public State() {
063
064                super();
065        }
066        
067        
068        @Override
069        public boolean equals(final Object object) {
070        
071                return object instanceof State &&
072                       this.toString().equals(object.toString());
073        }
074        
075        
076        /**
077         * Parses a state from the specified string.
078         *
079         * @param s The string to parse, {@code null} or empty if no state is
080         *          specified.
081         *
082         * @return The state, {@code null} if the parsed string was 
083         *         {@code null} or empty.
084         */
085        public static State parse(final String s) {
086        
087                if (StringUtils.isBlank(s))
088                        return null;
089                
090                return new State(s);
091        }
092}