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.customer;
35  
36  import java.time.LocalDate;
37  import java.util.ArrayList;
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 CustomerService#getInstance()}.
52   */
53  public class CustomerService {
54  
55      private static CustomerService instance;
56      private static final Logger LOGGER = Logger.getLogger(CustomerService.class.getName());
57  
58      private final HashMap<Long, Customer> contacts = new HashMap<>();
59      private long nextId = 0;
60  
61      private CustomerService() {
62      }
63  
64      /**
65       * @return a reference to an example facade for Customer objects.
66       */
67      public static CustomerService getInstance() {
68          if (instance == null) {
69              instance = new CustomerService();
70              instance.ensureTestData();
71          }
72          return instance;
73      }
74  
75      /**
76       * @return all available Customer objects.
77       */
78      public synchronized List<Customer> 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<Customer> findAll(String stringFilter) {
91          ArrayList<Customer> arrayList = getCustomers(stringFilter);
92          Collections.sort(arrayList, new Comparator<Customer>() {
93  
94              @Override
95              public int compare(Customer o1, Customer 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<Customer> findAll(String stringFilter, int start, int maxresults) {
115         ArrayList<Customer> arrayList = getCustomers(stringFilter);
116         Collections.sort(arrayList, new Comparator<Customer>() {
117 
118             @Override
119             public int compare(Customer o1, Customer 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<Customer> getCustomers(String stringFilter) {
131         ArrayList<Customer> arrayList = new ArrayList<>();
132         for (Customer 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(CustomerService.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(Customer 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(Customer 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 = (Customer) 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             final String[] names = new String[] { "Gabrielle Patel", "Brian Robinson", "Eduardo Haugen",
192                     "Koen Johansen", "Alejandro Macdonald", "Angel Karlsson", "Yahir Gustavsson", "Haiden Svensson",
193                     "Emily Stewart", "Corinne Davis", "Ryann Davis", "Yurem Jackson", "Kelly Gustavsson",
194                     "Eileen Walker", "Katelyn Martin", "Israel Carlsson", "Quinn Hansson", "Makena Smith",
195                     "Danielle Watson", "Leland Harris", "Gunner Karlsen", "Jamar Olsson", "Lara Martin",
196                     "Ann Andersson", "Remington Andersson", "Rene Carlsson", "Elvis Olsen", "Solomon Olsen",
197                     "Jaydan Jackson", "Bernard Nilsen", "Saimir Gasa" };
198 
199             final String[] childrenNames = new String[] { "Child One", "Child Two" };
200 
201             Random r = new Random(0);
202             for (String name : names) {
203                 String[] split = name.split(" ");
204                 Customer c = new Customer();
205                 c.setFirstName(split[0]);
206                 c.setLastName(split[1]);
207                 c.setEmail(split[0].toLowerCase() + "@" + split[1].toLowerCase() + ".com");
208                 c.setStatus(CustomerStatus.values()[r.nextInt(CustomerStatus.values().length)]);
209                 int daysOld = 0 - r.nextInt(365 * 15 + 365 * 60);
210                 c.setBirthDate(LocalDate.now().plusDays(daysOld));
211 
212                 List<Customer> children = new ArrayList<>();
213                 for (String childName : childrenNames) {
214                     String[] spaceSplit = childName.split(" ");
215                     Customer child = new Customer();
216                     child.setFirstName(spaceSplit[0]);
217                     child.setLastName(spaceSplit[1]);
218                     child.setEmail(spaceSplit[0].toLowerCase() + "@" + spaceSplit[1].toLowerCase() + ".com");
219                     child.setStatus(CustomerStatus.values()[r.nextInt(CustomerStatus.values().length)]);
220                     //child.setId(nextId++);
221                     int days = 0 - r.nextInt(365 * 15 + 365 * 60);
222                     child.setBirthDate(LocalDate.now().plusDays(days));
223 
224                     children.add(child);
225                 }
226                 c.setChildren(children);
227                 save(c);
228             }
229         }
230     }
231 }