001// ***************************************************************************************************************************
002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *
003// * distributed with this work for additional information regarding copyright ownership.  The ASF licenses this file        *
004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance            *
005// * with the License.  You may obtain a copy of the License at                                                              *
006// *                                                                                                                         *
007// *  http://www.apache.org/licenses/LICENSE-2.0                                                                             *
008// *                                                                                                                         *
009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an  *
010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the        *
011// * specific language governing permissions and limitations under the License.                                              *
012// ***************************************************************************************************************************
013package org.apache.juneau;
014
015import static org.apache.juneau.internal.StringUtils.*;
016
017import java.lang.reflect.*;
018import java.text.*;
019import java.util.*;
020
021import org.apache.juneau.internal.*;
022import org.apache.juneau.json.*;
023import org.apache.juneau.serializer.*;
024
025/**
026 * A one-time-use non-thread-safe object that's meant to be used once and then thrown away.
027 *
028 * <p>
029 * Serializers and parsers use session objects to retrieve config properties and to use it as a scratchpad during
030 * serialize and parse actions.
031 */
032public abstract class Session {
033
034   private JuneauLogger logger;
035
036   private final ObjectMap properties;
037   private Map<String,Object> cache;
038   private List<String> warnings;                 // Any warnings encountered.
039
040
041   /**
042    * Default constructor.
043    *
044    * @param args
045    *    Runtime arguments.
046    */
047   protected Session(SessionArgs args) {
048      this.properties = args.properties == null ? ObjectMap.EMPTY_MAP : args.properties;
049   }
050
051   /**
052    * Returns <jk>true</jk> if this session has the specified property defined.
053    *
054    * @param key The property key.
055    * @return <jk>true</jk> if this session has the specified property defined.
056    */
057   public final boolean hasProperty(String key) {
058      return properties != null && properties.containsKey(key);
059   }
060
061   /**
062    * Returns the session property with the specified key.
063    *
064    * <p>
065    * The returned type is the raw value of the property.
066    *
067    * @param key The property key.
068    * @return The session property, or <jk>null</jk> if the property does not exist.
069    */
070   public final Object getProperty(String key) {
071      if (properties == null)
072         return null;
073      return properties.get(key);
074   }
075
076   /**
077    * Returns the session property with the specified key and type.
078    *
079    * @param key The property key.
080    * @param type The type to convert the property to.
081    * @param def The default value if the session property does not exist or is <jk>null</jk>.
082    * @return The session property.
083    */
084   @SuppressWarnings("unchecked")
085   public final <T> T getProperty(String key, Class<T> type, T def) {
086      if (properties == null)
087         return def;
088      type = (Class<T>)ClassUtils.getWrapperIfPrimitive(type);
089      T t = properties.get(key, type);
090      return t == null ? def : t;
091   }
092
093   /**
094    * Same as {@link #getProperty(String, Class, Object)} but allows for more than one default value.
095    *
096    * @param key The property key.
097    * @param type The type to convert the property to.
098    * @param def
099    *    The default values if the session property does not exist or is <jk>null</jk>.
100    *    The first non-null value is returned.
101    * @return The session property.
102    */
103   @SafeVarargs
104   public final <T> T getProperty(String key, Class<T> type, T...def) {
105      return getProperty(key, type, ObjectUtils.firstNonNull(def));
106   }
107
108   /**
109    * Returns the session class property with the specified name.
110    *
111    * @param key The property name.
112    * @param type The class type of the property.
113    * @param def The default value.
114    * @return The property value, or the default value if it doesn't exist.
115    */
116   @SuppressWarnings("unchecked")
117   public final <T> Class<? extends T> getClassProperty(String key, Class<T> type, Class<? extends T> def) {
118      return getProperty(key, Class.class, def);
119   }
120
121   /**
122    * Returns an instantiation of the specified class property.
123    *
124    * @param key The property name.
125    * @param type The class type of the property.
126    * @param def
127    *    The default instance or class to instantiate if the property doesn't exist.
128    * @return A new property instance.
129    */
130   public <T> T getInstanceProperty(String key, Class<T> type, Object def) {
131      return newInstance(type, getProperty(key), def);
132   }
133
134   /**
135    * Returns the specified property as an array of instantiated objects.
136    *
137    * @param key The property name.
138    * @param type The class type of the property.
139    * @param def The default object to return if the property doesn't exist.
140    * @return A new property instance.
141    */
142   @SuppressWarnings("unchecked")
143   public <T> T[] getInstanceArrayProperty(String key, Class<T> type, T[] def) {
144      Object o = getProperty(key);
145      T[] t = null;
146      if (o == null)
147         t = def;
148      else if (o.getClass().isArray()) {
149         if (o.getClass().getComponentType() == type)
150            t = (T[])o;
151         else {
152            t = (T[])Array.newInstance(type, Array.getLength(o));
153            for (int i = 0; i < Array.getLength(o); i++)
154               t[i] = newInstance(type, Array.get(o, i), null);
155         }
156      } else if (o instanceof Collection) {
157         Collection<?> c = (Collection<?>)o;
158         t = (T[])Array.newInstance(type, c.size());
159         int i = 0;
160         for (Object o2 : c)
161            t[i++] = newInstance(type, o2, null);
162      }
163      if (t != null)
164         return t;
165      throw new ConfigException("Could not instantiate property ''{0}'' as type {1}", key, type);
166   }
167
168   /**
169    * Returns the session properties.
170    *
171    * @return The session properties passed in through the constructor.
172    */
173   protected ObjectMap getProperties() {
174      return properties;
175   }
176
177   /**
178    * Returns the session property keys.
179    *
180    * @return The session property keys passed in through the constructor.
181    */
182   public Set<String> getPropertyKeys() {
183      return properties.keySet();
184   }
185
186   @SuppressWarnings("unchecked")
187   private <T> T newInstance(Class<T> type, Object o, Object def) {
188      T t = null;
189      if (o == null) {
190         if (def == null)
191            return null;
192         t = ClassUtils.newInstance(type, def);
193      }
194      else if (type.isInstance(o))
195         t = (T)o;
196      else if (o.getClass() == Class.class)
197         t = ClassUtils.newInstance(type, o);
198      else if (o.getClass() == String.class)
199         t = ClassUtils.fromString(type, o.toString());
200      if (t != null)
201         return t;
202      throw new ConfigException("Could not instantiate type ''{0}'' as type {1}", o, type);
203   }
204
205   /**
206    * Adds an arbitrary object to this session's cache.
207    *
208    * <p>
209    * Can be used to store objects for reuse during a session.
210    *
211    * @param key The key.  Can be any string.
212    * @param val The cached object.
213    */
214   public final void addToCache(String key, Object val) {
215      if (cache == null)
216         cache = new TreeMap<>();
217      cache.put(key, val);
218   }
219
220   /**
221    * Adds arbitrary objects to this session's cache.
222    *
223    * <p>
224    * Can be used to store objects for reuse during a session.
225    *
226    * @param cacheObjects
227    *    The objects to add to this session's cache.
228    *    No-op if <jk>null</jk>.
229    */
230   public final void addToCache(Map<String,Object> cacheObjects) {
231      if (cacheObjects != null) {
232         if (cache == null)
233            cache = new TreeMap<>();
234         cache.putAll(cacheObjects);
235      }
236   }
237
238   /**
239    * Returns an object stored in the session cache.
240    *
241    * @param c The class type of the object.
242    * @param key The session object key.
243    * @return The cached object, or <jk>null</jk> if it doesn't exist.
244    */
245   @SuppressWarnings("unchecked")
246   public final <T> T getFromCache(Class<T> c, String key) {
247      return cache == null ? null : (T)cache.get(key);
248   }
249
250   /**
251    * Logs a warning message.
252    *
253    * @param msg The warning message.
254    * @param args Optional {@link MessageFormat}-style arguments.
255    */
256   public final void addWarning(String msg, Object... args) {
257      if (warnings == null)
258         warnings = new LinkedList<>();
259      getLogger().warning(msg, args);
260      warnings.add((warnings.size() + 1) + ": " + format(msg, args));
261   }
262
263   /**
264    * Returns <jk>true</jk> if warnings occurred in this session.
265    *
266    * @return <jk>true</jk> if warnings occurred in this session.
267    */
268   public final boolean hasWarnings() {
269      return warnings != null && warnings.size() > 0;
270   }
271
272   /**
273    * Returns the warnings that occurred in this session.
274    *
275    * @return The warnings that occurred in this session, or <jk>null</jk> if no warnings occurred.
276    */
277   public final List<String> getWarnings() {
278      return warnings;
279   }
280
281   /**
282    * Returns the logger associated with this session.
283    *
284    * <p>
285    * Subclasses can override this method to provide their own logger.
286    *
287    * @return The logger associated with this session.
288    */
289   protected final JuneauLogger getLogger() {
290      if (logger == null)
291         logger = JuneauLogger.getLogger(getClass());
292      return logger;
293   }
294
295   /**
296    * Returns the properties defined on this bean context as a simple map for debugging purposes.
297    *
298    * @return A new map containing the properties defined on this context.
299    */
300   public ObjectMap asMap() {
301      return new ObjectMap();
302   }
303
304   @Override /* Object */
305   public String toString() {
306      try {
307         return asMap().toString(SimpleJsonSerializer.DEFAULT_READABLE);
308      } catch (SerializeException e) {
309         return e.getLocalizedMessage();
310      }
311   }
312
313   /**
314    * Throws a {@link BeanRuntimeException} if any warnings occurred in this session.
315    */
316   public void checkForWarnings() {
317      if (warnings != null && ! warnings.isEmpty())
318         throw new BeanRuntimeException("Warnings occurred in session: \n" + join(getWarnings(), "\n"));
319   }
320}