View Javadoc
1   /**
2    * This file Copyright (c) 2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.poc.task;
35  
36  import java.util.ArrayList;
37  import java.util.Calendar;
38  import java.util.Collections;
39  import java.util.Comparator;
40  import java.util.HashMap;
41  import java.util.List;
42  import java.util.Random;
43  import java.util.logging.Level;
44  import java.util.logging.Logger;
45  
46  /**
47   * An in memory dummy "database" for the example purposes. In a typical Java app
48   * this class would be replaced by e.g. EJB or a Spring based service class.
49   * <p>
50   * In demos/tutorials/examples, get a reference to this service class with
51   * {@link MagnoliaTaskService#getInstance()}.
52   */
53  public class MagnoliaTaskService {
54  
55      private static MagnoliaTaskService instance;
56      private static final Logger LOGGER = Logger.getLogger(MagnoliaTaskService.class.getName());
57  
58      private final HashMap<Long, MagnoliaTask> contacts = new HashMap<>();
59      private long nextId = 0;
60  
61      private MagnoliaTaskService() {
62      }
63  
64      /**
65       * @return a reference to an example facade for Customer objects.
66       */
67      public static MagnoliaTaskService getInstance() {
68          if (instance == null) {
69              instance = new MagnoliaTaskService();
70              instance.ensureTestData();
71          }
72          return instance;
73      }
74  
75      /**
76       * @return all available Customer objects.
77       */
78      public synchronized List<MagnoliaTask> findAll() {
79          return findAll(null);
80      }
81  
82      /**
83       * Finds all Customer's that match given filter.
84       *
85       * @param stringFilter
86       *            filter that returned objects should match or null/empty string
87       *            if all objects should be returned.
88       * @return list a Customer objects
89       */
90      public synchronized List<MagnoliaTask> findAll(String stringFilter) {
91          ArrayList<MagnoliaTask> arrayList = getCustomers(stringFilter);
92          Collections.sort(arrayList, new Comparator<MagnoliaTask>() {
93  
94              @Override
95              public int compare(MagnoliaTask../../../../info/magnolia/poc/task/MagnoliaTask.html#MagnoliaTask">MagnoliaTask o1, MagnoliaTask o2) {
96                  return (int) (o2.getId() - o1.getId());
97              }
98          });
99          return arrayList;
100     }
101 
102     /**
103      * Finds all Customer's that match given filter and limits the resultset.
104      *
105      * @param stringFilter
106      *            filter that returned objects should match or null/empty string
107      *            if all objects should be returned.
108      * @param start
109      *            the index of first result
110      * @param maxresults
111      *            maximum result count
112      * @return list a Customer objects
113      */
114     public synchronized List<MagnoliaTask> findAll(String stringFilter, int start, int maxresults) {
115         ArrayList<MagnoliaTask> arrayList = getCustomers(stringFilter);
116         Collections.sort(arrayList, new Comparator<MagnoliaTask>() {
117 
118             @Override
119             public int compare(MagnoliaTask../../../../info/magnolia/poc/task/MagnoliaTask.html#MagnoliaTask">MagnoliaTask o1, MagnoliaTask o2) {
120                 return (int) (o2.getId() - o1.getId());
121             }
122         });
123         int end = start + maxresults;
124         if (end > arrayList.size()) {
125             end = arrayList.size();
126         }
127         return arrayList.subList(start, end);
128     }
129 
130     private ArrayList<MagnoliaTask> getCustomers(String stringFilter) {
131         ArrayList<MagnoliaTask> arrayList = new ArrayList<>();
132         for (MagnoliaTask contact : contacts.values()) {
133             try {
134                 boolean passesFilter = (stringFilter == null || stringFilter.isEmpty())
135                         || contact.toString().toLowerCase().contains(stringFilter.toLowerCase());
136                 if (passesFilter) {
137                     arrayList.add(contact.clone());
138                 }
139             } catch (CloneNotSupportedException ex) {
140                 Logger.getLogger(MagnoliaTaskService.class.getName()).log(Level.SEVERE, null, ex);
141             }
142         }
143         return arrayList;
144     }
145 
146     /**
147      * @return the amount of all customers in the system
148      */
149     public synchronized long count() {
150         return contacts.size();
151     }
152 
153     /**
154      * Deletes a customer from a system
155      *
156      * @param value
157      *            the Customer to be deleted
158      */
159     public synchronized void delete(MagnoliaTask value) {
160         contacts.remove(value.getId());
161     }
162 
163     /**
164      * Persists or updates customer in the system. Also assigns an identifier
165      * for new Customer instances.
166      *
167      * @param entry
168      */
169     public synchronized void save(MagnoliaTask entry) {
170         if (entry == null) {
171             LOGGER.log(Level.SEVERE,
172                     "Customer is null. Are you sure you have connected your form to the application as described in tutorial chapter 7?");
173             return;
174         }
175         if (entry.getId() == null) {
176             entry.setId(nextId++);
177         }
178         try {
179             entry = (MagnoliaTask) entry.clone();
180         } catch (Exception ex) {
181             throw new RuntimeException(ex);
182         }
183         contacts.put(entry.getId(), entry);
184     }
185 
186     /**
187      * Sample data generation
188      */
189     public void ensureTestData() {
190         if (findAll().isEmpty()) {
191             Random r = new Random(0);
192             for (int i = 0; i<10; i++ ) {
193                 MagnoliaTaskask.html#MagnoliaTask">MagnoliaTask task = new MagnoliaTask();
194                 task.setName("Publication request");
195                 task.setDescription("Enhance Your Brand Potential With loong text that should not be shown");
196                 task.setStatus(MagnoliaTaskStatus.values()[r.nextInt(MagnoliaTaskStatus.values().length)]);
197                 int daysOld = 0 - r.nextInt(365 * 15 + 365 * 60);
198                 Calendar calendar = Calendar.getInstance();
199                 calendar.add(Calendar.DATE, daysOld);
200                 task.setLastChange(calendar.getTime());
201                 task.setSender("Administrator");
202                 task.setSendTo("travel-demo-publishers");
203                 task.setAssigned("Monkey");
204                 save(task);
205             }
206         }
207     }
208 }