View Javadoc
1   package org.kuali.ole.ingest;
2   
3   import org.kuali.ole.OLEConstants;
4   import org.kuali.ole.ingest.ProfileXMLSchemaValidator;
5   import org.kuali.ole.ingest.pojo.*;
6   import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
7   import org.kuali.rice.krad.bo.PersistableBusinessObject;
8   import org.kuali.rice.krad.service.BusinessObjectService;
9   import org.kuali.rice.krad.service.KRADServiceLocator;
10  import org.kuali.rice.krms.api.repository.term.TermSpecificationDefinition;
11  import org.kuali.rice.krms.impl.repository.*;
12  import org.xml.sax.SAXException;
13  
14  import java.io.File;
15  import java.io.IOException;
16  import java.net.MalformedURLException;
17  import java.net.URISyntaxException;
18  import java.net.URL;
19  import java.util.*;
20  
21  /**
22   *  ProfileBuilder is used to build the KRMS Agenda for the Profile xml which is used for Staff upload screen.
23   */
24  public class ProfileBuilder {
25      private TermBoService termBoService;
26      private BusinessObjectService businessObjectService;
27      private ProfileObjectGeneratorFromXML profileObjectGeneratorFromXML;
28  
29      /**
30       *   This method creates the context.
31       * @param namespace
32       * @param contextName
33       * @return  contextBo
34       */
35      public ContextBo createContext(String namespace, String contextName) {
36          ContextBo contextBo;
37          Object existing = objectExists(ContextBo.class, "nm", contextName);
38          if (null == existing) {
39              contextBo = new ContextBo();
40              contextBo.setNamespace(namespace);
41              contextBo.setName(contextName);
42              getBusinessObjectService().save(contextBo);
43          } else {
44              contextBo = (ContextBo) existing;
45          }
46          return contextBo;
47      }
48  
49      /**
50       *  This method registers the default service types in the database for the context.
51       * @param contextBo
52       * @return  contextValidActionBo
53       */
54      public ContextValidActionBo registerDefaultServiceTypes(ContextBo contextBo) {
55          KrmsTypeBo actionTypeService = createActionTypeService();
56          ContextValidActionBo contextValidActionBo;
57          Object existing = objectExists(ContextValidActionBo.class, "actn_typ_id", actionTypeService.getId());
58          if (existing == null) {
59              contextValidActionBo = new ContextValidActionBo();
60              contextValidActionBo.setActionType(actionTypeService);
61              contextValidActionBo.setActionTypeId(actionTypeService.getId());
62              contextValidActionBo.setContextId(contextBo.getId());
63              getBusinessObjectService().save(contextValidActionBo);
64          } else {
65              contextValidActionBo = (ContextValidActionBo) existing;
66          }
67          return contextValidActionBo;
68      }
69  
70      /**
71       * This method  create Bibliographic record action as type in the database for creating custom action.
72       * @return actionTypeService
73       */
74      public KrmsTypeBo createActionTypeService() {
75          KrmsTypeBo actionTypeService;
76          String typeName = "Create Bibliographic Record";
77          Object existing = objectExists(KrmsTypeBo.class, "nm", typeName);
78          if (existing == null) {
79              actionTypeService = new KrmsTypeBo();
80              actionTypeService.setActive(true);
81              actionTypeService.setName("Create Bibliographic Record");
82              actionTypeService.setNamespace(OLEConstants.OLE_NAMESPACE);
83              actionTypeService.setServiceName("createBibActionTypeService");
84              getBusinessObjectService().save(actionTypeService);
85          } else {
86              actionTypeService = (KrmsTypeBo) existing;
87          }
88          return actionTypeService;
89      }
90  
91      /**
92       *   This method creates profileTermResolverType record as type in database for creating custom action.
93       * @return profileTermResolverTypeService
94       */
95      public KrmsTypeBo createTermResolverTypeService() {
96          KrmsTypeBo profileTermResolverTypeService;
97          String serviceName = "profileTermResolverTypeService";
98          Object existing = objectExists(KrmsTypeBo.class, "srvc_nm", serviceName);
99          if (existing == null) {
100             profileTermResolverTypeService = new KrmsTypeBo();
101             profileTermResolverTypeService.setActive(true);
102             profileTermResolverTypeService.setName("ProfileTermResolver");
103             profileTermResolverTypeService.setNamespace(OLEConstants.OLE_NAMESPACE);
104             profileTermResolverTypeService.setServiceName("profileTermResolverTypeService");
105             getBusinessObjectService().save(profileTermResolverTypeService);
106         } else {
107             profileTermResolverTypeService = (KrmsTypeBo) existing;
108         }
109         return profileTermResolverTypeService;
110     }
111 
112     /**
113      *  This method creates the category.
114      *  If category name already exists it returns the category else it returns new category.
115      * @param namespace
116      * @param categoryName
117      * @return  categoryBo
118      */
119     public CategoryBo createCategory(String namespace, String categoryName) {
120         CategoryBo categoryBo;
121         Object existing = objectExists(CategoryBo.class, "nm", categoryName);
122         if (existing == null) {
123             categoryBo = new CategoryBo();
124             categoryBo.setName(categoryName);
125             categoryBo.setNamespace(namespace);
126             getBusinessObjectService().save(categoryBo);
127         } else {
128             categoryBo = (CategoryBo) existing;
129         }
130         return categoryBo;
131     }
132 
133     /**
134      *  This method creates the term specifications .
135      *  If the term already exists in termSpecificationBo then it will return that object else it will create  new termSpecificationBo.
136      * @param namespace
137      * @param termSpecificationName
138      * @param type
139      * @param categoryBoList
140      * @param contextBoList
141      * @return  termSpecificationBo
142      */
143     //TODO: Wasn't able to use business object service to save the term spec as the pk generated was empty string.
144     //TOOD: When using the termboservice (which in turn uses the bo service) its generating the pk. Bug need to be
145     //TODO: fixed with Rice Team.
146     public TermSpecificationBo createTermSpecification(String namespace, String termSpecificationName, String type, List<CategoryBo> categoryBoList, List<ContextBo> contextBoList) {
147         TermSpecificationBo termSpecificationBo;
148         Object existing = objectExists(TermSpecificationBo.class, "nm", termSpecificationName);
149         if (existing == null) {
150             termSpecificationBo = new TermSpecificationBo();
151             termSpecificationBo.setActive(true);
152             termSpecificationBo.setName(termSpecificationName);
153             termSpecificationBo.setNamespace(namespace);
154             termSpecificationBo.setCategories(categoryBoList);
155             termSpecificationBo.setDescription(termSpecificationName);
156             termSpecificationBo.setContexts(contextBoList);
157             termSpecificationBo.setType(type);
158             TermSpecificationDefinition termSpecification = getTermBoService().createTermSpecification(TermSpecificationDefinition.Builder.create(termSpecificationBo).build());
159             termSpecificationBo = TermSpecificationBo.from(termSpecification);
160         } else {
161             termSpecificationBo = (TermSpecificationBo) existing;
162         }
163         return termSpecificationBo;
164     }
165 
166     /**
167      *  This method creates the term for each termSpecification.
168      * @param name
169      * @param termSpecificationBo
170      * @return  termBo
171      */
172     public TermBo createTerm(String name, TermSpecificationBo termSpecificationBo) {
173         TermBo termBo;
174         Object existing = objectExists(TermBo.class, "term_spec_id", termSpecificationBo.getId());
175         if (existing == null) {
176             termBo = new TermBo();
177             termBo.setSpecification(termSpecificationBo);
178             termBo.setSpecificationId(termSpecificationBo.getId());
179             termBo.setDescription(name);
180             getBusinessObjectService().save(termBo);
181         } else {
182             termBo = (TermBo) existing;
183         }
184         return termBo;
185     }
186 
187     /**
188      *  This method creates the custom function by using functionLoader.
189      * @param namespace
190      * @param termName
191      * @param returnType
192      * @param categories
193      * @return  functionBo
194      */
195     public FunctionBo createFunction(String namespace, String termName, String returnType, List categories) {
196         Object existing = objectExists(FunctionBo.class, "nm", termName + "Function");
197         FunctionBo functionBo;
198         if (existing == null) {
199             HashMap<String, String> map = new HashMap<String, String>();
200             map.put("nm", "FunctionLoader");
201             List<KrmsTypeBo> matching =
202                     (List<KrmsTypeBo>) getBusinessObjectService().findMatching(KrmsTypeBo.class, map);
203             KrmsTypeBo krmsTypeBo = matching.get(0);
204             functionBo = new FunctionBo();
205             functionBo.setActive(true);
206             functionBo.setName(termName + "Function");
207             functionBo.setNamespace(namespace);
208             functionBo.setReturnType(returnType);
209             functionBo.setCategories(categories);
210             functionBo.setTypeId(krmsTypeBo.getId());
211             getBusinessObjectService().save(functionBo);
212 
213             FunctionParameterBo functionParameterBo = new FunctionParameterBo();
214             functionParameterBo.setFunctionId(functionBo.getId());
215             functionParameterBo.setParameterType("org.kuali.ole.Ingest.ProfileTerm");
216             functionParameterBo.setName(termName);
217             functionParameterBo.setSequenceNumber(0);
218 
219             getBusinessObjectService().save(functionParameterBo);
220 
221             List<FunctionParameterBo> parameters = functionBo.getParameters();
222             if (null == parameters) {
223                 parameters = new ArrayList<FunctionParameterBo>();
224             }
225             parameters.add(functionParameterBo);
226             functionBo.setParameters(parameters);
227 
228             getBusinessObjectService().save(functionBo);
229         } else {
230             functionBo = (FunctionBo) existing;
231         }
232 
233         return functionBo;
234     }
235 
236     /**
237      *  This method creates the simple or compound proposition.
238      * @param categoryId
239      * @param propositionDescription
240      * @param propositionType
241      * @param rule
242      * @return  propositionBo
243      */
244     public PropositionBo createProposition(String categoryId, String propositionDescription, String propositionType, RuleBo rule) {
245         PropositionBo propositionBo = new PropositionBo();
246         propositionBo.setCategoryId(categoryId);
247         propositionBo.setDescription(propositionDescription);
248         propositionBo.setRuleId(rule.getId());
249         propositionBo.setPropositionTypeCode(propositionType);
250         getBusinessObjectService().save(propositionBo);
251         rule.setProposition(propositionBo);
252         getBusinessObjectService().save(rule);
253         return propositionBo;
254     }
255 
256     /**
257      * This method creates the rule for the ruleName.
258      * if the rule already exists then it will return that object else it return new rule.
259      * @param namespace
260      * @param ruleName
261      * @return  ruleBo
262      */
263     public RuleBo createRule(String namespace, String ruleName) {
264         RuleBo ruleBo = new RuleBo();
265         Object existing = objectExists(RuleBo.class, "nm", ruleName);
266         if (existing == null) {
267             ruleBo.setName(ruleName);
268             ruleBo.setNamespace(namespace);
269             getBusinessObjectService().save(ruleBo);
270         } else {
271             ruleBo = (RuleBo) existing;
272         }
273         return ruleBo;
274     }
275 
276     /**
277      *  This method adds the action into rule to create the agenda.
278      * @param namespace
279      * @param actionName
280      * @param description
281      * @param actionTypeId
282      * @param ruleBo
283      * @param sequenceNumber
284      * @return  actionBo
285      */
286     public ActionBo addActionToRule(String namespace, String actionName, String description, String actionTypeId, RuleBo ruleBo, Integer sequenceNumber) {
287         ActionBo actionBo = new ActionBo();
288         Object existing = objectExists(ActionBo.class, "nm", actionName);
289         if (existing == null) {
290             actionBo.setName(actionName + "Action");
291             actionBo.setRuleId(ruleBo.getId());
292             actionBo.setNamespace(namespace);
293             actionBo.setSequenceNumber(sequenceNumber);
294             actionBo.setDescription(description);
295             actionBo.setTypeId(actionTypeId);
296             getBusinessObjectService().save(actionBo);
297             List<ActionBo> actionBos = ruleBo.getActions();
298             if (null == actionBos) {
299                 actionBos = new ArrayList<ActionBo>();
300             }
301             actionBos.add(actionBo);
302             ruleBo.setActions(actionBos);
303             getBusinessObjectService().save(ruleBo);
304         } else {
305             actionBo = (ActionBo) existing;
306         }
307         return actionBo;
308     }
309 
310     /**
311      *   This method adds the customFunction into propositionParameter to create the rule and agenda.
312      * @param functionId
313      * @param proposition
314      * @return  proposition
315      */
316     public PropositionBo addCustomFunctionToPropositionParameter(String functionId, PropositionBo proposition) {
317         PropositionParameterBo propositionParameterBo = new PropositionParameterBo();
318         propositionParameterBo.setPropId(proposition.getId());
319         propositionParameterBo.setValue(functionId);
320         propositionParameterBo.setSequenceNumber(1);
321         propositionParameterBo.setParameterType("F");
322         getBusinessObjectService().save(propositionParameterBo);
323         List<PropositionParameterBo> parameters = proposition.getParameters();
324         if (null == parameters) {
325             parameters = new ArrayList<PropositionParameterBo>();
326         }
327         parameters.add(propositionParameterBo);
328         proposition.setParameters(parameters);
329         getBusinessObjectService().save(proposition);
330         return proposition;
331     }
332 
333     /**
334      *  This method adds the term to propositionParameter to create the rule and agenda.
335      * @param termId
336      * @param proposition
337      * @return proposition
338      */
339     public PropositionBo addTermToPropositionParameter(String termId, PropositionBo proposition) {
340         PropositionParameterBo propositionParameterBo = new PropositionParameterBo();
341         propositionParameterBo.setPropId(proposition.getId());
342         propositionParameterBo.setValue(termId);
343         propositionParameterBo.setSequenceNumber(0);
344         propositionParameterBo.setParameterType("T");
345         getBusinessObjectService().save(propositionParameterBo);
346         List<PropositionParameterBo> parameters = proposition.getParameters();
347         if (null == parameters) {
348             parameters = new ArrayList<PropositionParameterBo>();
349         }
350         parameters.add(propositionParameterBo);
351         proposition.setParameters(parameters);
352         getBusinessObjectService().save(proposition);
353         return proposition;
354     }
355 
356     /**
357      *  This method creates the agenda and persist in the database for the context.
358      * @param agendaName
359      * @param contextBo
360      * @return  agendaBo
361      */
362     public AgendaBo createAgenda(String agendaName, ContextBo contextBo) {
363         AgendaBo agendaBo;
364         Object existing = objectExists(AgendaBo.class, "nm", agendaName);
365         if (existing == null) {
366             agendaBo = new AgendaBo();
367             agendaBo.setActive(true);
368             agendaBo.setName(agendaName);
369             agendaBo.setContext(contextBo);
370             agendaBo.setContextId(contextBo.getId());
371             getBusinessObjectService().save(agendaBo);
372             List<AgendaBo> agendas = contextBo.getAgendas();
373             if (null == agendas) {
374                 agendas = new ArrayList<AgendaBo>();
375             }
376             agendas.add(agendaBo);
377             contextBo.setAgendas(agendas);
378             getBusinessObjectService().save(contextBo);
379         } else {
380             agendaBo = (AgendaBo) existing;
381         }
382         return agendaBo;
383     }
384 
385     /**
386      *  This method adds the rule to agenda.
387      * @param agendaBo
388      * @param ruleBo
389      * @return agendaBo
390      */
391     public AgendaBo addRuleToAgenda(AgendaBo agendaBo, RuleBo ruleBo) {
392         AgendaItemBo agendaItemBo = new AgendaItemBo();
393         agendaItemBo.setAgendaId(agendaBo.getId());
394         agendaItemBo.setRule(ruleBo);
395         getBusinessObjectService().save(agendaItemBo);
396         List<AgendaItemBo> agendaBoItems = agendaBo.getItems();
397         if (null == agendaBoItems) {
398             agendaBoItems = new ArrayList<AgendaItemBo>();
399         }
400         agendaBoItems.add(agendaItemBo);
401         agendaBo.setItems(agendaBoItems);
402         agendaBo.setFirstItemId(agendaBoItems.get(0).getId());
403         getBusinessObjectService().save(agendaBo);
404         return agendaBo;
405     }
406 
407     /**
408      *  This method adds the dummy rule into database for falseAction.
409      * @param ruleBo
410      * @param falseActionRuleBo
411      * @return existingAgendaItemBo
412      */
413     public AgendaItemBo addDummyRuleForFalseAction(RuleBo ruleBo, RuleBo falseActionRuleBo) {
414         HashMap<String, String> map = new HashMap<String, String>();
415         map.put("rule_id", ruleBo.getId());
416         List<AgendaItemBo> matching =
417                 (List<AgendaItemBo>) getBusinessObjectService().findMatching(AgendaItemBo.class, map);
418         AgendaItemBo existingAgendaItemBo = matching.get(0);
419 
420         AgendaItemBo falseActionAgendaItemBo = new AgendaItemBo();
421         falseActionAgendaItemBo.setAgendaId(existingAgendaItemBo.getAgendaId());
422         falseActionAgendaItemBo.setRule(falseActionRuleBo);
423         falseActionAgendaItemBo.setRuleId(falseActionRuleBo.getId());
424         getBusinessObjectService().save(falseActionAgendaItemBo);
425         existingAgendaItemBo.setWhenFalse(falseActionAgendaItemBo);
426         getBusinessObjectService().save(existingAgendaItemBo);
427         return existingAgendaItemBo;
428 
429     }
430 
431     /**
432      *  This method adds the agendaName,docType,incomingField,existingField into MatchBo.
433      * @param agendaName
434      * @param termName
435      * @param docType
436      * @param incomingField
437      * @param existingField
438      * @return  matchBo
439      */
440     public MatchBo addMatchBo(String agendaName, String termName, String docType, String incomingField, String existingField) {
441         MatchBo matchBo = new MatchBo();
442         matchBo.setAgendaName(agendaName);
443         matchBo.setDocType(docType);
444         matchBo.setTermName(termName);
445         matchBo.setIncomingField(incomingField);
446         matchBo.setExistingField(existingField);
447         getBusinessObjectService().save(matchBo);
448         return matchBo;
449 
450     }
451 
452     /**
453      *  This method returns Profile build from fileContent.
454      * @param fileContent
455      * @return  Profile
456      * @throws java.net.URISyntaxException
457      * @throws java.io.IOException
458      */
459     public Profile buildProfileFromFileContent(String fileContent) throws URISyntaxException, IOException {
460         return getProfileObjectGeneratorFromXML().buildProfileFromFileContent(fileContent);
461     }
462 
463     /**
464      *  This method builds the profile based on fileContent.
465      * @param fileName
466      * @return  Profile
467      * @throws java.net.URISyntaxException
468      * @throws java.io.IOException
469      * @throws org.xml.sax.SAXException
470      */
471     public Profile buildProfile(String fileName) throws URISyntaxException, IOException, SAXException {
472         URL resource = getClass().getResource(fileName);
473         File file = new File(resource.toURI());
474         String fileContent = new FileUtil().readFile(file);
475         if (validProfileXML(fileContent)) {
476             return getProfileObjectGeneratorFromXML().buildProfileFromFileContent(fileContent);
477         }
478         return null;
479     }
480 
481     /**
482      *  This method validates the XmlSchema.
483      * @param fileContent
484      * @return  boolean
485      * @throws java.io.IOException
486      * @throws org.xml.sax.SAXException
487      */
488     private boolean validProfileXML(String fileContent) throws IOException, SAXException {
489         return new ProfileXMLSchemaValidator().validateContentsAgainstSchema(null);
490     }
491 
492     /**
493      * This method persists the KRMSProfile got from fileContent into the database.
494      * @param fileContent
495      * @return  name
496      * @throws java.io.IOException
497      * @throws java.net.URISyntaxException
498      */
499     public String persistKRMSProfileFromFileContent(String fileContent) throws IOException, URISyntaxException {
500         Profile profile = getProfileObjectGeneratorFromXML().buildProfileFromFileContent(fileContent);
501         return persist(profile);
502 
503     }
504 
505     /**
506      * This method persists the KRMSProfile into database.
507      * @param profileFileName
508      * @return  name
509      * @throws java.io.IOException
510      * @throws java.net.URISyntaxException
511      * @throws org.xml.sax.SAXException
512      */
513     public String persistKRMSProfile(String profileFileName) throws IOException, URISyntaxException, SAXException {
514         Profile profile = buildProfile(profileFileName);
515         return persist(profile);
516     }
517 
518     /**
519      *  This method  creates context,category,rules,preposition,term and action for creating agenda and finally persisted into database.
520      * @param profile
521      * @return name
522      */
523     public String persist(Profile profile) {
524         Boolean profileExists = doesProfileExist(profile.getName());
525         if (profileExists) {
526             deleteAgenda(profile);
527         }
528         ContextBo context = createContext(OLEConstants.OLE_NAMESPACE, profile.getContextName());
529         CategoryBo category = createCategory(OLEConstants.OLE_NAMESPACE, profile.getCategoryName());
530 
531         registerDefaultTermResolvers(Arrays.asList(context), Arrays.asList(category));
532         registerDefaultFunctionLoader();
533 
534         ContextValidActionBo contextValidActionBo = registerDefaultServiceTypes(context);
535 
536 
537         AgendaBo agendaBo = createAgenda(profile.getName(), context);
538 
539         List<OleRule> rules = profile.getRules();
540         for (Iterator<OleRule> iterator = rules.iterator(); iterator.hasNext(); ) {
541             OleRule rule = iterator.next();
542 
543             TermSpecificationBo termSpecification =
544                     createTermSpecification(OLEConstants.OLE_NAMESPACE, rule.getTerm(), "org.kuali.ole.ProfileTerm", Arrays.asList(category), Arrays.asList(context));
545 
546             TermBo termBo = createTerm(rule.getTerm(), termSpecification);
547 
548             RuleBo ruleBo = createRule(OLEConstants.OLE_NAMESPACE, rule.getName());
549 
550             addRuleToAgenda(agendaBo, ruleBo);
551 
552             PropositionBo propositionBo = createProposition(category.getId(), rule.getTerm() + " check", "S", ruleBo);
553 
554             FunctionBo function = createFunction(OLEConstants.OLE_NAMESPACE, rule.getTerm(), "java.lang.Boolean", Arrays.asList(category));
555 
556             addTermToPropositionParameter(termBo.getId(), propositionBo);
557 
558             addCustomFunctionToPropositionParameter(function.getId(), propositionBo);
559 
560             List<OleAction> trueActions = rule.getTrueActions();
561             for (Iterator<OleAction> oleActionIterator = trueActions.iterator(); oleActionIterator.hasNext(); ) {
562                 OleAction trueAction = oleActionIterator.next();
563                 addActionToRule(OLEConstants.OLE_NAMESPACE, trueAction.getName(), trueAction.getDescription(), contextValidActionBo.getActionTypeId(), ruleBo, trueAction.getSequenceNumber());
564             }
565 
566             List<OleAction> falseActions = rule.getFalseActions();
567             for (Iterator<OleAction> oleActionIterator = falseActions.iterator(); oleActionIterator.hasNext(); ) {
568                 OleAction falseAction = oleActionIterator.next();
569                 RuleBo falseActionRuleBo = createRule(OLEConstants.OLE_NAMESPACE, rule.getName() + "_falseActionRule");
570                 addActionToRule(OLEConstants.OLE_NAMESPACE, falseAction.getName(), falseAction.getDescription(), contextValidActionBo.getActionTypeId(), falseActionRuleBo, falseAction.getSequenceNumber());
571                 addDummyRuleForFalseAction(ruleBo, falseActionRuleBo);
572             }
573             persistMatchBo(agendaBo, rule);
574         }
575         persistProfileAttributes(profile);
576         return agendaBo.getName();
577     }
578 
579     /**
580      *   This method creates function loader type in the database for creating custom function.
581      */
582     public void registerDefaultFunctionLoader() {
583         if (null == objectExists(KrmsTypeBo.class, "nm", "FunctionLoader")) {
584             KrmsTypeBo krmsTypeBo = new KrmsTypeBo();
585             krmsTypeBo.setNamespace(OLEConstants.OLE_NAMESPACE);
586             krmsTypeBo.setName("FunctionLoader");
587             krmsTypeBo.setServiceName("functionLoader");
588             getBusinessObjectService().save(krmsTypeBo);
589         }
590     }
591 
592     /**
593      *   This method creates the termResolver for ExistingField and IncomingField based on category and context.
594      * @param contextBos
595      * @param categoryBos
596      */
597     public void registerDefaultTermResolvers(List<ContextBo> contextBos, List<CategoryBo> categoryBos) {
598         List list = new ArrayList();
599         KrmsTypeBo termResolverTypeService = createTermResolverTypeService();
600 
601         TermSpecificationBo termSpecificationBo = createTermSpecification(OLEConstants.OLE_NAMESPACE, OLEConstants.EXISTING_FIELD, "java.lang.String", categoryBos, contextBos);
602         createTerm(OLEConstants.EXISTING_FIELD, termSpecificationBo);
603 
604         TermResolverBo termResolverBoForExistinField = null;
605         if (null == objectExists(TermResolverBo.class, "nm", OLEConstants.EXISTING_FIELD)) {
606             termResolverBoForExistinField = new TermResolverBo();
607             termResolverBoForExistinField.setNamespace(OLEConstants.OLE_NAMESPACE);
608             termResolverBoForExistinField.setName(OLEConstants.EXISTING_FIELD);
609             termResolverBoForExistinField.setOutputId(termSpecificationBo.getId());
610             termResolverBoForExistinField.setTypeId(termResolverTypeService.getId());
611             list.add(termResolverBoForExistinField);
612         }
613 
614         TermSpecificationBo termSpecificationBo1 = createTermSpecification(OLEConstants.OLE_NAMESPACE, OLEConstants.INCOMING_FIELD, "java.lang.String", categoryBos, contextBos);
615         createTerm(OLEConstants.INCOMING_FIELD, termSpecificationBo1);
616 
617         TermResolverBo termResolverBoForIncomingField = null;
618         if (null == objectExists(TermResolverBo.class, "nm", OLEConstants.INCOMING_FIELD)) {
619             termResolverBoForIncomingField = new TermResolverBo();
620             termResolverBoForIncomingField.setNamespace(OLEConstants.OLE_NAMESPACE);
621             termResolverBoForIncomingField.setName(OLEConstants.INCOMING_FIELD);
622             termResolverBoForIncomingField.setTypeId(termResolverTypeService.getId());
623             termResolverBoForIncomingField.setOutputId(termSpecificationBo1.getId());
624             getBusinessObjectService().save(termResolverBoForIncomingField);
625             list.add(termResolverBoForIncomingField);
626         }
627 
628         if (!list.isEmpty()) {
629             getBusinessObjectService().save(list);
630         }
631     }
632 
633     /**
634      *  This method persists the profile attributes in to database.
635      * @param profile
636      */
637     private void persistProfileAttributes(Profile profile) {
638         List<ProfileAttributeBo> profileAttributes = profile.getProfileAttributes();
639         for (Iterator<ProfileAttributeBo> iterator = profileAttributes.iterator(); iterator.hasNext(); ) {
640             ProfileAttributeBo profileAttributeBo = iterator.next();
641             profileAttributeBo.setAgendaName(profile.getName());
642         }
643         getBusinessObjectService().save(profileAttributes);
644     }
645 
646     /**
647      * This method persists the agenda and rule into database.
648      * @param agendaBo
649      * @param rule
650      */
651     private void persistMatchBo(AgendaBo agendaBo, OleRule rule) {
652         MatchBo matchBo = new MatchBo();
653         matchBo.setAgendaName(agendaBo.getName());
654         matchBo.setDocType(rule.getDocType());
655         String incomingField = rule.getIncomingField().getField() + rule.getIncomingField().getSubfield();
656         String existingField = rule.getExistingField().getField() + rule.getExistingField().getSubfield();
657         matchBo.setIncomingField(incomingField);
658         matchBo.setExistingField(existingField);
659         matchBo.setTermName(rule.getTerm());
660         getBusinessObjectService().save(matchBo);
661     }
662 
663     /**
664      *  This method returns the  object
665      * @param objectClass
666      * @param key
667      * @param value
668      * @return  This method returns object if exists in db, if not returns null.
669      */
670     public Object objectExists(Class objectClass, String key, String value) {
671         HashMap<String, String> map = new HashMap<String, String>();
672         map.put(key, value);
673         List<Object> matching = (List<Object>) getBusinessObjectService().findMatching(objectClass, map);
674         return matching.isEmpty() ? null : matching.get(0);
675     }
676 
677     /**
678      * To clear Profile Data if Profile already Exists
679      *
680      * @param profile
681      */
682     public void deleteAgenda(Profile profile) {
683 
684         Map<String, String> contextPks = new HashMap<String, String>();
685         contextPks.put("nm", profile.getContextName());
686         contextPks.put("nmspc_cd", OLEConstants.OLE_NAMESPACE);
687         ContextBo context = getBusinessObjectService().findByPrimaryKey(ContextBo.class, contextPks);
688         String contextId = context.getId();
689 
690         Map<String, String> agendaPks = new HashMap<String, String>();
691         agendaPks.put("nm", profile.getName());
692         agendaPks.put("cntxt_id", contextId);
693         AgendaBo oldAgenda = getBusinessObjectService().findByPrimaryKey(AgendaBo.class, agendaPks);
694 
695         Map<String, String> itemPks = new HashMap<String, String>();
696         itemPks.put("agenda_id", oldAgenda.getId());
697         List<AgendaItemBo> items = (List<AgendaItemBo>) getBusinessObjectService().findMatching(AgendaItemBo.class, itemPks);
698 
699         getBusinessObjectService().delete(items);
700 
701         getBusinessObjectService().delete(oldAgenda);
702 
703         List<AgendaBo> agendas = context.getAgendas();
704         AgendaBo removeAgenda = null;
705         for (AgendaBo agenda : agendas) {
706             if (agenda.getName().equalsIgnoreCase(oldAgenda.getName())) {
707                 removeAgenda = agenda;
708             }
709         }
710         agendas.remove(removeAgenda);
711         context.setAgendas(agendas);
712         getBusinessObjectService().save(context);
713 
714         deleteRegisteredRules(profile);
715         unregisterDefaultTermResolvers();
716         unregisterFunctionLoader();
717 
718         HashMap matchingProfileAttr = new HashMap();
719         matchingProfileAttr.put("agenda_name", oldAgenda.getName());
720         List<ProfileAttributeBo> profileAttributeBos =
721                 (List<ProfileAttributeBo>) getBusinessObjectService().findMatching(ProfileAttributeBo.class, matchingProfileAttr);
722         getBusinessObjectService().delete(profileAttributeBos);
723 
724         HashMap matchingProfileFacts = new HashMap();
725         matchingProfileFacts.put("agenda_name", oldAgenda.getName());
726         List<MatchBo> matchBos =
727                 (List<MatchBo>) getBusinessObjectService().findMatching(MatchBo.class, matchingProfileFacts);
728         getBusinessObjectService().delete(matchBos);
729     }
730 
731     /**
732      * This method deletes the term related rules from database.
733      * @param profile
734      */
735     private void deleteRegisteredRules(Profile profile) {
736         Map map = new HashMap();
737         List<OleRule> rules = profile.getRules();
738         for (Iterator<OleRule> iterator = rules.iterator(); iterator.hasNext(); ) {
739             OleRule oleRule = iterator.next();
740             String term = oleRule.getTerm();
741             deleteTerm(term);
742 
743             map.put("nm", oleRule.getName());
744             List<RuleBo> matching = (List<RuleBo>) getBusinessObjectService().findMatching(RuleBo.class, map);
745             getBusinessObjectService().delete(matching);
746         }
747     }
748 
749     /**
750      *  This method deletes the term record from database.
751      * @param term
752      */
753     private void deleteTerm(String term) {
754         Map map = new HashMap();
755         map.put("desc_txt", term);
756         List<TermBo> termsToBeDeleted = (List<TermBo>) getBusinessObjectService().findMatching(TermBo.class, map);
757         if (!termsToBeDeleted.isEmpty()) {
758             getBusinessObjectService().delete(termsToBeDeleted);
759         }
760 //        List<TermSpecificationBo> termSpecificationBosToBeDeleted =
761 //                (List<TermSpecificationBo>) getBusinessObjectService().findMatching(TermSpecificationBo.class, map);
762 //        for (Iterator<TermSpecificationBo> iterator = termSpecificationBosToBeDeleted.iterator(); iterator.hasNext(); ) {
763 //            TermSpecificationBo termSpecificationBo = iterator.next();
764 //            Map categoryBoMap = new HashMap();
765 //            categoryBoMap.put("term_spec_id", termSpecificationBo.getId());
766 //            List<CategoryBo> categoryBosToBeDeleted =
767 //                    (List<CategoryBo>) getBusinessObjectService().findMatching(CategoryBo.class, categoryBoMap);
768 //            getBusinessObjectService().delete(categoryBosToBeDeleted);
769 //        }
770 //        getBusinessObjectService().delete(termSpecificationBosToBeDeleted);
771     }
772 
773     /**
774      *   This method deletes the functionLoader record from database.
775      */
776     private void unregisterFunctionLoader() {
777         HashMap map = new HashMap();
778         map.put("nm", "functionLoader");
779         List<KrmsTypeBo> matching = (List<KrmsTypeBo>) getBusinessObjectService().findMatching(KrmsTypeBo.class, map);
780         if (!matching.isEmpty()) {
781             getBusinessObjectService().delete(matching);
782         }
783     }
784 
785     /**
786      *   This method deletes the incomingField and existingField record from database .
787      */
788     private void unregisterDefaultTermResolvers() {
789         Map incomingTermMap = new HashMap();
790         incomingTermMap.put("desc_txt", OLEConstants.INCOMING_FIELD);
791         getBusinessObjectService().
792                 delete((List<? extends PersistableBusinessObject>) getBusinessObjectService().
793                         findMatching(TermBo.class, incomingTermMap));
794 
795         Map existingTermMap = new HashMap();
796         existingTermMap.put("desc_txt", OLEConstants.EXISTING_FIELD);
797         getBusinessObjectService().
798                 delete((List<? extends PersistableBusinessObject>) getBusinessObjectService().
799                         findMatching(TermBo.class, existingTermMap));
800 
801 
802         HashMap map = new HashMap();
803         map.put("nm", "Create Bibliographic Record");
804         List<KrmsTypeBo> matching = (List<KrmsTypeBo>) getBusinessObjectService().findMatching(KrmsTypeBo.class, map);
805         if (!matching.isEmpty()) {
806             getBusinessObjectService().delete(matching);
807         }
808 //
809 //        HashMap map1 = new HashMap();
810 //        map1.put("nm", "ProfileTermResolver");
811 //        List<KrmsTypeBo> matching1 = (List<KrmsTypeBo>) getBusinessObjectService().findMatching(KrmsTypeBo.class, map1);
812 //        if (!matching1.isEmpty()) {
813 //            getBusinessObjectService().delete(matching1);
814 //        }
815     }
816 
817     /**
818      *  This method returns True/False.
819      *  This method checks the existence of profileName with the help of BusinessObjectService.
820      * @param profileName
821      * @return  Boolean
822      */
823     public Boolean doesProfileExist(String profileName) {
824         HashMap<String, String> map = new HashMap<String, String>();
825         map.put("nm", profileName);
826         List<AgendaBo> matching = (List<AgendaBo>) getBusinessObjectService().findMatching(AgendaBo.class, map);
827         return !matching.isEmpty();
828     }
829 
830     /**
831      * Get the businessObjectService attribute.
832      *  if businessObjectService is null it will create a new instance else it will return existing instance.
833      * @return businessObjectService
834      */
835     private BusinessObjectService getBusinessObjectService() {
836         if (null == businessObjectService) {
837             businessObjectService = KRADServiceLocator.getBusinessObjectService();
838         }
839         return businessObjectService;
840     }
841 
842     /**
843      *   Gets the termBoService attribute.
844      *   if termBoService is null it will create a new instance else it will return existing instance.
845      * @return termBoService
846      */
847     private TermBoService getTermBoService() {
848         if (null == termBoService) {
849             termBoService = GlobalResourceLoader.getService("termBoService");
850         }
851         return termBoService;
852     }
853 
854     /**
855      *  Gets the profileObjectGeneratorFromXML attribute.
856      *  if profileObjectGeneratorFromXML is null it will create a new instance else it will return existing instance.
857      * @return  profileObjectGeneratorFromXML
858      */
859     public ProfileObjectGeneratorFromXML getProfileObjectGeneratorFromXML() {
860         if (null == profileObjectGeneratorFromXML) {
861             profileObjectGeneratorFromXML = new ProfileObjectGeneratorFromXML();
862         }
863         return profileObjectGeneratorFromXML;
864     }
865 
866     /**
867      * Sets the profileObjectGeneratorFromXML attribute value.
868      * @param profileObjectGeneratorFromXML
869      */
870     public void setProfileObjectGeneratorFromXML(ProfileObjectGeneratorFromXML profileObjectGeneratorFromXML) {
871         this.profileObjectGeneratorFromXML = profileObjectGeneratorFromXML;
872     }
873 }