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