View Javadoc
1   /*
2    * Copyright 2007-2008 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.ole.module.purap.batch;
17  
18  import org.apache.commons.lang.StringUtils;
19  import org.kuali.ole.integration.purap.CapitalAssetLocation;
20  import org.kuali.ole.module.purap.PurapConstants;
21  import org.kuali.ole.module.purap.PurapConstants.POCostSources;
22  import org.kuali.ole.module.purap.PurapConstants.POTransmissionMethods;
23  import org.kuali.ole.module.purap.PurapConstants.RequisitionSources;
24  import org.kuali.ole.module.purap.PurapConstants.RequisitionStatuses;
25  import org.kuali.ole.module.purap.businessobject.*;
26  import org.kuali.ole.module.purap.document.ContractManagerAssignmentDocument;
27  import org.kuali.ole.module.purap.document.PurchaseOrderDocument;
28  import org.kuali.ole.module.purap.document.RequisitionDocument;
29  import org.kuali.ole.module.purap.document.service.PurapService;
30  import org.kuali.ole.module.purap.document.service.RequisitionService;
31  import org.kuali.ole.sys.OLEConstants;
32  import org.kuali.ole.sys.batch.AbstractStep;
33  import org.kuali.ole.sys.batch.Job;
34  import org.kuali.ole.sys.batch.TestingStep;
35  import org.kuali.ole.sys.context.SpringContext;
36  import org.kuali.rice.core.api.util.type.KualiDecimal;
37  import org.kuali.rice.coreservice.api.parameter.EvaluationOperator;
38  import org.kuali.rice.coreservice.api.parameter.Parameter;
39  import org.kuali.rice.coreservice.api.parameter.Parameter.Builder;
40  import org.kuali.rice.coreservice.api.parameter.ParameterType;
41  import org.kuali.rice.coreservice.framework.parameter.ParameterService;
42  import org.kuali.rice.kew.api.exception.WorkflowException;
43  import org.kuali.rice.krad.UserSession;
44  import org.kuali.rice.krad.bo.DocumentHeader;
45  import org.kuali.rice.krad.document.Document;
46  import org.kuali.rice.krad.exception.ValidationException;
47  import org.kuali.rice.krad.service.BusinessObjectService;
48  import org.kuali.rice.krad.service.DocumentService;
49  import org.kuali.rice.krad.service.PersistenceStructureService;
50  import org.kuali.rice.krad.util.GlobalVariables;
51  
52  import java.math.BigDecimal;
53  import java.util.*;
54  
55  public class PurapMassRequisitionStep extends AbstractStep implements TestingStep {
56      private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PurapMassRequisitionStep.class);
57  
58      private DocumentService documentService;
59      private RequisitionService requisitionService;
60      private PurapService purapService;
61      private BusinessObjectService boService;
62      private PersistenceStructureService psService;
63  
64      private final int NUM_DOCS_TO_CREATE = 25; // number of each document type to create
65      private final int ROUTE_TO_FINAL_SECONDS_LIMIT = 240; // number of seconds to wait for routing of documents to Final.
66      private final String RUN_INDICATOR_PARAMETER_NAMESPACE_STEP = "PurapMassRequisitionStep";
67      private final String RUN_INDICATOR_PARAMETER_VALUE = "N";
68      private final String RUN_INDICATOR_PARAMETER_ALLOWED = "A";
69      private final String RUN_INDICATOR_PARAMETER_DESCRIPTION = "Tells the job framework whether to run this job or not; because the PurapMassRequisitionJob needs to only be run once after database initialization.";
70      private final String RUN_INDICATOR_PARAMETER_TYPE = "CONFG";
71  
72      @Override
73      public boolean execute(String jobName, Date jobRunDate) throws InterruptedException {
74          LOG.debug("Starting execution of PurapMassRequisitionStep");
75  
76          Parameter runIndicatorParameter = SpringContext.getBean(ParameterService.class).getParameter(PurapMassRequisitionStep.class, Job.STEP_RUN_PARM_NM);
77  
78          if (runIndicatorParameter == null || "Y".equals(runIndicatorParameter.getValue())) {
79              // save runParameter as "N" so that the job won't run until DB has been cleared
80              setInitiatedRunParameter();
81  
82              for (int i = 0; i < NUM_DOCS_TO_CREATE; i++) {
83  
84                  try {
85                      LOG.info("Setting user session for routing of quantity document.");
86                      GlobalVariables.setUserSession(new UserSession("khuntley"));
87                      // create document
88                      RequisitionDocument reqDoc = populateQuantityDocument();
89  
90                      LOG.info("Blanket approving quantity requisition document.");
91                      // route it
92                      documentService.blanketApproveDocument(reqDoc, "auto-routing: Test Requisition Job.", null);
93                  } catch (WorkflowException e) {
94                      e.printStackTrace();
95                  }
96                  Thread.sleep(5000);
97              }
98  
99              for (int i = 0; i < NUM_DOCS_TO_CREATE; i++) {
100 
101                 try {
102                     LOG.info("Setting user session for routing of non-quantity document.");
103                     GlobalVariables.setUserSession(new UserSession("khuntley"));
104                     // create document
105                     RequisitionDocument reqDoc = populateNonQuantityDocument();
106                     LOG.info("Blanket approving non-quantity requisition document.");
107                     // route it
108                     documentService.blanketApproveDocument(reqDoc, "auto-routing: Test Requisition Job.", null);
109                 } catch (WorkflowException e) {
110                     e.printStackTrace();
111                 }
112                 Thread.sleep(5000);
113             }
114 
115 
116             // TODO leaving CAMS docs commented out until problem is fixed
117             // for (int i = 0; i < NUM_DOCS_TO_CREATE; i++) {
118             // RequisitionDocument reqDoc = null;
119             // try {
120             // LOG.info("Setting user session for routing of requisition with capital asset data and addresses.");
121             // GlobalVariables.setUserSession(new UserSession("khuntley"));
122             // // create document
123             // reqDoc = populateCapitalAsset_Individual_WithAddresses_Document();
124             // Thread.sleep(10000);
125             // LOG.info("Blanket approving requisition with capital asset data and addresses.");
126             // // route it
127             // documentService.blanketApproveDocument(reqDoc, "auto-routing: Test Requisition Job.", null);
128             // }
129             // catch (WorkflowException e) {
130             // e.printStackTrace();
131             // }
132             // catch (ValidationException ve) {
133             // continue;
134             // }
135             // Thread.sleep(5000);
136             //
137             // // Use Contract Manager Assignment to create PO.
138             // LOG.info("Setting user session for contract manager assignment of requisition with capital asset data and addresses.");
139             // GlobalVariables.setUserSession(new UserSession("parke"));
140             // LOG.info("Routing Contract Manager Assignment document for requisition with capital asset data and addresses.");
141             // ContractManagerAssignmentDocument acmDoc = createAndRouteContractManagerAssignmentDocument(reqDoc);
142             //
143             // Thread.sleep(20000);
144             //
145             // LOG.info("Routing Purchase Order document for requisition with capital asset data and addresses.");
146             // createAndRoutePurchaseOrderDocument(reqDoc, acmDoc);
147             //
148             // Thread.sleep(5000);
149             // }
150             //
151             // for (int i = 0; i < NUM_DOCS_TO_CREATE; i++) {
152             // RequisitionDocument reqDoc = null;
153             // try {
154             // LOG.info("Setting user session for routing of BAS requisition.");
155             // GlobalVariables.setUserSession(new UserSession("khuntley"));
156             // // create document
157             // reqDoc = populateCapitalAsset_Individual_Unfilled_Document();
158             // Thread.sleep(10000);
159             // LOG.info("Blanket approving BAS requisition.");
160             // // route it
161             // documentService.blanketApproveDocument(reqDoc, "auto-routing: Test Requisition Job.", null);
162             // }
163             // catch (WorkflowException e) {
164             // e.printStackTrace();
165             // }
166             // catch (ValidationException ve) {
167             // continue;
168             // }
169             // Thread.sleep(5000);
170             //
171             // // Use Contract Manager Assignment to create PO.
172             // LOG.info("Setting user session for contract manager assignment BAS requisition.");
173             // GlobalVariables.setUserSession(new UserSession("parke"));
174             // LOG.info("Routing Contract Manager Assignment document for BAS requisition.");
175             // ContractManagerAssignmentDocument acmDoc = createAndRouteContractManagerAssignmentDocument(reqDoc);
176             //
177             // Thread.sleep(20000);
178             //
179             // LOG.info("Routing Purchase Order document for BAS requisition");
180             // createAndRoutePurchaseOrderDocument(reqDoc, acmDoc);
181             //
182             // Thread.sleep(5000);
183             // }
184         }
185 
186         Thread.sleep(60000);
187         return true;
188     }
189 
190     private RequisitionDocument populateQuantityDocument() {
191         LOG.debug("Creating a new requisition.");
192         RequisitionDocument reqDoc = null;
193         try {
194             reqDoc = (RequisitionDocument) documentService.getNewDocument(RequisitionDocument.class);
195             LOG.info("Populating a new requisition.");
196             // RequisitionDocument reqDoc = new RequisitionDocument();
197             // set doc attributes
198             reqDoc.getDocumentHeader().setExplanation("batch created quantity document");
199             DocumentHeader documentHeader = reqDoc.getDocumentHeader();
200             documentHeader.setDocumentDescription("batch created quantity document");
201             reqDoc.setDocumentFundingSourceCode("INST");
202             reqDoc.setRequisitionSourceCode(RequisitionSources.STANDARD_ORDER);
203             reqDoc.setPurchaseOrderTransmissionMethodCode(POTransmissionMethods.NOPRINT);
204             reqDoc.setPurchaseOrderCostSourceCode(POCostSources.ESTIMATE);
205             reqDoc.setChartOfAccountsCode("KO");
206             reqDoc.setOrganizationCode("SBSC");
207             reqDoc.setDeliveryCampusCode("KO");
208             reqDoc.setRequestorPersonName("WATSON,TERRENCE G");
209             reqDoc.setRequestorPersonEmailAddress("tw@localhost.localhost");
210             reqDoc.setRequestorPersonPhoneNumber("812-555-5555");
211             reqDoc.setDeliveryBuildingCode("ADMN");
212             reqDoc.setDeliveryBuildingName("Administration");
213             reqDoc.setDeliveryBuildingRoomNumber("100");
214             reqDoc.setDeliveryBuildingLine1Address("98 smart street");
215             reqDoc.setDeliveryCityName("brainy");
216             reqDoc.setDeliveryStateCode("CA");
217             reqDoc.setDeliveryPostalCode("46202");
218             reqDoc.setDeliveryCountryCode("US");
219             reqDoc.setDeliveryToName("front desk");
220             reqDoc.setBillingName("THE UNIVERSITY");
221             reqDoc.setBillingLine1Address("ACCOUNTS PAYABLE");
222             reqDoc.setBillingCityName("BUTTER NUT");
223             reqDoc.setBillingStateCode("SC");
224             reqDoc.setBillingPostalCode("47402");
225             reqDoc.setBillingCountryCode("US");
226             reqDoc.setBillingPhoneNumber("111-111-1111");
227             reqDoc.setPurchaseOrderAutomaticIndicator(false);
228             reqDoc.setApplicationDocumentStatus(RequisitionStatuses.APPDOC_IN_PROCESS);
229             reqDoc.setVendorHeaderGeneratedIdentifier(1002);
230             reqDoc.setVendorDetailAssignedIdentifier(0);
231             reqDoc.setVendorName("MK CORPORATION ACTIVE");
232             reqDoc.setVendorLine1Address("3894 SOUTH ST");
233             reqDoc.setVendorLine2Address("P.O. BOX 3455");
234             reqDoc.setVendorCityName("SPRINGFIELD");
235             reqDoc.setVendorStateCode("IL");
236             reqDoc.setVendorPostalCode("33555");
237             reqDoc.setVendorCountryCode("US");
238             reqDoc.setUseTaxIndicator(false);
239 
240             // set item attributes
241             RequisitionItem item1 = new RequisitionItem();
242             item1.setItemLineNumber(new Integer(1));
243             item1.setItemUnitOfMeasureCode("PCS");
244             item1.setItemCatalogNumber("P10M980");
245             item1.setItemDescription("Copy Paper - 8 1/2 x 11, White, 92, 20lb");
246             item1.setItemUnitPrice(new BigDecimal(30.20));
247             item1.setItemTypeCode("ITEM");
248             item1.setItemQuantity(new KualiDecimal(20));
249             item1.setExtendedPrice(new KualiDecimal(604));
250             item1.setItemAssignedToTradeInIndicator(false);
251 
252             // set accounting line attributes
253             RequisitionAccount account1 = new RequisitionAccount();
254             account1.setPostingYear(2004);
255             account1.setChartOfAccountsCode("BL");
256             account1.setAccountNumber("1023200");
257             account1.setFinancialObjectCode("4100");
258             account1.setDebitCreditCode(OLEConstants.GL_DEBIT_CODE);
259             account1.setAmount(new KualiDecimal("100"));
260             account1.setAccountLinePercent(new BigDecimal("100"));
261 
262             item1.getSourceAccountingLines().add(account1);
263             reqDoc.getItems().add(item1);
264             reqDoc.fixItemReferences();
265         } catch (WorkflowException e1) {
266             e1.printStackTrace();
267         }
268         return reqDoc;
269     }
270 
271     private RequisitionDocument populateNonQuantityDocument() {
272         RequisitionDocument reqDoc = null;
273         try {
274             reqDoc = (RequisitionDocument) documentService.getNewDocument(RequisitionDocument.class);
275 
276             // RequisitionDocument reqDoc = new RequisitionDocument();
277             // set doc attributes
278             reqDoc.getDocumentHeader().setExplanation("batch created non-quantity document");
279             DocumentHeader documentHeader = reqDoc.getDocumentHeader();
280             documentHeader.setDocumentDescription("batch created non-quantity document");
281             reqDoc.setDocumentFundingSourceCode("INST");
282             reqDoc.setRequisitionSourceCode(RequisitionSources.STANDARD_ORDER);
283             reqDoc.setPurchaseOrderTransmissionMethodCode(POTransmissionMethods.NOPRINT);
284             reqDoc.setPurchaseOrderCostSourceCode(POCostSources.ESTIMATE);
285             reqDoc.setChartOfAccountsCode("KO");
286             reqDoc.setOrganizationCode("SBSC");
287             reqDoc.setDeliveryCampusCode("KO");
288             reqDoc.setDeliveryCountryCode("US");
289             reqDoc.setRequestorPersonName("WATSON,TERRENCE G");
290             reqDoc.setRequestorPersonEmailAddress("tw@localhost.localhost");
291             reqDoc.setRequestorPersonPhoneNumber("812-555-5555");
292             reqDoc.setDeliveryBuildingCode("ADMN");
293             reqDoc.setDeliveryBuildingName("Administration");
294             reqDoc.setDeliveryBuildingRoomNumber("100");
295             reqDoc.setDeliveryBuildingLine1Address("98 smart street");
296             reqDoc.setDeliveryCityName("brainy");
297             reqDoc.setDeliveryStateCode("CA");
298             reqDoc.setDeliveryPostalCode("46202");
299             reqDoc.setDeliveryToName("front desk");
300             reqDoc.setBillingName("THE UNIVERSITY");
301             reqDoc.setBillingLine1Address("ACCOUNTS PAYABLE");
302             reqDoc.setBillingCityName("BUTTER NUT");
303             reqDoc.setBillingStateCode("SC");
304             reqDoc.setBillingPostalCode("47402");
305             reqDoc.setBillingCountryCode("US");
306             reqDoc.setBillingPhoneNumber("111-111-1111");
307             reqDoc.setPurchaseOrderAutomaticIndicator(false);
308             reqDoc.setApplicationDocumentStatus(RequisitionStatuses.APPDOC_IN_PROCESS);
309             reqDoc.setVendorHeaderGeneratedIdentifier(1016);
310             reqDoc.setVendorDetailAssignedIdentifier(0);
311             reqDoc.setVendorName("PHYSIK INSTRUMENT L.P.");
312             reqDoc.setVendorLine1Address("16 AUBURN ST");
313             reqDoc.setVendorCityName("AUBURN");
314             reqDoc.setVendorStateCode("MA");
315             reqDoc.setVendorPostalCode("01501");
316             reqDoc.setVendorCountryCode("US");
317             reqDoc.setUseTaxIndicator(false);
318 
319             // set item attributes
320             RequisitionItem item1 = new RequisitionItem();
321             item1.setItemLineNumber(new Integer(1));
322             item1.setItemUnitOfMeasureCode("");
323             item1.setItemCatalogNumber("");
324             item1.setItemDescription("consulting");
325             item1.setItemUnitPrice(new BigDecimal(5000));
326             item1.setItemTypeCode("SRVC");
327             item1.setItemQuantity(null);
328             item1.setExtendedPrice(new KualiDecimal(5000));
329             item1.setItemAssignedToTradeInIndicator(false);
330 
331             // set accounting line attributes
332             RequisitionAccount account1 = new RequisitionAccount();
333             account1.setPostingYear(2004);
334             account1.setChartOfAccountsCode("BL");
335             account1.setAccountNumber("1023200");
336             account1.setFinancialObjectCode("4078");
337             account1.setDebitCreditCode(OLEConstants.GL_DEBIT_CODE);
338             account1.setAmount(new KualiDecimal("100"));
339             account1.setAccountLinePercent(new BigDecimal("100"));
340 
341             item1.getSourceAccountingLines().add(account1);
342             reqDoc.getItems().add(item1);
343             reqDoc.fixItemReferences();
344         } catch (WorkflowException e1) {
345             e1.printStackTrace();
346         }
347         return reqDoc;
348     }
349 
350     public RequisitionDocument populateCapitalAsset_Individual_WithAddresses_Document() {
351         RequisitionDocument reqDoc = null;
352         try {
353             reqDoc = (RequisitionDocument) documentService.getNewDocument(RequisitionDocument.class);
354 
355             // set doc attributes
356             reqDoc.getDocumentHeader().setExplanation("batch created quantity document for cams");
357             DocumentHeader documentHeader = reqDoc.getDocumentHeader();
358             documentHeader.setDocumentDescription("batch created quantity document for cams");
359             reqDoc.setDocumentFundingSourceCode("INST");
360             reqDoc.setRequisitionSourceCode(RequisitionSources.STANDARD_ORDER);
361             reqDoc.setPurchaseOrderTransmissionMethodCode(POTransmissionMethods.NOPRINT);
362             reqDoc.setPurchaseOrderCostSourceCode(POCostSources.ESTIMATE);
363             reqDoc.setChartOfAccountsCode("UA");
364             reqDoc.setOrganizationCode("VPIT");
365             reqDoc.setDeliveryCampusCode("KO");
366             reqDoc.setRequestorPersonName("WATSON,TERRENCE G");
367             reqDoc.setRequestorPersonEmailAddress("tw@localhost.localhost");
368             reqDoc.setRequestorPersonPhoneNumber("812-555-5555");
369             reqDoc.setDeliveryBuildingCode("ADMN");
370             reqDoc.setDeliveryBuildingName("Administration");
371             reqDoc.setDeliveryBuildingRoomNumber("100");
372             reqDoc.setDeliveryBuildingLine1Address("98 smart street");
373             reqDoc.setDeliveryCityName("brainy");
374             reqDoc.setDeliveryStateCode("CA");
375             reqDoc.setDeliveryPostalCode("46202");
376             reqDoc.setDeliveryToName("front desk");
377             reqDoc.setBillingName("THE UNIVERSITY");
378             reqDoc.setBillingLine1Address("ACCOUNTS PAYABLE");
379             reqDoc.setBillingCityName("BUTTER NUT");
380             reqDoc.setBillingStateCode("SC");
381             reqDoc.setBillingPostalCode("47402");
382             reqDoc.setBillingCountryCode("US");
383             reqDoc.setBillingPhoneNumber("111-111-1111");
384             reqDoc.setPurchaseOrderAutomaticIndicator(false);
385             reqDoc.setApplicationDocumentStatus(RequisitionStatuses.APPDOC_IN_PROCESS);
386             reqDoc.setVendorHeaderGeneratedIdentifier(1002);
387             reqDoc.setVendorDetailAssignedIdentifier(0);
388             reqDoc.setVendorName("MK CORPORATION ACTIVE");
389             reqDoc.setVendorLine1Address("3984 SOUTH ST");
390             reqDoc.setVendorCityName("SPRINGFIELD");
391             reqDoc.setVendorStateCode("IL");
392             reqDoc.setVendorPostalCode("33555");
393             reqDoc.setVendorCountryCode("US");
394             reqDoc.setUseTaxIndicator(false);
395 
396             // set item attributes
397             RequisitionItem item1 = new RequisitionItem();
398             item1.setItemLineNumber(new Integer(1));
399             item1.setItemUnitOfMeasureCode("EA");
400             item1.setItemCatalogNumber("P10M980");
401             item1.setItemDescription("Gas Chromatograph");
402             item1.setItemUnitPrice(new BigDecimal(5000));
403             item1.setItemTypeCode("ITEM");
404             item1.setItemQuantity(new KualiDecimal(2.00));
405             item1.setExtendedPrice(new KualiDecimal(10000));
406             item1.setItemAssignedToTradeInIndicator(false);
407             item1.refreshReferenceObject("itemType");
408 
409             // set accounting line attributes
410             RequisitionAccount account1 = new RequisitionAccount();
411             account1.setPostingYear(2004);
412             account1.setChartOfAccountsCode("BL");
413             account1.setAccountNumber("1023200");
414             account1.setFinancialObjectCode("7000");
415             account1.setDebitCreditCode(OLEConstants.GL_DEBIT_CODE);
416             account1.setAmount(new KualiDecimal("10000"));
417             account1.setAccountLinePercent(new BigDecimal("100"));
418 
419             item1.getSourceAccountingLines().add(account1);
420             reqDoc.getItems().add(item1);
421             reqDoc.fixItemReferences();
422 
423             reqDoc.setCapitalAssetSystemStateCode("NEW");
424             reqDoc.setCapitalAssetSystemTypeCode("IND");
425 
426             // Save here because auto-generated IDs will be needed later.
427             purapService.saveDocumentNoValidation(reqDoc);
428             List<PurchasingCapitalAssetItem> purchasingCapitalAssetItems = new ArrayList();
429             RequisitionCapitalAssetItem capitalAssetItem = (RequisitionCapitalAssetItem) requisitionService.createCamsItem(reqDoc, item1);
430             capitalAssetItem.setCapitalAssetTransactionTypeCode("NEW");
431 
432             RequisitionCapitalAssetSystem system = (RequisitionCapitalAssetSystem) capitalAssetItem.getPurchasingCapitalAssetSystem();
433             system.setCapitalAssetNoteText("CA Notes go here");
434             system.setCapitalAssetNotReceivedCurrentFiscalYearIndicator(false);
435             system.setCapitalAssetManufacturerName("MK CORPORATION ACTIVE");
436             system.setCapitalAssetTypeCode("07034");
437             system.setCapitalAssetModelDescription("XXYYZZ");
438 
439             List<CapitalAssetLocation> locations = new ArrayList();
440 
441             RequisitionCapitalAssetLocation loc1 = new RequisitionCapitalAssetLocation();
442             loc1.setCapitalAssetSystemIdentifier(system.getCapitalAssetSystemIdentifier());
443             loc1.setItemQuantity(new KualiDecimal("1.00"));
444             loc1.setCampusCode("BL");
445             loc1.setBuildingCode("BL001");
446             loc1.setCapitalAssetLine1Address("211 S Indiana Ave");
447             loc1.setBuildingRoomNumber("001");
448             loc1.setCapitalAssetCityName("Bloomington");
449             loc1.setCapitalAssetStateCode("IN");
450             loc1.setCapitalAssetPostalCode("47405-7001");
451             loc1.setCapitalAssetCountryCode("US");
452             locations.add(loc1);
453 
454             RequisitionCapitalAssetLocation loc2 = new RequisitionCapitalAssetLocation();
455             loc2.setCapitalAssetSystemIdentifier(system.getCapitalAssetSystemIdentifier());
456             loc2.setItemQuantity(new KualiDecimal("1.00"));
457             loc2.setCampusCode("BL");
458             loc2.setBuildingCode("BL001");
459             loc2.setCapitalAssetLine1Address("211 S Indiana Ave");
460             loc2.setBuildingRoomNumber("001A");
461             loc2.setCapitalAssetCityName("Bloomington");
462             loc2.setCapitalAssetStateCode("IN");
463             loc2.setCapitalAssetPostalCode("47405-7001");
464             loc2.setCapitalAssetCountryCode("US");
465             locations.add(loc2);
466 
467             system.setCapitalAssetLocations(locations);
468 
469             purchasingCapitalAssetItems.add(capitalAssetItem);
470             reqDoc.setPurchasingCapitalAssetItems(purchasingCapitalAssetItems);
471         } catch (WorkflowException e1) {
472             e1.printStackTrace();
473         }
474         return reqDoc;
475     }
476 
477     private RequisitionDocument populateCapitalAsset_Individual_Unfilled_Document() {
478         RequisitionDocument reqDoc = null;
479         try {
480             reqDoc = (RequisitionDocument) documentService.getNewDocument(RequisitionDocument.class);
481 
482             // set doc attributes
483             reqDoc.getDocumentHeader().setExplanation("batch created quantity document BAS");
484             DocumentHeader documentHeader = reqDoc.getDocumentHeader();
485             documentHeader.setDocumentDescription("batch created quantity document BAS");
486             reqDoc.setDocumentFundingSourceCode("INST");
487             reqDoc.setRequisitionSourceCode(RequisitionSources.STANDARD_ORDER);
488             reqDoc.setPurchaseOrderTransmissionMethodCode(POTransmissionMethods.NOPRINT);
489             reqDoc.setPurchaseOrderCostSourceCode(POCostSources.ESTIMATE);
490             reqDoc.setChartOfAccountsCode("UA");
491             reqDoc.setOrganizationCode("VPIT");
492             reqDoc.setDeliveryCampusCode("KO");
493             reqDoc.setRequestorPersonName("WATSON,TERRENCE G");
494             reqDoc.setRequestorPersonEmailAddress("tw@localhost.localhost");
495             reqDoc.setRequestorPersonPhoneNumber("812-555-5555");
496             reqDoc.setDeliveryBuildingCode("ADMN");
497             reqDoc.setDeliveryBuildingName("Administration");
498             reqDoc.setDeliveryBuildingRoomNumber("100");
499             reqDoc.setDeliveryBuildingLine1Address("98 smart street");
500             reqDoc.setDeliveryCityName("brainy");
501             reqDoc.setDeliveryStateCode("CA");
502             reqDoc.setDeliveryPostalCode("46202");
503             reqDoc.setDeliveryToName("front desk");
504             reqDoc.setBillingName("THE UNIVERSITY");
505             reqDoc.setBillingLine1Address("ACCOUNTS PAYABLE");
506             reqDoc.setBillingCityName("BUTTER NUT");
507             reqDoc.setBillingStateCode("SC");
508             reqDoc.setBillingPostalCode("47402");
509             reqDoc.setBillingCountryCode("US");
510             reqDoc.setBillingPhoneNumber("111-111-1111");
511             reqDoc.setPurchaseOrderAutomaticIndicator(false);
512             reqDoc.setApplicationDocumentStatus(RequisitionStatuses.APPDOC_IN_PROCESS);
513             reqDoc.setVendorHeaderGeneratedIdentifier(1002);
514             reqDoc.setVendorDetailAssignedIdentifier(0);
515             reqDoc.setVendorName("MK CORPORATION ACTIVE");
516             reqDoc.setVendorLine1Address("3984 SOUTH ST");
517             reqDoc.setVendorCityName("SPRINGFIELD");
518             reqDoc.setVendorStateCode("IL");
519             reqDoc.setVendorPostalCode("33555");
520             reqDoc.setVendorCountryCode("US");
521             reqDoc.setUseTaxIndicator(false);
522 
523             // set item attributes
524             RequisitionItem item1 = new RequisitionItem();
525             item1.setItemLineNumber(new Integer(1));
526             item1.setItemUnitOfMeasureCode("EA");
527             item1.setItemCatalogNumber("");
528             item1.setItemDescription("Gas Chromatograph");
529             item1.setItemUnitPrice(new BigDecimal(6000));
530             item1.setItemTypeCode("ITEM");
531             item1.setItemQuantity(new KualiDecimal(1.00));
532             item1.setExtendedPrice(new KualiDecimal(6000));
533             item1.setItemAssignedToTradeInIndicator(false);
534 
535             // set accounting line attributes
536             RequisitionAccount account1 = new RequisitionAccount();
537             account1.setPostingYear(2004);
538             account1.setChartOfAccountsCode("BL");
539             account1.setAccountNumber("1023200");
540             account1.setFinancialObjectCode("7000");
541             account1.setDebitCreditCode(OLEConstants.GL_DEBIT_CODE);
542             account1.setAmount(new KualiDecimal("10000"));
543             account1.setAccountLinePercent(new BigDecimal("100"));
544 
545             item1.getSourceAccountingLines().add(account1);
546             reqDoc.getItems().add(item1);
547             reqDoc.fixItemReferences();
548 
549             reqDoc.setCapitalAssetSystemStateCode("NEW");
550             reqDoc.setCapitalAssetSystemTypeCode("IND");
551 
552             // Save here because auto-generated IDs will be needed later.
553             purapService.saveDocumentNoValidation(reqDoc);
554             List<PurchasingCapitalAssetItem> purchasingCapitalAssetItems = new ArrayList();
555             RequisitionCapitalAssetItem capitalAssetItem = (RequisitionCapitalAssetItem) requisitionService.createCamsItem(reqDoc, item1);
556             capitalAssetItem.setCapitalAssetTransactionTypeCode("NEW");
557 
558             RequisitionCapitalAssetSystem system = (RequisitionCapitalAssetSystem) capitalAssetItem.getPurchasingCapitalAssetSystem();
559             system.setCapitalAssetNoteText("");
560             system.setCapitalAssetNotReceivedCurrentFiscalYearIndicator(false);
561             system.setCapitalAssetManufacturerName("");
562             system.setCapitalAssetTypeCode("");
563             system.setCapitalAssetModelDescription("");
564 
565             purchasingCapitalAssetItems.add(capitalAssetItem);
566             reqDoc.setPurchasingCapitalAssetItems(purchasingCapitalAssetItems);
567         } catch (WorkflowException e1) {
568             e1.printStackTrace();
569         }
570         return reqDoc;
571     }
572 
573     /**
574      * Sets a Run parameter that tells the step that it has already run and it does not need to run again.
575      */
576     private void setInitiatedRunParameter() {
577         // First, see if we can find an existing Parameter object with this key.
578         Parameter runIndicatorParameter = SpringContext.getBean(ParameterService.class).getParameter(PurapMassRequisitionStep.class, Job.STEP_RUN_PARM_NM);
579         if (runIndicatorParameter == null) {
580             Parameter.Builder newParameter = Builder.create(OLEConstants.APPLICATION_NAMESPACE_CODE, PurapConstants.PURAP_NAMESPACE, RUN_INDICATOR_PARAMETER_NAMESPACE_STEP, Job.STEP_RUN_PARM_NM, ParameterType.Builder.create("CONFG"));
581             newParameter.setDescription(RUN_INDICATOR_PARAMETER_DESCRIPTION);
582             newParameter.setEvaluationOperator(EvaluationOperator.ALLOW);
583             newParameter.setValue(RUN_INDICATOR_PARAMETER_VALUE);
584             SpringContext.getBean(ParameterService.class).createParameter(newParameter.build());
585         } else {
586             Parameter.Builder newParameter = Builder.create(runIndicatorParameter);
587             newParameter.setValue(RUN_INDICATOR_PARAMETER_VALUE);
588             SpringContext.getBean(ParameterService.class).updateParameter(newParameter.build());
589         }
590     }
591 
592     /**
593      * Used by setInitiatedRunParameter to build a Map of search keys to obtain the exact needed Run parameter from the database.
594      *
595      * @return A Map<String,Object> where the Objects are the attributes of the Run parameter
596      */
597     private Map<String, Object> buildRunParameterSearchKeyMap() {
598         Map<String, Object> pkMapForParameter = new HashMap<String, Object>();
599 
600         // Set up a list of all the field names and values of the fields in the Parameter object.
601         Map<String, Object> fieldNamesValuesForParameter = new HashMap<String, Object>();
602         fieldNamesValuesForParameter.put("parameterNamespaceCode", PurapConstants.PURAP_NAMESPACE);
603         fieldNamesValuesForParameter.put("parameterDetailTypeCode", RUN_INDICATOR_PARAMETER_NAMESPACE_STEP);
604         fieldNamesValuesForParameter.put("parameterName", Job.STEP_RUN_PARM_NM);
605         fieldNamesValuesForParameter.put("parameterConstraintCode", RUN_INDICATOR_PARAMETER_ALLOWED);
606         fieldNamesValuesForParameter.put("parameterTypeCode", RUN_INDICATOR_PARAMETER_TYPE);
607 
608         // get the primary keys and assign them to values
609         List<String> parameterPKFields = psService.getPrimaryKeys(Parameter.class);
610         for (String pkFieldName : parameterPKFields) {
611             pkMapForParameter.put(pkFieldName, fieldNamesValuesForParameter.get(pkFieldName));
612         }
613         return pkMapForParameter;
614     }
615 
616     private ContractManagerAssignmentDocument createAndRouteContractManagerAssignmentDocument(RequisitionDocument reqDoc) {
617         ContractManagerAssignmentDocument acmDoc = null;
618         try {
619             acmDoc = (ContractManagerAssignmentDocument) documentService.getNewDocument(ContractManagerAssignmentDocument.class);
620             List<ContractManagerAssignmentDetail> contractManagerAssignmentDetails = new ArrayList<ContractManagerAssignmentDetail>();
621             ContractManagerAssignmentDetail detail = new ContractManagerAssignmentDetail(acmDoc, reqDoc);
622             detail.setContractManagerCode(new Integer("10"));
623             detail.refreshReferenceObject("contractManager");
624             contractManagerAssignmentDetails.add(detail);
625             acmDoc.setContractManagerAssignmentDetailss(contractManagerAssignmentDetails);
626             acmDoc.getDocumentHeader().setDocumentDescription("batch-created");
627             documentService.routeDocument(acmDoc, "Routing batch-created Contract Manager Assignment Document", null);
628             ChangeWaiter waiter = new ChangeWaiter(documentService, acmDoc.getDocumentNumber(), "F");
629             try {
630                 waiter.waitUntilChange(waiter, ROUTE_TO_FINAL_SECONDS_LIMIT, 5);
631             } catch (Exception e) {
632                 throw new RuntimeException("ContractManagerAssignmentDocument timed out in routing to final.");
633             }
634         } catch (WorkflowException we) {
635             we.printStackTrace();
636         } catch (ValidationException ve) {
637             ve.printStackTrace();
638         }
639         return acmDoc;
640     }
641 
642     private void createAndRoutePurchaseOrderDocument(RequisitionDocument reqDoc, ContractManagerAssignmentDocument acmDoc) {
643 
644         List<PurchaseOrderView> poViews = reqDoc.getRelatedViews().getRelatedPurchaseOrderViews();
645         if ((poViews != null) && (poViews.size() >= 1)) {
646             // There should be only one related PO at this point, so get that one and route it.
647             PurchaseOrderView poView = poViews.get(0);
648             String relatedPOWorkflowDocumentId = poView.getDocumentNumber();
649             PurchaseOrderDocument poDoc = null;
650             try {
651                 poDoc = (PurchaseOrderDocument) documentService.getByDocumentHeaderId(relatedPOWorkflowDocumentId);
652                 documentService.blanketApproveDocument(poDoc, "auto-routing: Test Requisition Job", null);
653                 ChangeWaiter waiter = new ChangeWaiter(documentService, poDoc.getDocumentNumber(), "F");
654                 try {
655                     waiter.waitUntilChange(waiter, ROUTE_TO_FINAL_SECONDS_LIMIT, 5);
656                 } catch (Exception e) {
657                     throw new RuntimeException("ContractManagerAssignmentDocument timed out in routing to final.");
658                 }
659             } catch (WorkflowException e) {
660                 e.printStackTrace();
661             } catch (ValidationException ve) {
662                 ve.printStackTrace();
663             }
664         }
665     }
666 
667     public DocumentService getDocumentService() {
668         return documentService;
669     }
670 
671     public void setDocumentService(DocumentService documentService) {
672         this.documentService = documentService;
673     }
674 
675     public RequisitionService getRequisitionService() {
676         return requisitionService;
677     }
678 
679     public void setRequisitionService(RequisitionService requisitionService) {
680         this.requisitionService = requisitionService;
681     }
682 
683     public PurapService getPurapService() {
684         return purapService;
685     }
686 
687     public void setPurapService(PurapService purapService) {
688         this.purapService = purapService;
689     }
690 
691     public BusinessObjectService getBoService() {
692         return boService;
693     }
694 
695     public void setBoService(BusinessObjectService boService) {
696         this.boService = boService;
697     }
698 
699     public PersistenceStructureService getPsService() {
700         return psService;
701     }
702 
703     public void setPsService(PersistenceStructureService psService) {
704         this.psService = psService;
705     }
706 
707     /**
708      * Performs the same function as DocumentWorkflowStatusMonitor, which is a test utility, and cannot be used outside that
709      * package. Allows us to wait until a change of Workflow status has occurred.
710      */
711     private class ChangeWaiter {
712 
713         final DocumentService documentService;
714         final private String docHeaderId;
715         final private String[] desiredWorkflowStates;
716 
717         public ChangeWaiter(DocumentService documentService, String docHeaderId, String desiredWorkflowStatus) {
718             this.documentService = documentService;
719             this.docHeaderId = docHeaderId;
720             this.desiredWorkflowStates = new String[]{desiredWorkflowStatus};
721         }
722 
723         public boolean valueChanged() throws Exception {
724             Document d = documentService.getByDocumentHeaderId(docHeaderId.toString());
725 
726             String currentStatus = d.getDocumentHeader().getWorkflowDocument().getStatus().toString();
727 
728             for (String desiredWorkflowState : desiredWorkflowStates) {
729                 if (StringUtils.equals(desiredWorkflowState, currentStatus)) {
730                     return true;
731                 }
732             }
733             return false;
734         }
735 
736         public boolean waitUntilChange(ChangeWaiter monitor, int maxWaitSeconds, int pauseSeconds) throws Exception {
737             long maxWaitMs = maxWaitSeconds * 1000;
738             long pauseMs = pauseSeconds * 1000;
739 
740             boolean valueChanged = false;
741             boolean interrupted = false;
742             long startTimeMs = System.currentTimeMillis();
743             long endTimeMs = startTimeMs + maxWaitMs;
744 
745             Thread.sleep(pauseMs / 10); // the first time through, sleep a fraction of the specified time
746             valueChanged = monitor.valueChanged();
747             LOG.debug("starting wait loop");
748             while (!interrupted && !valueChanged && (System.currentTimeMillis() < endTimeMs)) {
749                 try {
750                     if (LOG.isDebugEnabled()) {
751                         LOG.debug("sleeping for " + pauseMs + " ms");
752                     }
753                     Thread.sleep(pauseMs);
754                 } catch (InterruptedException e) {
755                     interrupted = true;
756                 }
757                 LOG.debug("checking wait loop sentinel");
758                 valueChanged = monitor.valueChanged();
759             }
760             if (LOG.isDebugEnabled()) {
761                 LOG.debug("finished wait loop (" + valueChanged + ")");
762             }
763 
764             return valueChanged;
765         }
766     }
767 
768 }