1 package org.sapia.util.license; 2 3 import java.io.IOException ; 4 import java.util.Calendar ; 5 import java.util.Date ; 6 7 19 public class DurationLicense implements License{ 20 21 static final long serialVersionUID = 1L; 22 23 private Date _startDate; 24 private int _duration; 25 private Date _endDate; 26 private boolean _activated; 27 28 public DurationLicense(int durationDays){ 29 if(durationDays < 1){ 30 throw new IllegalArgumentException ("Duration should be equal to or greater than 1"); 31 } 32 _duration = durationDays; 33 34 } 35 36 39 public Date getStartDate(){ 40 return _startDate; 41 } 42 43 46 public int getDurationDays(){ 47 return _duration; 48 } 49 50 54 public Date getEndDate(){ 55 return _endDate; 56 } 57 58 61 public boolean isValid(Object context) { 62 Date currentDate = new Date (); 63 if(_startDate == null){ 64 activate(null); 65 } 66 return currentDate.before(_endDate); 67 } 68 69 72 public void activate(Object context) { 73 if(!_activated){ 74 Date currentDate = new Date (); 75 init(currentDate); 76 _activated = true; 77 } 78 } 79 80 88 public boolean isValid(Date currentDate){ 89 if(_startDate == null){ 90 activate(null); 91 } 92 return currentDate.before(_endDate); 93 } 94 95 private Date computeEndDate(){ 96 return computeEndDate(_startDate, _duration); 97 } 98 99 private synchronized void init(Date currentDate){ 100 _startDate = new Date (); 101 _endDate = computeEndDate(_startDate, _duration); 102 } 103 104 static Date computeEndDate(Date from, int durationDays){ 105 Calendar cal = Calendar.getInstance(); 106 cal.setTime(from); 107 int i = 1; 108 int day = cal.get(Calendar.DAY_OF_YEAR); 109 for(; i <= durationDays; i++, day++){ 110 if(day > cal.getActualMaximum(Calendar.DAY_OF_YEAR)){ 111 cal.roll(Calendar.YEAR, true); 112 day = 1; 113 } 114 115 cal.roll(Calendar.DAY_OF_YEAR, true); 116 } 117 return cal.getTime(); 118 } 119 120 123 public byte[] getBytes() throws IOException { 124 return Integer.toString(_duration).getBytes(); 125 } 126 127 128 } 129 | Popular Tags |