View Javadoc

1   package org.kuali.ole.service;
2   
3   import org.apache.commons.io.FileUtils;
4   import org.apache.log4j.Logger;
5   import org.kuali.ole.OLEConstants;
6   import org.kuali.ole.PropertyUtil;
7   import org.kuali.ole.ingest.FileUtil;
8   import org.kuali.ole.ingest.OlePatronRecordHandler;
9   import org.kuali.ole.ingest.OlePatronXMLSchemaValidator;
10  import org.kuali.ole.ingest.pojo.*;
11  import org.kuali.ole.patron.api.OlePatronDefinition;
12  import org.kuali.ole.patron.bo.*;
13  import org.kuali.ole.patron.constant.OLEPatronConstant;
14  import org.kuali.rice.kim.impl.identity.address.EntityAddressBo;
15  import org.kuali.rice.kim.impl.identity.address.EntityAddressTypeBo;
16  import org.kuali.rice.kim.impl.identity.email.EntityEmailBo;
17  import org.kuali.rice.kim.impl.identity.email.EntityEmailTypeBo;
18  import org.kuali.rice.kim.impl.identity.entity.EntityBo;
19  import org.kuali.rice.kim.impl.identity.name.EntityNameBo;
20  import org.kuali.rice.kim.impl.identity.name.EntityNameTypeBo;
21  import org.kuali.rice.kim.impl.identity.phone.EntityPhoneBo;
22  import org.kuali.rice.kim.impl.identity.phone.EntityPhoneTypeBo;
23  import org.kuali.rice.krad.service.BusinessObjectService;
24  import org.kuali.rice.krad.service.KRADServiceLocator;
25  import org.kuali.rice.location.impl.country.CountryBo;
26  import org.kuali.rice.location.impl.state.StateBo;
27  import org.xml.sax.SAXException;
28  
29  import java.io.File;
30  import java.io.IOException;
31  import java.net.URISyntaxException;
32  import java.net.URL;
33  import java.util.*;
34  
35  /**
36   *  OlePatronConverterService generates list of patron to perform ole patron operation.
37   */
38  public class OlePatronConverterService {
39  
40      private static final Logger LOG = Logger.getLogger(OlePatronConverterService.class);
41  
42      private BusinessObjectService businessObjectService;
43      private OlePatronRecordHandler olePatronRecordHandler;
44      private OlePatronService olePatronService;
45  
46      /**
47       * Gets the value of olePatronService which is of type OlePatronService
48       * @return olePatronService(OlePatronService)
49       */
50      public OlePatronService getOlePatronService() {
51          return this.olePatronService;
52      }
53  
54      /**
55       * Sets the value for olePatronService which is of type OlePatronService
56       * @param olePatronService(OlePatronService)
57       */
58      public void setOlePatronService(OlePatronService olePatronService) {
59          this.olePatronService = olePatronService;
60      }
61  
62      /**
63       * This method will get the values from the ingested xml file, check the entity id and addUnmatchedPatron (from screen) .
64       * @param fileContent
65       * @param addUnMatchedPatronFlag
66       * @param fileName
67       * @param olePatronIngestSummaryRecord
68       * @return  list of OlePatronDocument
69       * @throws java.io.IOException
70       * @throws java.net.URISyntaxException
71       */
72      public List<OlePatronDocument> persistPatronFromFileContent(String fileContent, boolean addUnMatchedPatronFlag, String fileName,OlePatronIngestSummaryRecord olePatronIngestSummaryRecord) throws IOException, URISyntaxException {
73          List<OlePatronDocument> savedOlePatronDocuments = new ArrayList<OlePatronDocument>();
74          OlePatronGroup olePatronGroup = new OlePatronGroup();
75          OlePatronGroup patron = getOlePatronRecordHandler().buildPatronFromFileContent(fileContent);
76          List<OlePatron> createPatronList = new ArrayList<OlePatron>();
77          List<OlePatron> updatePatronList = new ArrayList<OlePatron>();
78          List<OlePatron> rejectedPatronList = new ArrayList<OlePatron>();
79          List<OlePatron> failedPatronList = new ArrayList<OlePatron>();
80          int patronTotCount = patron.getPatronGroup().size();
81          for (int i = 0; i < patron.getPatronGroup().size(); i++) {
82              if (patron.getPatronGroup().get(i).getPatronID() != null && !"".equals(patron.getPatronGroup().get(i).getPatronID())) {
83                  if (isPatronExist(patron.getPatronGroup().get(i).getPatronID())) {
84                      updatePatronList.add(patron.getPatronGroup().get(i));
85                  } else {
86                      if (addUnMatchedPatronFlag) {
87                          createPatronList.add(patron.getPatronGroup().get(i));
88                      } else {
89                          rejectedPatronList.add(patron.getPatronGroup().get(i));
90                      }
91                  }
92              } else {
93                  String patronId = "";
94                  if (addUnMatchedPatronFlag) {
95                      patronId = KRADServiceLocator.getSequenceAccessorService().getNextAvailableSequenceNumber("KRIM_ENTITY_ID_S").toString();
96                      patron.getPatronGroup().get(i).setPatronID(patronId);
97                      createPatronList.add(patron.getPatronGroup().get(i));
98                  } else {
99                      rejectedPatronList.add(patron.getPatronGroup().get(i));
100                 }
101             }
102         }
103         if (createPatronList.size() > 0) {
104             savedOlePatronDocuments.addAll(createOlePatronDocument(createPatronList,failedPatronList));
105             olePatronIngestSummaryRecord.setPatronCreateCount(createPatronList.size());
106             createPatronList.clear();
107         }
108         if (updatePatronList.size() > 0) {
109             savedOlePatronDocuments.addAll(updateOlePatronDocument(updatePatronList,failedPatronList));
110             olePatronIngestSummaryRecord.setPatronUpdateCount(updatePatronList.size());
111             updatePatronList.clear();
112         }
113         if (rejectedPatronList.size() > 0) {
114             olePatronIngestSummaryRecord.setPatronRejectCount(rejectedPatronList.size());
115             rejectedPatronList.clear();
116         }
117         if (failedPatronList.size()>0) {
118             olePatronIngestSummaryRecord.setPatronFailedCount(failedPatronList.size());
119         }
120         olePatronIngestSummaryRecord.setPatronTotCount(patronTotCount);
121         olePatronIngestSummaryRecord.setFileName(fileName);
122         getBusinessObjectService().save(olePatronIngestSummaryRecord);
123         if (failedPatronList.size()>0) {
124             olePatronGroup.setPatronGroup(failedPatronList);
125             String patronXML = getOlePatronRecordHandler().toXML(failedPatronList);
126             saveFailureRecordsForAttachment(patronXML,olePatronIngestSummaryRecord.getOlePatronSummaryId());
127             failedPatronList.clear();
128         }
129         return savedOlePatronDocuments;
130     }
131 
132     /**
133      * This method is for getting the uploaded process message
134      * @param olePatronIngestSummaryRecord
135      * @return message as a string
136      */
137     public String getUploadProcessMessage(OlePatronIngestSummaryRecord olePatronIngestSummaryRecord){
138 
139         String uploadProcessMessage = OLEConstants.PATRON_RECORD_SUCCESS+" Total record : "+olePatronIngestSummaryRecord.getPatronTotCount()+
140                 ", Created record : "+olePatronIngestSummaryRecord.getPatronCreateCount()+
141                 ", Updated record : "+olePatronIngestSummaryRecord.getPatronUpdateCount()+
142                 ", Rejected record : "+olePatronIngestSummaryRecord.getPatronRejectCount()+
143                 ", Failed record : "+olePatronIngestSummaryRecord.getPatronFailedCount();
144         return uploadProcessMessage;
145     }
146 
147     /**
148      * This method will check the entity id from the database , whether it is existing or not.
149      * @param patronId
150      * @return  a boolean flag
151      */
152     public boolean isPatronExist(String patronId) {
153         boolean flag = false;
154         if (getPatron(patronId) != null) {
155             flag = true;
156         } else {
157             flag = false;
158         }
159         return flag;
160     }
161 
162     /**
163      * This method will get the entity id from the EntityBo Object
164      * @param patronId
165      * @return EntityBo object
166      */
167     private EntityBo getPatron(String patronId) {
168         Map<String, Object> criteria = new HashMap<String, Object>(4);
169         criteria.put(OLEConstants.OlePatron.ENTITY_BO_ID, patronId);
170 
171         return getBusinessObjectService().findByPrimaryKey(EntityBo.class, criteria);
172     }
173 
174     /**
175      * This method is for creating a OlePatronDocument
176      * @param createPatronList
177      * @param failedPatronList
178      * @return  list of OlePatronDocument
179      */
180     public List<OlePatronDocument> createOlePatronDocument(List<OlePatron> createPatronList,List<OlePatron> failedPatronList) {
181         List<OlePatronDocument> newPatrons = new ArrayList<OlePatronDocument>();
182         OlePatronDocument olePatronDocument = new OlePatronDocument();
183         OlePatron olePatron;
184         int createPatron = createPatronList.size();
185         for (int i = 0; i < createPatronList.size(); i++) {
186             boolean patronCreateFlag = true;
187             olePatron = new OlePatron();
188             olePatron = createPatronList.get(i);
189             EntityBo kimEntity = new EntityBo();
190             kimEntity.setId(olePatron.getPatronID());
191             olePatronDocument.setEntity(kimEntity);
192             olePatronDocument.setBarcode(olePatron.getBarcode());
193             olePatronDocument.setExpirationDate(olePatron.getExpirationDate());
194             olePatronDocument.setCourtesyNotice(olePatron.getPatronLevelPolicies().isReceivesCourtesyNotice());
195             olePatronDocument.setDeliveryPrivilege(olePatron.getPatronLevelPolicies().isHasDeliveryPrivilege());
196             olePatronDocument.setGeneralBlock(olePatron.getPatronLevelPolicies().isGenerallyBlocked());
197             olePatronDocument.setPagingPrivilege(olePatron.getPatronLevelPolicies().isHasPagingPrivilege());
198             patronCreateFlag &= persistPatronNames(olePatron, olePatronDocument);
199             if(patronCreateFlag)
200             patronCreateFlag &= persistPatronBorrowerType(olePatron, olePatronDocument);
201             if(patronCreateFlag)
202             patronCreateFlag &= persistPatronPostalAddress(olePatron, olePatronDocument);
203             if(patronCreateFlag)
204             patronCreateFlag &= persistPatronPhoneNumbers(olePatron, olePatronDocument);
205             if(patronCreateFlag)
206             patronCreateFlag &= persistPatronEmailAddress(olePatron, olePatronDocument);
207             if(patronCreateFlag)
208             patronCreateFlag &= persistPatronNotes(olePatron, olePatronDocument);
209             olePatronDocument.setActiveIndicator(olePatron.isActive());
210             if (patronCreateFlag) {
211                 OlePatronDefinition patron = getOlePatronService().createPatron(OlePatronDocument.to(olePatronDocument));
212                 newPatrons.add(OlePatronDocument.from(patron));
213             } else {
214                 failedPatronList.add(olePatron);
215             }
216         }
217         createPatronList.removeAll(failedPatronList);
218         return newPatrons;
219     }
220 
221     /**
222      * This method is for updating the OlePatronDocument
223      * @param updatePatronList
224      * @param failedPatronList
225      * @return list of OlePatronDocument
226      */
227     public List<OlePatronDocument> updateOlePatronDocument(List<OlePatron> updatePatronList,List<OlePatron> failedPatronList) {
228         List<OlePatronDocument> updatedPatrons = new ArrayList<OlePatronDocument>();
229         OlePatronDocument olePatronDocument = new OlePatronDocument();
230         OlePatron olePatron;
231         Map criteria = new HashMap<String, String>();
232         for (int i = 0; i < updatePatronList.size(); i++) {
233             olePatron = updatePatronList.get(i);
234             criteria.put(OLEConstants.OlePatron.PATRON_ID, olePatron.getPatronID());
235             List<OlePatronDocument> patronImpls = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, criteria);
236             OlePatronDocument patronDocument;
237             for (Iterator<OlePatronDocument> patronIterator = patronImpls.iterator(); patronIterator.hasNext(); ) {
238                 boolean patronUpdateFlag = true;
239                 patronDocument = patronIterator.next();
240                 olePatronDocument.setOlePatronId(patronDocument.getOlePatronId());
241                 olePatronDocument.setBarcode(olePatron.getBarcode());
242                 olePatronDocument.setExpirationDate(olePatron.getExpirationDate());
243                 olePatronDocument.setCourtesyNotice(olePatron.getPatronLevelPolicies().isReceivesCourtesyNotice());
244                 olePatronDocument.setDeliveryPrivilege(olePatron.getPatronLevelPolicies().isHasDeliveryPrivilege());
245                 olePatronDocument.setGeneralBlock(olePatron.getPatronLevelPolicies().isGenerallyBlocked());
246                 olePatronDocument.setPagingPrivilege(olePatron.getPatronLevelPolicies().isHasPagingPrivilege());
247                 olePatronDocument.setActiveIndicator(olePatron.isActive());
248                 olePatronDocument.setObjectId(patronDocument.getObjectId());
249                 olePatronDocument.setVersionNumber(patronDocument.getVersionNumber());
250 
251                 patronUpdateFlag &= persistPatronNames(olePatron, olePatronDocument);
252                 if(patronUpdateFlag)
253                 patronUpdateFlag &= persistPatronBorrowerType(olePatron, olePatronDocument);
254                 if(patronUpdateFlag)
255                 patronUpdateFlag &= persistPatronPostalAddress(olePatron, olePatronDocument);
256                 if(patronUpdateFlag)
257                 patronUpdateFlag &= persistPatronPhoneNumbers(olePatron, olePatronDocument);
258                 if(patronUpdateFlag)
259                 patronUpdateFlag &= persistPatronEmailAddress(olePatron, olePatronDocument);
260                 if(patronUpdateFlag)
261                 patronUpdateFlag &= persistPatronNotes(olePatron, olePatronDocument);
262                 if (patronUpdateFlag) {
263                     OlePatronDefinition olePatronDefinition = getOlePatronService().updatePatron(OlePatronDocument.to(olePatronDocument));
264                     updatedPatrons.add(OlePatronDocument.from(olePatronDefinition));
265                 } else {
266                     failedPatronList.add(olePatron);
267                 }
268             }
269         }
270         updatePatronList.removeAll(failedPatronList);
271         return updatedPatrons;
272     }
273 
274     /**
275      * This method is for getting the object of OlePatronGroup from the ingested xml (used for testCase).
276      * @param fileContent
277      * @return OlePatronGroup object
278      * @throws java.net.URISyntaxException
279      * @throws java.io.IOException
280      */
281     public OlePatronGroup buildPatronFromFileContent(String fileContent) throws URISyntaxException, IOException {
282         return getOlePatronRecordHandler().buildPatronFromFileContent(fileContent);
283     }
284 
285     /**
286      * This method will get the resource file(xml file) and convert object from the xml file (used for testCase)
287      * @param fileName
288      * @return  OlePatronGroup object (converted from xml)
289      * @throws java.net.URISyntaxException
290      * @throws java.io.IOException
291      * @throws org.xml.sax.SAXException
292      */
293     public OlePatronGroup buildPatron(String fileName) throws URISyntaxException, IOException, SAXException {
294         URL resource = getClass().getResource(fileName);
295         File file = new File(resource.toURI());
296         String fileContent = new FileUtil().readFile(file);
297         if (validProfileXML(fileContent)) {
298             return getOlePatronRecordHandler().buildPatronFromFileContent(fileContent);
299         }
300         return null;
301     }
302 
303     /**
304      * This method will validate the ingested xml against schema.
305      * @param fileContent
306      * @return  boolean
307      * @throws java.io.IOException
308      * @throws org.xml.sax.SAXException
309      */
310     private boolean validProfileXML(String fileContent) throws IOException, SAXException {
311         return new OlePatronXMLSchemaValidator().validateContentsAgainstSchema(null);
312     }
313 
314     /**
315      * Persist phone numbers of the patron and set the values from the patron telephone numbers to entity phone bo  object
316      * @param olePatron
317      * @param olePatronDocument
318      * @return  boolean flag, to check whether the patron phone number type is valid .
319      */
320     private boolean persistPatronPhoneNumbers(OlePatron olePatron, OlePatronDocument olePatronDocument) {
321         boolean phoneFlag = false;
322         List<EntityPhoneBo> phones = new ArrayList<EntityPhoneBo>();
323         EntityPhoneBo entityPhoneBo;
324         List<OlePatronTelePhoneNumber> olePatronTelePhoneNumbers = olePatron.getTelephoneNumbers();
325         for (Iterator<OlePatronTelePhoneNumber> iterator = olePatronTelePhoneNumbers.iterator(); iterator.hasNext(); ) {
326             OlePatronTelePhoneNumber phoneNumbers = iterator.next();
327             entityPhoneBo = new EntityPhoneBo();
328             entityPhoneBo.setPhoneNumber(phoneNumbers.getTelephoneNumber());
329             Map criteria = new HashMap<String, String>();
330             Map criteriaCountry = new HashMap<String, String>();
331             if(!phoneNumbers.getTelephoneNumberType().equals("")){
332                 criteria.put(OLEConstants.CODE, phoneNumbers.getTelephoneNumberType());
333                 List<EntityPhoneTypeBo> entityType = (List<EntityPhoneTypeBo>) getBusinessObjectService().findMatching(EntityPhoneTypeBo.class, criteria);
334                 if (entityType.size()> 0) {
335                     entityPhoneBo.setPhoneType(entityType.get(0));
336                     entityPhoneBo.setPhoneTypeCode(entityType.get(0).getCode());
337                     if(phoneNumbers.getExtension() != null && !phoneNumbers.getExtension().equals("")){
338                            entityPhoneBo.setExtensionNumber(phoneNumbers.getExtension());
339                      }
340                     if(phoneNumbers.getCountry() != null && !phoneNumbers.getCountry().equals("")){
341                         criteriaCountry.put(OLEConstants.CODE, phoneNumbers.getCountry());
342                         List<CountryBo> countryList = (List<CountryBo>) getBusinessObjectService().findMatching(CountryBo.class, criteriaCountry);
343                         if (countryList.size()>0) {
344                             entityPhoneBo.setCountryCode(phoneNumbers.getCountry());
345                         } else {
346                             olePatron.setErrorMessage(OLEPatronConstant.COUNTRY_PHONE_ERROR);
347                             return false;
348                         }
349                     }
350                     entityPhoneBo.setActive(phoneNumbers.isActive());
351                     entityPhoneBo.setDefaultValue(phoneNumbers.isDefaults());
352                     phones.add(entityPhoneBo);
353                     boolean defaultValue = checkPhoneMultipleDefault(phones);
354                     if(defaultValue){
355                         olePatronDocument.setPhones(phones);
356                         phoneFlag = true;
357                     } else {
358                         olePatron.setErrorMessage(OLEPatronConstant.PHONE_DEFAULT_VALUE_ERROR);
359                         phoneFlag = false;
360                     }
361                 } else{
362                     olePatron.setErrorMessage(OLEPatronConstant.PHONETYPE_ERROR);
363                 }
364              } else{
365                 olePatron.setErrorMessage(OLEPatronConstant.PHONETYPE_BLANK_ERROR);
366             }
367         }
368         return phoneFlag;
369     }
370 
371     /**
372      * Persist email Address of the patron and set the values from the patron email address to entity email bo  object
373      * @param olePatron
374      * @param olePatronDocument
375      * @return  boolean flag ,to check whether the patron email type is valid .
376      */
377     private boolean persistPatronEmailAddress(OlePatron olePatron, OlePatronDocument olePatronDocument) {
378         boolean emailFlag = false;
379         List<EntityEmailBo> email = new ArrayList<EntityEmailBo>();
380         EntityEmailBo entityEmailBo;
381         List<OlePatronEmailAddress> olePatronEmailAddresses = olePatron.getEmailAddresses();
382         for (Iterator<OlePatronEmailAddress> iterator = olePatronEmailAddresses.iterator(); iterator.hasNext(); ) {
383             OlePatronEmailAddress emailAddresses = iterator.next();
384             entityEmailBo = new EntityEmailBo();
385             entityEmailBo.setEmailAddress(emailAddresses.getEmailAddress());
386             if(!emailAddresses.getEmailAddressType().equals("")){
387                 Map criteria = new HashMap<String, String>();
388                 criteria.put(OLEConstants.CODE, emailAddresses.getEmailAddressType());
389                 List<EntityEmailTypeBo> entityType = (List<EntityEmailTypeBo>) getBusinessObjectService().findMatching(EntityEmailTypeBo.class, criteria);
390                 if (entityType.size()>0) {
391                     entityEmailBo.setEmailType(entityType.get(0));
392                     entityEmailBo.setEmailTypeCode(entityType.get(0).getCode());
393                     entityEmailBo.setActive(emailAddresses.isActive());
394                     entityEmailBo.setDefaultValue(emailAddresses.isDefaults());
395                     email.add(entityEmailBo);
396                     boolean defaultValue = checkEmailMultipleDefault(email);
397                     if(defaultValue){
398                         olePatronDocument.setEmails(email);
399                         emailFlag = true;
400                     } else {
401                         olePatron.setErrorMessage(OLEPatronConstant.EMAIL_DEFAULT_VALUE_ERROR);
402                         emailFlag = false;
403                     }
404                 } else{
405                     olePatron.setErrorMessage(OLEPatronConstant.EMAILTYPE_ERROR);
406                 }
407             } else{
408                 olePatron.setErrorMessage(OLEPatronConstant.EMAILTYPE_BLANK_ERROR);
409             }
410         }
411         return emailFlag;
412     }
413 
414     /**
415      * Persist postal address of the patron and set the values from the patron postal address to entity address bo  object
416      * @param olePatron
417      * @param olePatronDocument
418      * @return  boolean flag , to check whether the patron address type is valid .
419      */
420     private boolean persistPatronPostalAddress(OlePatron olePatron, OlePatronDocument olePatronDocument) {
421         boolean addressFlag = false;
422         List<EntityAddressBo> address = new ArrayList<EntityAddressBo>();
423         EntityAddressBo entityAddressBo;
424         List<OlePatronPostalAddress> olePatronPostalAddresses = olePatron.getPostalAddresses();
425         for (Iterator<OlePatronPostalAddress> iterator = olePatronPostalAddresses.iterator(); iterator.hasNext(); ) {
426             OlePatronPostalAddress postalAddresses = iterator.next();
427             entityAddressBo = new EntityAddressBo();
428             List<OleAddressLine> addressLineList =  postalAddresses.getAddressLinesList();
429             if(addressLineList.size()>0){
430                 for(int i=0;i<addressLineList.size();i++){
431                     if(i==0){
432                         entityAddressBo.setLine1(addressLineList.get(i).getAddressLine());
433                     }
434                     if(i==1){
435                         entityAddressBo.setLine2(addressLineList.get(i).getAddressLine());
436                     }
437                     if(i==2){
438                         entityAddressBo.setLine3(addressLineList.get(i).getAddressLine());
439                     }
440                 }
441             }
442             Map criteria = new HashMap<String, String>();
443             Map criteriaState = new HashMap<String, String>();
444             Map criteriaCountry = new HashMap<String, String>();
445             if(postalAddresses.getPostalAddressType() != null && !postalAddresses.getPostalAddressType().equals("")){
446                 criteria.put(OLEConstants.CODE, postalAddresses.getPostalAddressType());
447                 List<EntityAddressTypeBo> entityType = (List<EntityAddressTypeBo>) getBusinessObjectService().findMatching(EntityAddressTypeBo.class, criteria);
448                 if (entityType.size()>0) {
449                     entityAddressBo.setAddressType(entityType.get(0));
450                     entityAddressBo.setAddressTypeCode(entityType.get(0).getCode());
451                 } else{
452                     olePatron.setErrorMessage(OLEPatronConstant.ADDRESSTYPE_ERROR);
453                     return false;
454                 }
455             } else{
456                 olePatron.setErrorMessage(OLEPatronConstant.ADDRESS_TYPE_BLANK_ERROR);
457                 return false;
458             }
459                 if(postalAddresses.getStateProvince() != null && !postalAddresses.getStateProvince().equals("")){
460                     criteriaState.put(OLEConstants.CODE, postalAddresses.getStateProvince());
461                     List<StateBo> stateBoList = (List<StateBo>) getBusinessObjectService().findMatching(StateBo.class, criteriaState);
462                     if (stateBoList.size()>0) {
463                         entityAddressBo.setStateProvinceCode(postalAddresses.getStateProvince());
464                     } else {
465                         olePatron.setErrorMessage(OLEPatronConstant.STATE_ERROR);
466                         return false;
467                     }
468                 }
469                 if(postalAddresses.getCountry() != null && !postalAddresses.getCountry().equals("")){
470                     criteriaCountry.put(OLEConstants.CODE, postalAddresses.getCountry());
471                     List<CountryBo> countryList = (List<CountryBo>) getBusinessObjectService().findMatching(CountryBo.class, criteriaCountry);
472                     if (countryList.size()>0) {
473                         entityAddressBo.setCountryCode(postalAddresses.getCountry());
474                     } else {
475                         olePatron.setErrorMessage(OLEPatronConstant.COUNTRY_ADDRESS_ERROR);
476                         return false;
477                     }
478                 }
479                 entityAddressBo.setCity(postalAddresses.getCity());
480                 entityAddressBo.setPostalCode(postalAddresses.getPostalCode());
481                 entityAddressBo.setActive(postalAddresses.isActive());
482                 entityAddressBo.setDefaultValue(postalAddresses.isDefaults());
483                 address.add(entityAddressBo);
484                 boolean defaultValue = checkAddressMultipleDefault(address);
485                 if(defaultValue){
486                     olePatronDocument.setAddresses(address);
487                     addressFlag = true;
488                 } else {
489                     olePatron.setErrorMessage(OLEPatronConstant.ADDRESS_DEFAULT_VALUE_ERROR);
490                     addressFlag = false;
491                 }
492         }
493         return addressFlag;
494     }
495 
496     /**
497      * Persist names of the patron and set the values from the patron names to entity name bo  object
498      * @param olePatron
499      * @param olePatronDocument
500      * @return  boolean flag , to check whether the patron name type is valid .
501      */
502     private boolean persistPatronNames(OlePatron olePatron, OlePatronDocument olePatronDocument) {
503         boolean nameFlag = false;
504         EntityNameBo names = new EntityNameBo();
505         Map criteria = new HashMap<String, String>();
506         criteria.put(OLEConstants.NAME, OLEConstants.PREFERRED);
507         List<EntityNameTypeBo> entityType = (List<EntityNameTypeBo>) getBusinessObjectService().findMatching(EntityNameTypeBo.class, criteria);
508         if (entityType.size()>0 ) {
509             names.setNameType(entityType.get(0));
510             names.setNameCode(entityType.get(0).getCode());
511             if (!olePatron.getName().getFirst().equals("") && !olePatron.getName().getSurname().equals("")) {
512                 names.setFirstName(olePatron.getName().getFirst());
513                 names.setLastName(olePatron.getName().getSurname());
514                 if(olePatron.getName().getTitle()!= null && !olePatron.getName().getTitle().equals("")){
515                     names.setNamePrefix(olePatron.getName().getTitle());
516                 }
517                 if(olePatron.getName().getSuffix()!= null && !olePatron.getName().getSuffix().equals("")){
518                     names.setNameSuffix(olePatron.getName().getSuffix());
519                 }
520                 names.setActive(true);
521                 names.setDefaultValue(true);
522                 olePatronDocument.setName(names);
523                 nameFlag = true;
524             }else{
525                 if(olePatron.getName().getFirst().equals("")){
526                     olePatron.setErrorMessage(OLEPatronConstant.FIRSTNAME_BLANK_ERROR);
527                 }
528                 if(olePatron.getName().getSurname().equals("")){
529                     olePatron.setErrorMessage(OLEPatronConstant.SURNAME_BLANK_ERROR);
530                 }
531             }
532         }
533         return nameFlag;
534     }
535 
536     /**
537      * Persist notes of the patron and set the values from the patron notes ( converted object from xml) to Patron notes bo  object
538      * @param olePatron
539      * @param olePatronDocument
540      * @return  boolean flag , to check whether the patron note type is valid .
541      */
542     private boolean persistPatronNotes(OlePatron olePatron, OlePatronDocument olePatronDocument) {
543         boolean notesFlag = false;
544         List<OlePatronNotes> olePatronNotesList = new ArrayList<OlePatronNotes>();
545         OlePatronNotes olePatronNotes;
546         List<OlePatronNote> olePatronNoteList = olePatron.getNotes();
547         for (Iterator<OlePatronNote> iterator = olePatronNoteList.iterator(); iterator.hasNext(); ) {
548             OlePatronNote olePatronNote = iterator.next();
549             olePatronNotes = new OlePatronNotes();
550             if (olePatronNote.getNoteType() != null && !"".equals(olePatronNote.getNoteType())) {
551                 Map criteria = new HashMap<String, String>();
552                 criteria.put(OLEConstants.PATRON_NOTE_TYPE_CODE, olePatronNote.getNoteType());
553                 List<OlePatronNoteType> olePatronNoteTypes = (List<OlePatronNoteType>) getBusinessObjectService().findMatching(OlePatronNoteType.class, criteria);
554                 if (olePatronNoteTypes.size()>0) {
555                     olePatronNotes.setOlePatronNoteType(olePatronNoteTypes.get(0));
556                     olePatronNotes.setPatronNoteTypeId(olePatronNoteTypes.get(0).getPatronNoteTypeId());
557                     olePatronNotes.setPatronNoteText(olePatronNote.getNote());
558                     olePatronNotes.setActive(olePatronNote.isActive());
559                     olePatronNotesList.add(olePatronNotes);
560                     olePatronDocument.setNotes(olePatronNotesList);
561                     notesFlag = true;
562                  } else {
563                     olePatron.setErrorMessage(OLEPatronConstant.NOTETYPE_ERROR);
564                 }
565 
566             } else{
567                 olePatron.setErrorMessage(OLEPatronConstant.NOTETYPE_BLANK_ERROR);
568             }
569         }
570         if (olePatronNoteList.isEmpty()) {
571             notesFlag = true;
572         }
573         return notesFlag;
574     }
575 
576     /**
577      * This method is for persisting the borrower Type of the patron
578      * @param olePatron
579      * @param olePatronDocument
580      * @return  boolean flag, to check whether the borrower Type is valid.
581      */
582     private boolean persistPatronBorrowerType(OlePatron olePatron, OlePatronDocument olePatronDocument) {
583         boolean borrowerTypeFlag = false;
584         String borroweTypeId;
585         String borrowerTypeName;
586         borrowerTypeName = olePatron.getBorrowerType();
587         if(borrowerTypeName!=null && !borrowerTypeName.equals("")){
588             HashMap<String, String> map = new HashMap<String, String>();
589             map.put(OLEConstants.BORROWER_TYPE_CODE, borrowerTypeName);
590             List<OleBorrowerType> borrowerTypes = (List<OleBorrowerType>) getBusinessObjectService().findMatching(OleBorrowerType.class, map);
591             if (borrowerTypes.size() > 0) {
592                 borroweTypeId = borrowerTypes.get(0).getBorrowerTypeId();
593                 olePatronDocument.setBorrowerType(borroweTypeId);
594                 olePatronDocument.setOleBorrowerType(borrowerTypes.get(0));
595                 borrowerTypeFlag = true;
596             }else{
597                 olePatron.setErrorMessage(OLEPatronConstant.BORROWERTYPE_ERROR);
598             }
599         }else{
600             olePatron.setErrorMessage(OLEPatronConstant.BORROWERTYPE_BLANK_ERROR);
601         }
602         return borrowerTypeFlag;
603     }
604 
605     /**
606      * This method is for saving the failed records in a separate location of home directory.
607      * @param patronXML
608      * @param patronReportId
609      */
610     private void saveFailureRecordsForAttachment(String patronXML,String patronReportId) {
611         OlePatronIngestSummaryRecord olePatronIngestSummaryRecord ;
612         try {
613             HashMap<String, String> map = new HashMap<String, String>();
614             String directory = PropertyUtil.getPropertyUtil().getProperty(OLEConstants.STAGING_DIRECTORY)+
615                     OLEConstants.PATRON_FILE_DIRECTORY;
616             String homeDirectory = System.getProperty(OLEConstants.USER_HOME_DIRECTORY);
617             int reportId = Integer.parseInt(patronReportId);
618             File file = new File(homeDirectory+directory);
619             if (file.isDirectory()) {
620                 file = new File(homeDirectory+directory+reportId+OLEConstants.FAILED_PATRON_RECORD_NAME);
621                 file.createNewFile();
622                 FileUtils.writeStringToFile(file, patronXML);
623             } else {
624                 file.mkdirs();
625                 if (file.isDirectory()) {
626                     File newFile = new File(file,reportId+OLEConstants.FAILED_PATRON_RECORD_NAME);
627                     newFile.createNewFile();
628                     FileUtils.writeStringToFile(newFile,patronXML);
629                 }
630             }
631         } catch (IOException e) {
632             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
633         }
634     }
635 
636     /**
637      * This method is for checking the entity phone has multiple defaults
638      * @param phoneBoList
639      * @return true , if the entity phone has only one default in a single patron record, else false
640      */
641     protected boolean checkPhoneMultipleDefault (List<EntityPhoneBo> phoneBoList) {
642 
643         boolean valid = true;
644         int defaultCounter = 0;
645         for(EntityPhoneBo entityPhoneBo:phoneBoList){
646             if(entityPhoneBo.isDefaultValue()){
647                 defaultCounter++;
648             } else {
649                 defaultCounter--;
650             }
651         }
652         if(defaultCounter > 1 || defaultCounter < 0){
653             valid = false;
654         }
655         return valid;
656     }
657 
658     /**
659      * This method is for checking the entity address has multiple defaults
660      * @param addrBoList
661      * @return true , if the entity address has only one default in a single patron record, else false
662      */
663     protected boolean checkAddressMultipleDefault (List<EntityAddressBo> addrBoList) {
664 
665         boolean valid = true;
666         int defaultCounter = 0;
667         for(EntityAddressBo entityAddressBo:addrBoList){
668             if(entityAddressBo.isDefaultValue()){
669                 defaultCounter++;
670             } else {
671                 defaultCounter--;
672             }
673         }
674         if(defaultCounter > 1 || defaultCounter < 0){
675             valid = false;
676         }
677         return valid;
678     }
679 
680     /**
681      * This method is for checking the entity email address has multiple defaults
682      * @param emailBoList
683      * @return true , if the entity email address has only one default in a single patron record, else false
684      */
685     protected boolean checkEmailMultipleDefault (List<EntityEmailBo> emailBoList) {
686 
687         boolean valid = true;
688         int defaultCounter = 0;
689         for(EntityEmailBo entityEmailBo:emailBoList){
690             if(entityEmailBo.isDefaultValue()){
691                 defaultCounter++;
692             }else {
693                 defaultCounter--;
694             }
695         }
696         if(defaultCounter > 1 || defaultCounter < 0){
697             valid = false;
698         }
699         return valid;
700     }
701 
702     /**
703      * Gets the instance of BusinessObjectService
704      * @return businessObjectService(BusinessObjectService)
705      */
706     private BusinessObjectService getBusinessObjectService() {
707         if (null == businessObjectService) {
708             businessObjectService = KRADServiceLocator.getBusinessObjectService();
709         }
710         return businessObjectService;
711     }
712 
713     /**
714      * Gets the instance of OlePatronRecordHandler
715      * @return olePatronRecordHandler(OlePatronRecordHandler)
716      */
717     public OlePatronRecordHandler getOlePatronRecordHandler() {
718         if (null == olePatronRecordHandler) {
719             olePatronRecordHandler = new OlePatronRecordHandler();
720         }
721         return olePatronRecordHandler;
722     }
723 
724     /**
725      * Sets the olePatronRecordHandler which is of type OlePatronRecordHandler
726      * @param olePatronRecordHandler(OlePatronRecordHandler)
727      */
728     public void setOlePatronRecordHandler(OlePatronRecordHandler olePatronRecordHandler) {
729         this.olePatronRecordHandler = olePatronRecordHandler;
730     }
731 }