/**
   * verifies that rule exports are the same regardless of whether the rule is ready for render, or
   * for persistance.
   */
  protected void assertRuleBaseValuesStateIndependence() throws Exception {
    for (Object o : KEWServiceLocator.getRuleService().fetchAllRules(true)) {
      RuleBaseValues rule = (RuleBaseValues) o;
      KewExportDataSet dataSet = new KewExportDataSet();
      dataSet.getRules().add(rule);

      // first, do a conversion in the just-loaded state:
      byte[] saveXmlBytes =
          CoreApiServiceLocator.getXmlExporterService().export(dataSet.createExportDataSet());
      String saveStr = new String(saveXmlBytes);

      // now, convert for render:
      WebRuleUtils.populateRuleMaintenanceFields(rule);

      // do another conversion in the ready-for-render state:
      byte[] loadXmlBytes =
          CoreApiServiceLocator.getXmlExporterService().export(dataSet.createExportDataSet());
      String loadStr = new String(loadXmlBytes);

      // check that the results are identical:
      assertTrue(
          "The load/render state of the RuleBaseValues shouldn't effect the export: \n"
              + saveStr
              + "\n\n != \n\n"
              + loadStr,
          StringUtils.equals(saveStr, loadStr));
    }
  }
Exemple #2
0
 public static boolean checkDateRanges(String fromDate, String toDate) {
   try {
     Date parsedDate = CoreApiServiceLocator.getDateTimeService().convertToDate(fromDate.trim());
     Calendar fromCalendar = Calendar.getInstance();
     fromCalendar.setLenient(false);
     fromCalendar.setTime(parsedDate);
     fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
     fromCalendar.set(Calendar.MINUTE, 0);
     fromCalendar.set(Calendar.SECOND, 0);
     fromCalendar.set(Calendar.MILLISECOND, 0);
     parsedDate = CoreApiServiceLocator.getDateTimeService().convertToDate(toDate.trim());
     Calendar toCalendar = Calendar.getInstance();
     toCalendar.setLenient(false);
     toCalendar.setTime(parsedDate);
     toCalendar.set(Calendar.HOUR_OF_DAY, 0);
     toCalendar.set(Calendar.MINUTE, 0);
     toCalendar.set(Calendar.SECOND, 0);
     toCalendar.set(Calendar.MILLISECOND, 0);
     if (fromCalendar.after(toCalendar)) {
       return false;
     }
     return true;
   } catch (Exception ex) {
     return false;
   }
 }
  protected MailMessage composeMessage(MailMessage message) {

    MailMessage mm = new MailMessage();

    // If realNotificationsEnabled is false, mails will be sent to
    // nonProductionNotificationMailingList
    if (!isRealNotificationsEnabled()) {
      getNonProductionMessage(message);
    }

    String app =
        CoreApiServiceLocator.getKualiConfigurationService()
            .getPropertyValueAsString(CoreConstants.Config.APPLICATION_ID);
    String env =
        CoreApiServiceLocator.getKualiConfigurationService()
            .getPropertyValueAsString(KRADConstants.ENVIRONMENT_KEY);

    mm.setToAddresses(message.getToAddresses());
    mm.setBccAddresses(message.getBccAddresses());
    mm.setCcAddresses(message.getCcAddresses());
    mm.setSubject(app + " " + env + ": " + message.getSubject());
    mm.setMessage(message.getMessage());
    mm.setFromAddress(message.getFromAddress());
    return mm;
  }
 public void removeSubAwardAttachment(BudgetSubAwards subAward) {
   subAward.setFormName(null);
   subAward.setNamespace(null);
   subAward.setSubAwardXfdFileData(null);
   subAward.setSubAwardXfdFileName(null);
   subAward.setSubAwardXmlFileData(null);
   subAward.setXfdUpdateUser(null);
   subAward.getBudgetSubAwardAttachments().clear();
   subAward.getBudgetSubAwardFiles().clear();
   subAward.setXfdUpdateUser(getLoggedInUserNetworkId());
   subAward.setXfdUpdateTimestamp(
       CoreApiServiceLocator.getDateTimeService().getCurrentTimestamp());
   subAward.setXmlUpdateUser(getLoggedInUserNetworkId());
   subAward.setXmlUpdateTimestamp(
       CoreApiServiceLocator.getDateTimeService().getCurrentTimestamp());
 }
  /**
   * Retrieves validation errors from GlobalVariables MessageMap and appends to the given list of
   * RemotableAttributeError
   *
   * @param validationErrors list to append validation errors
   */
  protected void retrieveValidationErrorsFromGlobalVariables(
      List<RemotableAttributeError> validationErrors) {
    // can we use KualiConfigurationService?  It seemed to be used elsewhere...
    ConfigurationService configurationService =
        CoreApiServiceLocator.getKualiConfigurationService();

    if (GlobalVariables.getMessageMap().hasErrors()) {
      MessageMap deepCopy =
          (MessageMap) SerializationUtils.deepCopy(GlobalVariables.getMessageMap());
      for (String errorKey : deepCopy.getErrorMessages().keySet()) {
        List<ErrorMessage> errorMessages = deepCopy.getErrorMessages().get(errorKey);
        if (CollectionUtils.isNotEmpty(errorMessages)) {
          List<String> errors = new ArrayList<String>();
          for (ErrorMessage errorMessage : errorMessages) {
            // need to materialize the message from it's parameters so we can send it back to the
            // framework
            String error =
                MessageFormat.format(
                    configurationService.getPropertyValueAsString(errorMessage.getErrorKey()),
                    errorMessage.getMessageParameters());
            errors.add(error);
          }
          RemotableAttributeError remotableAttributeError =
              RemotableAttributeError.Builder.create(errorKey, errors).build();
          validationErrors.add(remotableAttributeError);
        }
      }
      // we should now strip the error messages from the map because they have moved to
      // validationErrors
      GlobalVariables.getMessageMap().clearErrorMessages();
    }
  }
