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.*;
016import static org.apache.juneau.internal.ClassUtils.*;
017
018import java.lang.reflect.*;
019import java.text.*;
020import java.util.*;
021
022import org.apache.juneau.internal.*;
023import org.apache.juneau.json.*;
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      Object o = properties.get(key);
089      if (o == null)
090         return def;
091      type = (Class<T>)getClassInfo(type).getWrapperIfPrimitive();
092      T t = properties.get(key, type);
093      return t == null ? def : t;
094   }
095
096   /**
097    * Same as {@link #getProperty(String, Class, Object)} but allows for more than one default value.
098    *
099    * @param key The property key.
100    * @param type The type to convert the property to.
101    * @param def
102    *    The default values if the session property does not exist or is <jk>null</jk>.
103    *    The first non-null value is returned.
104    * @return The session property.
105    */
106   @SafeVarargs
107   public final <T> T getProperty(String key, Class<T> type, T...def) {
108      return getProperty(key, type, ObjectUtils.firstNonNull(def));
109   }
110
111   /**
112    * Returns the session class property with the specified name.
113    *
114    * @param key The property name.
115    * @param type The class type of the property.
116    * @param def The default value.
117    * @return The property value, or the default value if it doesn't exist.
118    */
119   @SuppressWarnings("unchecked")
120   public final <T> Class<? extends T> getClassProperty(String key, Class<T> type, Class<? extends T> def) {
121      return getProperty(key, Class.class, def);
122   }
123
124   /**
125    * Returns an instantiation of the specified class property.
126    *
127    * @param key The property name.
128    * @param type The class type of the property.
129    * @param def
130    *    The default instance or class to instantiate if the property doesn't exist.
131    * @return A new property instance.
132    */
133   public <T> T getInstanceProperty(String key, Class<T> type, Object def) {
134      return newInstance(type, getProperty(key), def);
135   }
136
137   /**
138    * Returns the specified property as an array of instantiated objects.
139    *
140    * @param key The property name.
141    * @param type The class type of the property.
142    * @param def The default object to return if the property doesn't exist.
143    * @return A new property instance.
144    */
145   @SuppressWarnings("unchecked")
146   public <T> T[] getInstanceArrayProperty(String key, Class<T> type, T[] def) {
147      Object o = getProperty(key);
148      T[] t = null;
149      if (o == null)
150         t = def;
151      else if (o.getClass().isArray()) {
152         if (o.getClass().getComponentType() == type)
153            t = (T[])o;
154         else {
155            t = (T[])Array.newInstance(type, Array.getLength(o));
156            for (int i = 0; i < Array.getLength(o); i++)
157               t[i] = newInstance(type, Array.get(o, i), null);
158         }
159      } else if (o instanceof Collection) {
160         Collection<?> c = (Collection<?>)o;
161         t = (T[])Array.newInstance(type, c.size());
162         int i = 0;
163         for (Object o2 : c)
164            t[i++] = newInstance(type, o2, null);
165      }
166      if (t != null)
167         return t;
168      throw new ConfigException("Could not instantiate property ''{0}'' as type {1}", key, type);
169   }
170
171   /**
172    * Returns the session properties.
173    *
174    * @return The session properties passed in through the constructor.
175    */
176   protected ObjectMap getProperties() {
177      return properties;
178   }
179
180   /**
181    * Returns the session property keys.
182    *
183    * @return The session property keys passed in through the constructor.
184    */
185   public Set<String> getPropertyKeys() {
186      return properties.keySet();
187   }
188
189   @SuppressWarnings("unchecked")
190   private <T> T newInstance(Class<T> type, Object o, Object def) {
191      T t = null;
192      if (o == null) {
193         if (def == null)
194            return null;
195         t = castOrCreate(type, def);
196      }
197      else if (type.isInstance(o))
198         t = (T)o;
199      else if (o.getClass() == Class.class)
200         t = castOrCreate(type, o);
201      else if (o.getClass() == String.class)
202         t = ClassUtils.fromString(type, o.toString());
203      if (t != null)
204         return t;
205      throw new ConfigException("Could not instantiate type ''{0}'' as type {1}", o, type);
206   }
207
208   /**
209    * Adds an arbitrary object to this session's cache.
210    *
211    * <p>
212    * Can be used to store objects for reuse during a session.
213    *
214    * @param key The key.  Can be any string.
215    * @param val The cached object.
216    */
217   public final void addToCache(String key, Object val) {
218      if (cache == null)
219         cache = new TreeMap<>();
220      cache.put(key, val);
221   }
222
223   /**
224    * Adds arbitrary objects to this session's cache.
225    *
226    * <p>
227    * Can be used to store objects for reuse during a session.
228    *
229    * @param cacheObjects
230    *    The objects to add to this session's cache.
231    *    No-op if <jk>null</jk>.
232    */
233   public final void addToCache(Map<String,Object> cacheObjects) {
234      if (cacheObjects != null) {
235         if (cache == null)
236            cache = new TreeMap<>();
237         cache.putAll(cacheObjects);
238      }
239   }
240
241   /**
242    * Returns an object stored in the session cache.
243    *
244    * @param c The class type of the object.
245    * @param key The session object key.
246    * @return The cached object, or <jk>null</jk> if it doesn't exist.
247    */
248   @SuppressWarnings("unchecked")
249   public final <T> T getFromCache(Class<T> c, String key) {
250      return cache == null ? null : (T)cache.get(key);
251   }
252
253   /**
254    * Logs a warning message.
255    *
256    * @param msg The warning message.
257    * @param args Optional {@link MessageFormat}-style arguments.
258    */
259   public final void addWarning(String msg, Object... args) {
260      if (warnings == null)
261         warnings = new LinkedList<>();
262      getLogger().warning(msg, args);
263      warnings.add((warnings.size() + 1) + ": " + format(msg, args));
264   }
265
266   /**
267    * Returns <jk>true</jk> if warnings occurred in this session.
268    *
269    * @return <jk>true</jk> if warnings occurred in this session.
270    */
271   public final boolean hasWarnings() {
272      return warnings != null && warnings.size() > 0;
273   }
274
275   /**
276    * Returns the warnings that occurred in this session.
277    *
278    * @return The warnings that occurred in this session, or <jk>null</jk> if no warnings occurred.
279    */
280   public final List<String> getWarnings() {
281      return warnings;
282   }
283
284   /**
285    * Returns the logger associated with this session.
286    *
287    * <p>
288    * Subclasses can override this method to provide their own logger.
289    *
290    * @return The logger associated with this session.
291    */
292   protected final JuneauLogger getLogger() {
293      if (logger == null)
294         logger = JuneauLogger.getLogger(getClass());
295      return logger;
296   }
297
298   /**
299    * Throws a {@link BeanRuntimeException} if any warnings occurred in this session.
300    */
301   public void checkForWarnings() {
302      if (warnings != null && ! warnings.isEmpty())
303         throw new BeanRuntimeException("Warnings occurred in session: \n" + join(getWarnings(), "\n"));
304   }
305
306   //-----------------------------------------------------------------------------------------------------------------
307   // Other methods
308   //-----------------------------------------------------------------------------------------------------------------
309
310   /**
311    * Returns the properties defined on this bean context as a simple map for debugging purposes.
312    *
313    * @return A new map containing the properties defined on this context.
314    */
315   public ObjectMap toMap() {
316      return new DefaultFilteringObjectMap();
317   }
318
319   @Override /* Object */
320   public String toString() {
321      return SimpleJsonSerializer.DEFAULT_READABLE.toString(toMap());
322   }
323}