001/**
002 *
003 * Copyright 2018-2020 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack.fsm;
018
019import java.lang.reflect.Constructor;
020import java.lang.reflect.InvocationTargetException;
021import java.util.Arrays;
022import java.util.Collections;
023import java.util.HashSet;
024import java.util.Set;
025import java.util.logging.Level;
026import java.util.logging.Logger;
027
028import org.jivesoftware.smack.c2s.ModularXmppClientToServerConnection;
029import org.jivesoftware.smack.c2s.internal.ModularXmppClientToServerConnectionInternal;
030
031public abstract class StateDescriptor {
032
033    private static final Logger LOGGER = Logger.getLogger(StateDescriptor.class.getName());
034
035    public enum Property {
036        multiVisitState,
037        finalState,
038        notImplemented,
039    }
040
041    private final String stateName;
042    private final int xepNum;
043    private final String rfcSection;
044    private final Set<Property> properties;
045
046    private final Class<? extends State> stateClass;
047    private final Constructor<? extends State> stateClassConstructor;
048
049    private final Set<Class<? extends StateDescriptor>> successors = new HashSet<>();
050
051    private final Set<Class<? extends StateDescriptor>> predecessors = new HashSet<>();
052
053    private final Set<Class<? extends StateDescriptor>> precedenceOver = new HashSet<>();
054
055    private final Set<Class<? extends StateDescriptor>> inferiorTo = new HashSet<>();
056
057    protected StateDescriptor() {
058        this(NoOpState.class, (Property) null);
059    }
060
061    protected StateDescriptor(Property... properties) {
062        this(NoOpState.class, properties);
063    }
064
065    protected StateDescriptor(Class<? extends State> stateClass) {
066        this(stateClass, -1, null, Collections.emptySet());
067    }
068
069    protected StateDescriptor(Class<? extends State> stateClass, Property... properties) {
070        this(stateClass, -1, null, new HashSet<>(Arrays.asList(properties)));
071    }
072
073    protected StateDescriptor(Class<? extends State> stateClass, int xepNum) {
074        this(stateClass, xepNum, null, Collections.emptySet());
075    }
076
077    protected StateDescriptor(Class<? extends State> stateClass, int xepNum,
078                    Property... properties) {
079        this(stateClass, xepNum, null, new HashSet<>(Arrays.asList(properties)));
080    }
081
082    protected StateDescriptor(Class<? extends State> stateClass, String rfcSection) {
083        this(stateClass, -1, rfcSection, Collections.emptySet());
084    }
085
086    @SuppressWarnings("unchecked")
087    private StateDescriptor(Class<? extends State> stateClass, int xepNum,
088                    String rfcSection, Set<Property> properties) {
089        this.stateClass = stateClass;
090        if (rfcSection != null && xepNum > 0) {
091            throw new IllegalArgumentException("Must specify either RFC or XEP");
092        }
093        this.xepNum = xepNum;
094        this.rfcSection = rfcSection;
095        this.properties = properties;
096
097        Constructor<? extends State> selectedConstructor = null;
098        Constructor<?>[] constructors = stateClass.getDeclaredConstructors();
099        for (Constructor<?> constructor : constructors) {
100            Class<?>[] parameterTypes = constructor.getParameterTypes();
101            if (parameterTypes.length != 3) {
102                continue;
103            }
104            if (!ModularXmppClientToServerConnection.class.isAssignableFrom(parameterTypes[0])) {
105                continue;
106            }
107            if (!StateDescriptor.class.isAssignableFrom(parameterTypes[1])) {
108                continue;
109            }
110            if (!ModularXmppClientToServerConnectionInternal.class.isAssignableFrom(parameterTypes[2])) {
111                continue;
112            }
113            selectedConstructor = (Constructor<? extends State>) constructor;
114            break;
115        }
116
117        stateClassConstructor = selectedConstructor;
118        if (stateClassConstructor != null) {
119            stateClassConstructor.setAccessible(true);
120        } else {
121            // TODO: Add validation check that if stateClassConstructor is 'null' the cosntructState() method is overriden.
122        }
123
124        String className = getClass().getSimpleName();
125        stateName = className.replaceFirst("StateDescriptor", "");
126    }
127
128    protected void addSuccessor(Class<? extends StateDescriptor> successor) {
129        addAndCheckNonExistent(successors, successor);
130    }
131
132    public void addPredeccessor(Class<? extends StateDescriptor> predeccessor) {
133        addAndCheckNonExistent(predecessors, predeccessor);
134    }
135
136    protected void declarePrecedenceOver(Class<? extends StateDescriptor> subordinate) {
137        addAndCheckNonExistent(precedenceOver, subordinate);
138    }
139
140    protected void declarePrecedenceOver(String subordinate) {
141        addAndCheckNonExistent(precedenceOver, subordinate);
142    }
143
144    protected void declareInferiorityTo(Class<? extends StateDescriptor> superior) {
145        addAndCheckNonExistent(inferiorTo, superior);
146    }
147
148    protected void declareInferiorityTo(String superior) {
149        addAndCheckNonExistent(inferiorTo, superior);
150    }
151
152    private static void addAndCheckNonExistent(Set<Class<? extends StateDescriptor>> set, String clazzName) {
153        Class<?> clazz;
154        try {
155            clazz = Class.forName(clazzName);
156        } catch (ClassNotFoundException e) {
157            // The state descriptor class is not in classpath, which probably means that the smack module is not loaded
158            // into the classpath. Hence we can silently ignore that.
159            LOGGER.log(Level.FINEST, "Ignoring unknown state descriptor '" + clazzName + "'", e);
160            return;
161        }
162        if (!StateDescriptor.class.isAssignableFrom(clazz)) {
163            throw new IllegalArgumentException(clazz + " is no state descriptor class");
164        }
165        Class<? extends StateDescriptor> stateDescriptorClass = clazz.asSubclass(StateDescriptor.class);
166        addAndCheckNonExistent(set, stateDescriptorClass);
167    }
168
169    private static <E> void addAndCheckNonExistent(Set<E> set, E e) {
170        boolean newElement = set.add(e);
171        if (!newElement) {
172            throw new IllegalArgumentException("Element already exists in set");
173        }
174    }
175
176    public Set<Class<? extends StateDescriptor>> getSuccessors() {
177        return Collections.unmodifiableSet(successors);
178    }
179
180    public Set<Class<? extends StateDescriptor>> getPredeccessors() {
181        return Collections.unmodifiableSet(predecessors);
182    }
183
184    public Set<Class<? extends StateDescriptor>> getSubordinates() {
185        return Collections.unmodifiableSet(precedenceOver);
186    }
187
188    public Set<Class<? extends StateDescriptor>> getSuperiors() {
189        return Collections.unmodifiableSet(inferiorTo);
190    }
191
192    public String getStateName() {
193        return stateName;
194    }
195
196    public String getFullStateName(boolean breakStateName) {
197        String reference = getReference();
198        if (reference != null) {
199            char sep;
200            if (breakStateName) {
201                sep = '\n';
202            } else {
203                sep = ' ';
204            }
205            return getStateName() + sep + '(' + reference + ')';
206        }
207        else {
208            return getStateName();
209        }
210    }
211
212    private transient String referenceCache;
213
214    public String getReference()  {
215        if (referenceCache == null) {
216            if (xepNum > 0) {
217                referenceCache = "XEP-" + String.format("%04d", xepNum);
218            } else if (rfcSection != null) {
219                referenceCache = rfcSection;
220            }
221        }
222        return referenceCache;
223    }
224
225    public Class<? extends State> getStateClass() {
226        return stateClass;
227    }
228
229    public boolean isMultiVisitState() {
230        return properties.contains(Property.multiVisitState);
231    }
232
233    public boolean isNotImplemented() {
234        return properties.contains(Property.notImplemented);
235    }
236
237    public boolean isFinalState() {
238        return properties.contains(Property.finalState);
239    }
240
241    protected State constructState(ModularXmppClientToServerConnectionInternal connectionInternal) {
242        ModularXmppClientToServerConnection connection = connectionInternal.connection;
243        try {
244            // If stateClassConstructor is null here, then you probably forgot to override the
245            // StateDescriptor.constructState() method?
246            return stateClassConstructor.newInstance(connection, this, connectionInternal);
247        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
248                        | InvocationTargetException e) {
249            throw new IllegalStateException(e);
250        }
251    }
252
253    @Override
254    public String toString() {
255        return "StateDescriptor " + stateName;
256    }
257}