Exemple #6
0
  /**
   * route the document using the document service
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return ActionForward
   * @throws Exception
   */
  @Override
  public ActionForward route(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    AwardBudgetDocument awardBudgetDocument = ((AwardBudgetForm) form).getAwardBudgetDocument();
    Award currentAward =
        getAwardBudgetService()
            .getActiveOrNewestAward(
                ((AwardDocument) awardBudgetDocument.getBudget().getBudgetParent().getDocument())
                    .getAward()
                    .getAwardNumber());
    ScaleTwoDecimal newCostLimit = getAwardBudgetService().getTotalCostLimit(currentAward);
    if (!newCostLimit.equals(awardBudgetDocument.getBudget().getTotalCostLimit())
        || !getAwardBudgetService()
            .limitsMatch(
                currentAward.getAwardBudgetLimits(),
                awardBudgetDocument.getAwardBudget().getAwardBudgetLimits())) {
      Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME);
      Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
      String methodToCall = ((KualiForm) form).getMethodToCall();
      if (question == null) {
        ConfigurationService kualiConfiguration =
            CoreApiServiceLocator.getKualiConfigurationService();
        return confirm(
            buildParameterizedConfirmationQuestion(
                mapping,
                form,
                request,
                response,
                UPDATE_COST_LIMITS_QUESTION,
                KeyConstants.QUESTION_TOTALCOSTLIMIT_CHANGED),
            methodToCall,
            methodToCall);
      } else if (UPDATE_COST_LIMITS_QUESTION.equals(question)
          && ConfirmationQuestion.YES.equals(buttonClicked)) {
        getAwardBudgetService().setBudgetLimits(awardBudgetDocument, currentAward);
        return mapping.findForward(Constants.MAPPING_AWARD_BASIC);
      } else {
        // do nothing and continue with route
      }
    }
    ((AwardBudgetForm) form).setAuditActivated(true);
    ValidationState state =
        KcServiceLocator.getService(AuditHelper.class)
            .isValidSubmission((AwardBudgetForm) form, true);
    if (state != ValidationState.ERROR) {
      getAwardBudgetService().processSubmision(awardBudgetDocument);
      return super.route(mapping, form, request, response);
    } else {
      GlobalVariables.getMessageMap().clearErrorMessages();
      GlobalVariables.getMessageMap()
          .putError("datavalidation", KeyConstants.ERROR_WORKFLOW_SUBMISSION, new String[] {});

      return mapping.findForward(Constants.MAPPING_AWARD_BASIC);
    }
  }
 @Override
 public String convertToEntityAttribute(String dataValue) {
   // don't attempt to decrypt nulls or empty strings
   if (dataValue == null) {
     return null;
   }
   if (StringUtils.isEmpty(dataValue.toString())) {
     return "";
   }
   try {
     // check if the encryption service is enable before using it
     if (CoreApiServiceLocator.getEncryptionService().isEnabled()) {
       return CoreApiServiceLocator.getEncryptionService().decrypt(dataValue.toString());
     }
   } catch (Exception e) {
     throw new RuntimeException("Exception while attempting to decrypt value from DB: ", e);
   }
   return dataValue;
 }
 @Override
 public String convertToDatabaseColumn(String objectValue) {
   // don't attempt to encrypt nulls or empty strings
   if (objectValue == null) {
     return null;
   }
   if (StringUtils.isEmpty(objectValue.toString())) {
     return "";
   }
   try {
     // check if the encryption service is enable before using it
     if (CoreApiServiceLocator.getEncryptionService().isEnabled()) {
       return CoreApiServiceLocator.getEncryptionService().encrypt(objectValue);
     }
   } catch (Exception e) {
     throw new RuntimeException("Exception while attempting to encrypt value for DB: ", e);
   }
   return objectValue;
 }
 public Map<String, String> getDefaultReplacementParameters() {
   Map<String, String> params = super.getDefaultReplacementParameters();
   params.put(
       ProtocolReplacementParameters.REASON,
       StringUtils.isNotBlank(reason)
           ? reason
           : CoreApiServiceLocator.getKualiConfigurationService()
               .getPropertyValueAsString(NO_REASON_GIVEN));
   return params;
 }
 /**
  * Uses the key returned by {@link #getPatternTypeKey()} to fetch the validationPattern's regex
  * string from the ConfigurationService which should not include the start(^) and end($) symbols
  *
  * @return String regex validation string
  */
 @Override
 protected String getRegexString() {
   if (StringUtils.isBlank(getPatternTypeKey())) {
     throw new IllegalArgumentException(
         "patternTypeKey is null, configuration of "
             + this.getClass().getName()
             + " is incomplete");
   }
   return CoreApiServiceLocator.getKualiConfigurationService()
       .getPropertyValueAsString(getPatternTypeKey());
 }
  public void populateBudgetSubAwardFiles(
      Budget budget, BudgetSubAwards subAward, String newFileName, byte[] newFileData) {
    subAward.setSubAwardStatusCode(1);
    BudgetSubAwardFiles newSubAwardFile = new BudgetSubAwardFiles();
    newSubAwardFile.setSubAwardXfdFileData(newFileData);
    subAward.getBudgetSubAwardAttachments().clear();
    subAward.getBudgetSubAwardFiles().clear();
    subAward.getBudgetSubAwardFiles().add(newSubAwardFile);

    boolean subawardBudgetExtracted = false;

    try {
      byte[] pdfFileContents = newSubAwardFile.getSubAwardXfdFileData();
      subAward.setSubAwardXfdFileData(pdfFileContents);
      PdfReader reader = new PdfReader(pdfFileContents);
      byte[] xmlContents = getXMLFromPDF(reader);
      subawardBudgetExtracted = (xmlContents != null && xmlContents.length > 0);
      if (subawardBudgetExtracted) {
        Map fileMap = extractAttachments(reader);
        updateXML(xmlContents, fileMap, subAward, budget);
      }
    } catch (Exception e) {
      LOG.error("Not able to extract xml from pdf", e);
      subawardBudgetExtracted = false;
    }

    newSubAwardFile.setSubAwardXfdFileData(subAward.getSubAwardXfdFileData());
    if (subawardBudgetExtracted) {
      newSubAwardFile.setSubAwardXmlFileData(new String(subAward.getSubAwardXmlFileData()));
    }
    newSubAwardFile.setSubAwardXfdFileName(newFileName);
    newSubAwardFile.setBudgetId(subAward.getBudgetId());
    newSubAwardFile.setSubAwardNumber(subAward.getSubAwardNumber());
    subAward.setSubAwardXfdFileName(newFileName);
    subAward.setXfdUpdateUser(getLoggedInUserNetworkId());
    subAward.setXfdUpdateTimestamp(
        CoreApiServiceLocator.getDateTimeService().getCurrentTimestamp());
    subAward.setXmlUpdateUser(getLoggedInUserNetworkId());
    subAward.setXmlUpdateTimestamp(
        CoreApiServiceLocator.getDateTimeService().getCurrentTimestamp());
  }
  /**
   * Note that the assertion here will fail if you have multiple rules with the same description.
   */
  protected void assertExport() throws Exception {
    // export all existing rules and their dependencies (document types, rule templates, rule
    // attributes)
    List oldRules = KEWServiceLocator.getRuleService().fetchAllRules(true);
    assertAllRulesHaveUniqueNames(oldRules);
    List oldRuleDelegations =
        KEWServiceLocator.getRuleDelegationService().findAllCurrentRuleDelegations();
    assertAllRuleDelegationsHaveUniqueNames(oldRuleDelegations);

    KewExportDataSet dataSet = new KewExportDataSet();
    dataSet.getRules().addAll(oldRules);
    dataSet.getRuleDelegations().addAll(oldRuleDelegations);
    dataSet.getDocumentTypes().addAll(KEWServiceLocator.getDocumentTypeService().findAllCurrent());
    dataSet.getRuleTemplates().addAll(KEWServiceLocator.getRuleTemplateService().findAll());
    dataSet.getRuleAttributes().addAll(KEWServiceLocator.getRuleAttributeService().findAll());
    byte[] xmlBytes =
        CoreApiServiceLocator.getXmlExporterService().export(dataSet.createExportDataSet());
    assertTrue("XML should be non empty.", xmlBytes != null && xmlBytes.length > 0);

    // now clear the tables
    ClearDatabaseLifecycle clearLifeCycle = new ClearDatabaseLifecycle();
    clearLifeCycle.getTablesToClear().add("KREW_RULE_T");
    clearLifeCycle.getTablesToClear().add("KREW_RULE_RSP_T");
    clearLifeCycle.getTablesToClear().add("KREW_DLGN_RSP_T");
    clearLifeCycle.getTablesToClear().add("KREW_RULE_ATTR_T");
    clearLifeCycle.getTablesToClear().add("KREW_RULE_TMPL_T");
    clearLifeCycle.getTablesToClear().add("KREW_DOC_TYP_T");
    clearLifeCycle.start();
    new ClearCacheLifecycle().stop();

    // import the exported xml
    loadXmlStream(new BufferedInputStream(new ByteArrayInputStream(xmlBytes)));

    List newRules = KEWServiceLocator.getRuleService().fetchAllRules(true);
    assertEquals("Should have same number of old and new Rules.", oldRules.size(), newRules.size());
    for (Iterator iterator = oldRules.iterator(); iterator.hasNext(); ) {
      RuleBaseValues oldRule = (RuleBaseValues) iterator.next();
      boolean foundRule = false;
      for (Iterator iterator2 = newRules.iterator(); iterator2.hasNext(); ) {
        RuleBaseValues newRule = (RuleBaseValues) iterator2.next();
        if (oldRule.getDescription().equals(newRule.getDescription())) {
          assertRuleExport(oldRule, newRule);
          foundRule = true;
        }
      }
      assertTrue(
          "Could not locate the new rule for description " + oldRule.getDescription(), foundRule);
    }

    List newRuleDelegations =
        KEWServiceLocator.getRuleDelegationService().findAllCurrentRuleDelegations();
    assertDelegations(oldRuleDelegations, newRuleDelegations);
  }
  /**
   * Determines what Timestamp should be used for active queries on effective dated records.
   * Determination made as follows:
   *
   * <ul>
   *   <li>Use activeAsOfDate value from search values Map if value is not empty
   *   <li>If search value given, try to convert to sql date, if conversion fails, try to convert to
   *       Timestamp
   *   <li>If search value empty, use current Date
   *   <li>If Timestamp value not given, create Timestamp from given Date setting the time as 1
   *       second before midnight
   * </ul>
   *
   * @param searchValues - Map containing search key/value pairs
   * @return Timestamp to be used for active criteria
   */
  public static Timestamp getActiveDateTimestampForCriteria(Map searchValues) {
    Date activeDate = CoreApiServiceLocator.getDateTimeService().getCurrentSqlDate();
    Timestamp activeTimestamp = null;
    if (searchValues.containsKey(KRADPropertyConstants.ACTIVE_AS_OF_DATE)) {
      String activeAsOfDate = (String) searchValues.get(KRADPropertyConstants.ACTIVE_AS_OF_DATE);
      if (StringUtils.isNotBlank(activeAsOfDate)) {
        try {
          activeDate =
              CoreApiServiceLocator.getDateTimeService()
                  .convertToSqlDate(ObjectUtils.clean(activeAsOfDate));
        } catch (ParseException e) {
          // try to parse as timestamp
          try {
            activeTimestamp =
                CoreApiServiceLocator.getDateTimeService()
                    .convertToSqlTimestamp(ObjectUtils.clean(activeAsOfDate));
          } catch (ParseException e1) {
            throw new RuntimeException(
                "Unable to convert date: " + ObjectUtils.clean(activeAsOfDate));
          }
        }
      }
    }

    // if timestamp not given set to 1 second before midnight on the given date
    if (activeTimestamp == null) {
      Calendar cal = Calendar.getInstance();
      cal.setTime(activeDate);
      cal.set(Calendar.HOUR, cal.getMaximum(Calendar.HOUR));
      cal.set(Calendar.MINUTE, cal.getMaximum(Calendar.MINUTE));
      cal.set(Calendar.SECOND, cal.getMaximum(Calendar.SECOND));

      activeTimestamp = new Timestamp(cal.getTime().getTime());
    }

    return activeTimestamp;
  }
