Coverage Report - org.codeforamerica.open311.internals.caching.CacheableObject
 
Classes in this File Line Coverage Branch Coverage Complexity
CacheableObject
88%
16/18
75%
3/4
2.2
 
 1  
 package org.codeforamerica.open311.internals.caching;
 2  
 
 3  
 import java.io.IOException;
 4  
 import java.io.Serializable;
 5  
 import java.util.Date;
 6  
 
 7  
 import net.iharder.Base64;
 8  
 
 9  
 import org.joda.time.DateTime;
 10  
 
 11  
 /**
 12  
  * A pair of serializable, expiration date.
 13  
  * 
 14  
  * @author Santiago MunĂ­n <santimunin@gmail.com>
 15  
  * 
 16  
  */
 17  
 public class CacheableObject implements Serializable {
 18  
 
 19  
         private static final long serialVersionUID = -108175395476829305L;
 20  
         private Serializable object;
 21  
         private Date expirationTime;
 22  
 
 23  
         public CacheableObject(Serializable object, int hoursToLive) {
 24  12
                 super();
 25  12
                 this.object = object;
 26  12
                 this.expirationTime = new DateTime().plusHours(hoursToLive).toDate();
 27  12
         }
 28  
 
 29  33
         public CacheableObject(String base64object) {
 30  
                 try {
 31  33
                         CacheableObject thisObject = (CacheableObject) Base64
 32  
                                         .decodeToObject(base64object);
 33  11
                         this.object = thisObject.object;
 34  11
                         this.expirationTime = thisObject.expirationTime;
 35  22
                 } catch (Exception e) {
 36  11
                 }
 37  33
         }
 38  
 
 39  
         public Object getObject() {
 40  33
                 if (expirationTime != null) {
 41  11
                         return expirationTime.after(new Date()) ? object : null;
 42  
                 }
 43  22
                 return null;
 44  
         }
 45  
 
 46  
         /**
 47  
          * Return a serialized version of the object.
 48  
          * 
 49  
          * @return A base64 encoded string version of the object.
 50  
          */
 51  
         public String serialize() {
 52  12
                 return serialize(this);
 53  
         }
 54  
 
 55  
         public static String serialize(Serializable object) {
 56  
                 try {
 57  16
                         return new String(Base64.encodeObject(object));
 58  0
                 } catch (IOException e) {
 59  0
                         return null;
 60  
                 }
 61  
         }
 62  
 }