001/**
002 *
003 * Copyright 2019-2021 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.c2s;
018
019import java.io.PrintWriter;
020import java.io.StringWriter;
021import java.lang.reflect.Constructor;
022import java.lang.reflect.InvocationTargetException;
023import java.util.Arrays;
024import java.util.Collections;
025import java.util.HashMap;
026import java.util.HashSet;
027import java.util.Map;
028import java.util.Set;
029
030import org.jivesoftware.smack.ConnectionConfiguration;
031import org.jivesoftware.smack.SmackConfiguration;
032import org.jivesoftware.smack.fsm.StateDescriptor;
033import org.jivesoftware.smack.fsm.StateDescriptorGraph;
034import org.jivesoftware.smack.fsm.StateDescriptorGraph.GraphVertex;
035import org.jivesoftware.smack.util.CollectionUtil;
036
037public final class ModularXmppClientToServerConnectionConfiguration extends ConnectionConfiguration {
038
039    final Set<ModularXmppClientToServerConnectionModuleDescriptor> moduleDescriptors;
040
041    final GraphVertex<StateDescriptor> initialStateDescriptorVertex;
042
043    private ModularXmppClientToServerConnectionConfiguration(Builder builder) {
044        super(builder);
045
046        moduleDescriptors = Collections.unmodifiableSet(CollectionUtil.newSetWith(builder.modulesDescriptors.values()));
047
048        Set<Class<? extends StateDescriptor>> backwardEdgeStateDescriptors = new HashSet<>();
049        // Add backward edges from configured connection modules. Note that all state descriptors from module
050        // descriptors are backwards edges.
051        for (ModularXmppClientToServerConnectionModuleDescriptor moduleDescriptor : moduleDescriptors) {
052            Set<Class<? extends StateDescriptor>> moduleStateDescriptors = moduleDescriptor.getStateDescriptors();
053            backwardEdgeStateDescriptors.addAll(moduleStateDescriptors);
054        }
055
056        try {
057            initialStateDescriptorVertex = StateDescriptorGraph.constructStateDescriptorGraph(backwardEdgeStateDescriptors);
058        }
059        catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
060                        | NoSuchMethodException | SecurityException e) {
061            // TODO: Depending on the exact exception thrown, this potentially indicates an invalid connection
062            // configuration, e.g. there is no edge from disconnected to connected.
063            throw new IllegalStateException(e);
064        }
065
066        for (ModularXmppClientToServerConnectionModuleDescriptor moduleDescriptor : moduleDescriptors) {
067            moduleDescriptor.validateConfiguration(this);
068        }
069    }
070
071    public void printStateGraphInDotFormat(PrintWriter pw, boolean breakStateName) {
072        StateDescriptorGraph.stateDescriptorGraphToDot(Collections.singleton(initialStateDescriptorVertex), pw,
073                        breakStateName);
074    }
075
076    public String getStateGraphInDotFormat() {
077        StringWriter sw = new StringWriter();
078        PrintWriter pw = new PrintWriter(sw);
079
080        printStateGraphInDotFormat(pw, true);
081
082        return sw.toString();
083    }
084
085    public static Builder builder() {
086        return new Builder();
087    }
088
089    public static final class Builder
090                    extends ConnectionConfiguration.Builder<Builder, ModularXmppClientToServerConnectionConfiguration> {
091
092        private final Map<Class<? extends ModularXmppClientToServerConnectionModuleDescriptor>, ModularXmppClientToServerConnectionModuleDescriptor> modulesDescriptors = new HashMap<>();
093
094        private Builder() {
095            SmackConfiguration.addAllKnownModulesTo(this);
096        }
097
098        @Override
099        public ModularXmppClientToServerConnectionConfiguration build() {
100            return new ModularXmppClientToServerConnectionConfiguration(this);
101        }
102
103        public void addModule(ModularXmppClientToServerConnectionModuleDescriptor connectionModule) {
104            Class<? extends ModularXmppClientToServerConnectionModuleDescriptor> moduleDescriptorClass = connectionModule.getClass();
105            if (modulesDescriptors.containsKey(moduleDescriptorClass)) {
106                throw new IllegalArgumentException("A connection module for " + moduleDescriptorClass + " is already configured");
107            }
108            modulesDescriptors.put(moduleDescriptorClass, connectionModule);
109        }
110
111        @SuppressWarnings("unchecked")
112        public Builder addModule(Class<? extends ModularXmppClientToServerConnectionModuleDescriptor> moduleClass) {
113            Class<?>[] declaredClasses = moduleClass.getDeclaredClasses();
114
115            Class<? extends ModularXmppClientToServerConnectionModuleDescriptor.Builder> builderClass = null;
116            for (Class<?> declaredClass : declaredClasses) {
117                if (!ModularXmppClientToServerConnectionModuleDescriptor.Builder.class.isAssignableFrom(declaredClass)) {
118                    continue;
119                }
120
121                builderClass = (Class<? extends ModularXmppClientToServerConnectionModuleDescriptor.Builder>) declaredClass;
122                break;
123            }
124
125            if (builderClass == null) {
126                throw new IllegalArgumentException(
127                                "Found no builder for " + moduleClass + ". Delcared classes: " + Arrays.toString(declaredClasses));
128            }
129
130            return with(builderClass).buildModule();
131        }
132
133        public <B extends ModularXmppClientToServerConnectionModuleDescriptor.Builder> B with(
134                        Class<? extends B> moduleDescriptorBuilderClass) {
135            Constructor<? extends B> moduleDescriptorBuilderCosntructor;
136            try {
137                moduleDescriptorBuilderCosntructor = moduleDescriptorBuilderClass.getDeclaredConstructor(
138                                ModularXmppClientToServerConnectionConfiguration.Builder.class);
139            } catch (NoSuchMethodException | SecurityException e) {
140                throw new IllegalArgumentException(e);
141            }
142
143            moduleDescriptorBuilderCosntructor.setAccessible(true);
144
145            B moduleDescriptorBuilder;
146            try {
147                moduleDescriptorBuilder = moduleDescriptorBuilderCosntructor.newInstance(this);
148            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
149                            | InvocationTargetException e) {
150                throw new IllegalArgumentException(e);
151            }
152
153            return moduleDescriptorBuilder;
154        }
155
156        public Builder removeModule(Class<? extends ModularXmppClientToServerConnectionModuleDescriptor> moduleClass) {
157            modulesDescriptors.remove(moduleClass);
158            return getThis();
159        }
160
161        public Builder removeAllModules() {
162            modulesDescriptors.clear();
163            return getThis();
164        }
165
166        @Override
167        protected Builder getThis() {
168            return this;
169        }
170    }
171}