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