Exemple #14
0
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   ExportDataSet dataSet = (ExportDataSet) request.getSession().getAttribute(EXPORT_DATA_SET_KEY);
   request.getSession().removeAttribute(EXPORT_DATA_SET_KEY);
   if (dataSet == null) {
     throw new ServletException("No data set was specified.");
   }
   String contentType = "application/xml";
   XmlExporterService exporter = CoreApiServiceLocator.getXmlExporterService();
   byte[] data = exporter.export(dataSet);
   response.setContentType(contentType);
   response.setContentLength(data.length);
   response.setHeader("Content-disposition", "attachment; filename=" + extractFileName(request));
   response.getOutputStream().write(data);
   response.getOutputStream().close();
 }
Exemple #15
0
  /**
   * Close the document and take the user back to the index; only after asking the user if they want
   * to save the document first. Only users who have the "canSave()" permission are given this
   * option.
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return ActionForward
   * @throws Exception
   */
  @Override
  public ActionForward close(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    KualiDocumentFormBase docForm = (KualiDocumentFormBase) form;
    // only want to prompt them to save if they already can save
    if (docForm.getDocumentActions().containsKey(KRADConstants.KUALI_ACTION_CAN_SAVE)) {
      Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME);
      ConfigurationService kualiConfiguration =
          CoreApiServiceLocator.getKualiConfigurationService();

      // logic for close question
      if (question == null) {
        // ask question if not already asked
        return this.performQuestionWithoutInput(
            mapping,
            form,
            request,
            response,
            KRADConstants.DOCUMENT_SAVE_BEFORE_CLOSE_QUESTION,
            kualiConfiguration.getPropertyValueAsString(
                RiceKeyConstants.QUESTION_SAVE_BEFORE_CLOSE),
            KRADConstants.CONFIRMATION_QUESTION,
            KRADConstants.MAPPING_CLOSE,
            "");
      } else {
        BudgetForm budgetForm = (BudgetForm) form;
        Budget budget = budgetForm.getBudgetDocument().getBudget();

        Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
        if ((KRADConstants.DOCUMENT_SAVE_BEFORE_CLOSE_QUESTION.equals(question))
            && ConfirmationQuestion.YES.equals(buttonClicked)) {
          // if yes button clicked - save the doc
          getBudgetJustificationService().preSave(budget, getBudgetJusticationWrapper(form));
        }
        // else go to close logic below
      }
    }

    return super.close(mapping, form, request, response);
  }
  protected void assertExport() throws Exception {
    // export all existing rule templates and their dependencies (rule attributes)
    List oldRuleTemplates = KEWServiceLocator.getRuleTemplateService().findAll();
    KewExportDataSet dataSet = new KewExportDataSet();
    dataSet.getRuleTemplates().addAll(oldRuleTemplates);
    dataSet.getRuleAttributes().addAll(KEWServiceLocator.getRuleAttributeService().findAll());
    byte[] xmlBytes =
        CoreApiServiceLocator.getXmlExporterService().export(dataSet.createExportDataSet());
    assertTrue("XML should be non empty.", xmlBytes != null && xmlBytes.length > 0);

    // now clear the tables
    new ClearDatabaseLifecycle(getPerTestTablesToClear(), getPerTestTablesNotToClear()).start();

    // import the exported xml
    loadXmlStream(new BufferedInputStream(new ByteArrayInputStream(xmlBytes)));

    List newRuleTemplates = KEWServiceLocator.getRuleTemplateService().findAll();
    assertEquals(
        "Should have same number of old and new RuleTemplates.",
        oldRuleTemplates.size(),
        newRuleTemplates.size());
    for (Iterator iterator = oldRuleTemplates.iterator(); iterator.hasNext(); ) {
      RuleTemplateBo oldRuleTemplate = (RuleTemplateBo) iterator.next();
      boolean foundTemplate = false;
      for (Iterator iterator2 = newRuleTemplates.iterator(); iterator2.hasNext(); ) {
        RuleTemplateBo newRuleTemplate = (RuleTemplateBo) iterator2.next();
        if (oldRuleTemplate.getName().equals(newRuleTemplate.getName())) {
          assertRuleTemplateExport(oldRuleTemplate, newRuleTemplate);
          foundTemplate = true;
        }
      }
      assertTrue(
          "Could not locate the new rule template for name " + oldRuleTemplate.getName(),
          foundTemplate);
    }
  }
  @Override
  @RequestMapping(params = "methodToCall=docHandler")
  public ModelAndView docHandler(
      @ModelAttribute("KualiForm") DocumentFormBase formBase,
      BindingResult result,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // TODO getting double view if we call base, not sure how to handle
    // so pasting in superclass code
    // super.docHandler(formBase, request, response);
    // * begin copy/paste from the base
    MaintenanceDocumentForm form = (MaintenanceDocumentForm) formBase;

    // in all of the following cases we want to load the document
    if (ArrayUtils.contains(DOCUMENT_LOAD_COMMANDS, form.getCommand()) && form.getDocId() != null) {
      try {
        loadDocument(form);
        OlePersistableBusinessObjectBase olePersistableBusinessObjectBase =
            (OlePersistableBusinessObjectBase)
                form.getDocument().getNewMaintainableObject().getDataObject();
        olePersistableBusinessObjectBase.setAlertBoList(
            alertService.retrieveAlertList(form.getDocument().getDocumentNumber()));
      } catch (UnknownDocumentIdException udie) {
        ConfigurationService kualiConfigurationService =
            CoreApiServiceLocator.getKualiConfigurationService();
        StringBuffer sb = new StringBuffer();
        sb.append(kualiConfigurationService.getPropertyValueAsString(KRADConstants.KRAD_URL_KEY));
        sb.append(
            kualiConfigurationService.getPropertyValueAsString(
                KRADConstants.KRAD_INITIATED_DOCUMENT_URL_KEY));
        Properties props = new Properties();
        props.put(UifParameters.METHOD_TO_CALL, UifConstants.MethodToCallNames.START);
        GlobalVariables.getUifFormManager().removeSessionForm(form); // removeForm(form);
        return performRedirect(new InitiatedDocumentInfoForm(), sb.toString(), props);
      }
    } else if (KewApiConstants.INITIATE_COMMAND.equals(form.getCommand())) {
      createDocument(form);
    } else {
      LOG.error("docHandler called with invalid parameters");
      throw new IllegalArgumentException("docHandler called with invalid parameters");
    }
    // * end copy/paste from the base

    if (KewApiConstants.ACTIONLIST_COMMAND.equals(form.getCommand())
        || KewApiConstants.DOCSEARCH_COMMAND.equals(form.getCommand())
        || KewApiConstants.SUPERUSER_COMMAND.equals(form.getCommand())
        || KewApiConstants.HELPDESK_ACTIONLIST_COMMAND.equals(form.getCommand())
            && form.getDocId() != null) {
      // TODO: set state in view
      // form.setReadOnly(true);
      form.setMaintenanceAction(
          (form.getDocument()).getNewMaintainableObject().getMaintenanceAction());

      // Retrieving the FileName from BO table
      Maintainable tmpMaintainable = form.getDocument().getNewMaintainableObject();
      if (tmpMaintainable.getDataObject() instanceof PersistableAttachment) {
        PersistableAttachment bo =
            (PersistableAttachment)
                getBusinessObjectService()
                    .retrieve((PersistableBusinessObject) tmpMaintainable.getDataObject());
        if (bo != null) {
          request.setAttribute("fileName", bo.getFileName());
        }
      }
    } else if (KewApiConstants.INITIATE_COMMAND.equals(form.getCommand())) {
      // form.setReadOnly(false);
      setupMaintenance(form, request, KRADConstants.MAINTENANCE_NEW_ACTION);
    } else {
      LOG.error("We should never have gotten to here");
      throw new IllegalArgumentException("docHandler called with invalid parameters");
    }

    return getUIFModelAndView(form);
  }
 private static ConfigurationService getKualiConfigurationService() {
   if (kualiConfigurationService == null) {
     kualiConfigurationService = CoreApiServiceLocator.getKualiConfigurationService();
   }
   return kualiConfigurationService;
 }
 protected DateTimeService getDateTimeService() {
   if (this.dateTimeService == null) {
     this.dateTimeService = CoreApiServiceLocator.getDateTimeService();
   }
   return this.dateTimeService;
 }
  public void run() {
    // if(!directoriesWritable()){
    //     LOG.error("Error writing to xml data directories. Stopping xmlLoader ...");
    //     this.cancel();
    // }
    LOG.debug("checking for xml data files...");
    File[] files = getXmlPendingDir().listFiles();
    if (files == null || files.length == 0) {
      return;
    }
    LOG.info("Found " + files.length + " files to ingest.");
    List<XmlDocCollection> collections = new ArrayList<XmlDocCollection>();
    for (File file : files) {
      if (file.isDirectory()) {
        collections.add(new DirectoryXmlDocCollection(file));
      } else if (file.getName().equals(PENDING_MOVE_FAILED_ARCHIVE_FILE)) {
        // the movesfailed file...ignore this
        continue;
      } else if (file.getName().toLowerCase().endsWith(".zip")) {
        try {
          collections.add(new ZipXmlDocCollection(file));
        } catch (IOException ioe) {
          LOG.error("Unable to load file: " + file);
        }
      } else if (file.getName().endsWith(".xml")) {
        collections.add(new FileXmlDocCollection(file));
      } else {
        LOG.warn("Ignoring extraneous file in xml pending directory: " + file);
      }
    }

    // Cull any resources which were already processed and whose moves failed
    Iterator collectionsIt = collections.iterator();
    Collection<XmlDocCollection> culled = new ArrayList<XmlDocCollection>();
    while (collectionsIt.hasNext()) {
      XmlDocCollection container = (XmlDocCollection) collectionsIt.next();
      // if a move has already failed for this archive, ignore it
      if (inPendingMoveFailedArchive(container.getFile())) {
        LOG.info("Ignoring previously processed resource: " + container);
        culled.add(container);
      }
    }
    collections.removeAll(culled);

    if (collections.size() == 0) {
      LOG.debug("No valid new resources found to ingest");
      return;
    }

    Date LOAD_TIME = Calendar.getInstance().getTime();
    // synchronization around date format should not be an issue as this code is single-threaded
    File completeDir = new File(getXmlCompleteDir(), DIR_FORMAT.format(LOAD_TIME));
    File failedDir = new File(getXmlProblemDir(), DIR_FORMAT.format(LOAD_TIME));

    // now ingest the containers
    Collection failed = null;
    try {
      failed = CoreApiServiceLocator.getXmlIngesterService().ingest(collections);
    } catch (Exception e) {
      LOG.error("Error ingesting data", e);
      // throw new RuntimeException(e);
    }

    // now iterate through all containers again, and move containers to approprate dir
    LOG.info("Moving files...");
    collectionsIt = collections.iterator();
    while (collectionsIt.hasNext()) {
      XmlDocCollection container = (XmlDocCollection) collectionsIt.next();
      LOG.debug("container: " + container);
      try {
        // "close" the container
        // this only matters for ZipFiles for now
        container.close();
      } catch (IOException ioe) {
        LOG.warn("Error closing " + container, ioe);
      }
      if (failed.contains(container)) {
        // some docs must have failed, move the whole
        // container to the failed dir
        if (container.getFile() != null) {
          LOG.error("Moving " + container.getFile() + " to problem dir.");
          if ((!failedDir.isDirectory() && !failedDir.mkdirs())
              || !moveFile(failedDir, container.getFile())) {
            LOG.error("Could not move: " + container.getFile());
            recordUnmovablePendingFile(container.getFile(), LOAD_TIME);
          }
        }
      } else {
        if (container.getFile() != null) {
          LOG.info("Moving " + container.getFile() + " to loaded dir.");
          if ((!completeDir.isDirectory() && !completeDir.mkdirs())
              || !moveFile(completeDir, container.getFile())) {
            LOG.error("Could not move: " + container.getFile());
            recordUnmovablePendingFile(container.getFile(), LOAD_TIME);
          }
        }
      }
    }
  }
 protected ConfigurationService getKualiConfigurationService() {
   return CoreApiServiceLocator.getKualiConfigurationService();
 }