public ActionForward store(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response,
      SessionAPI session)
      throws Exception {

    // Comprobar si el usuario tiene asignadas las funciones adecuadas
    FunctionHelper.checkFunctions(
        request, session.getClientContext(), new int[] {ISecurityAPI.FUNC_COMP_CALENDARS_EDIT});

    ClientContext cct = session.getClientContext();

    IInvesflowAPI invesFlowAPI = session.getAPI();
    ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI();

    // Formulario asociado a la acción
    CalendarForm defaultForm = (CalendarForm) form;

    // int keyId = Integer.parseInt(defaultForm.getKey());
    // int entityId = Integer.parseInt(defaultForm.getEntity());

    String parameter = request.getParameter("entityId");
    if (parameter == null) {
      parameter = defaultForm.getEntity();
    }
    int entityId = Integer.parseInt(parameter);

    parameter = request.getParameter("regId");
    int condicion = Integer.parseInt(parameter);

    if (parameter == null) {
      parameter = defaultForm.getKey();
    }
    int keyId = Integer.parseInt(parameter);

    EntityApp entityapp = null;
    String path = getRealPath("");

    // Ejecución en un contexto transaccional
    boolean bCommit = false;

    try {
      // Abrir transacción
      cct.beginTX();

      // Obtener la aplicación que gestiona la entidad
      if (keyId == ISPACEntities.ENTITY_NULLREGKEYID) {

        entityapp = catalogAPI.newCTDefaultEntityApp(entityId, path);
        keyId = entityapp.getEntityRegId();
      } else {
        entityapp = catalogAPI.getCTDefaultEntityApp(entityId, path);
      }

      // Permite modificar los datos del formulario
      defaultForm.setReadonly("false");
      // Salva el identificador de la entidad
      defaultForm.setEntity(Integer.toString(entityId));
      // Salva el identificador del registro
      defaultForm.setKey(Integer.toString(keyId));
      defaultForm.processEntityApp(entityapp);

      // Se le asigna la clave del registro. Es necesario ya que el
      // item al que hace referencia puede estar recien creado y por tanto
      // tendría su campo clave a -1 (ISPACEntities.ENTITY_REGKEYID)
      entityapp.getItem().setKey(keyId);

      // entityapp.setAppName("EditCalendar");
      if (!entityapp.validate()) {

        ActionMessages errors = new ActionMessages();
        List errorList = entityapp.getErrors();
        Iterator iteError = errorList.iterator();
        while (iteError.hasNext()) {

          ValidationError validError = (ValidationError) iteError.next();
          ActionMessage error = new ActionMessage(validError.getErrorKey(), validError.getArgs());
          errors.add("property(NOMBRE)", error);
        }
        saveErrors(request, errors);

        return new ActionForward(mapping.getInput());
      }

      // Guardar la entidad
      entityapp.store();

      // Si todo ha sido correcto se hace commit de la transacción
      bCommit = true;
    } catch (ISPACException e) {

      if (entityapp != null) {

        // Establecer la aplicación para acceder a los valores extra en
        // el formulario
        defaultForm.setValuesExtra(entityapp);

        // Página jsp asociada a la presentación de la entidad
        request.setAttribute("application", entityapp.getURL());
        request.setAttribute("EntityId", Integer.toString(entityId));
        request.setAttribute("KeyId", Integer.toString(keyId));

        throw new ISPACInfo(e.getMessage());
      } else {
        // Suele producirse error en las secuencias al estar mal
        // inicializadas
        // provocando una duplicación de keys
        throw e;
      }
    } finally {
      cct.endTX(bCommit);
    }

    if (condicion == ISPACEntities.ENTITY_NULLREGKEYID) {
      return getActionForwardShow(String.valueOf(entityId), String.valueOf(keyId));
    }

    return updateWeekEnd(mapping, defaultForm, request, response, session);

    //		ActionForward forward = mapping.findForward("ShowEntity" + entityId);
    //		if (forward == null) {
    //
    //			forward = mapping.findForward("reloadShowEntity" + entityId);
    //			if (forward == null) {
    //				forward = mapping.findForward("reload");
    //			}
    //
    //			String redirected = forward.getPath() + "?entityId=" + entityId + "&regId=" + keyId;
    //			if (request.getQueryString() != null) {
    //				redirected += "&" + request.getQueryString();
    //			}
    //			forward = new ActionForward(forward.getName(), redirected, true);
    //		}
    //
    //		return forward;
  }
  public ActionForward executeAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response,
      SessionAPI session)
      throws Exception {

    // Comprobar si el usuario tiene asignadas las funciones adecuadas
    FunctionHelper.checkFunctions(
        request,
        session.getClientContext(),
        new int[] {ISecurityAPI.FUNC_INV_DOCTYPES_EDIT, ISecurityAPI.FUNC_INV_TEMPLATES_EDIT});

    IInvesflowAPI invesFlowAPI = session.getAPI();
    ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI();
    ITemplateAPI templateAPI = invesFlowAPI.getTemplateAPI();

    // Formulario asociado a la acción
    UploadForm defaultForm = (UploadForm) form;

    int keyId = Integer.parseInt(defaultForm.getKey());
    int entityId = Integer.parseInt(defaultForm.getEntity());
    String name = defaultForm.getProperty("NOMBRE");
    String code = defaultForm.getProperty("COD_PLANT");
    CTTemplate template = null;

    try {

      if (keyId == ISPACEntities.ENTITY_NULLREGKEYID) {

        int type = Integer.parseInt(defaultForm.getProperty("ID_TPDOC"));
        String expresion = defaultForm.getProperty("EXPRESION");
        FormFile fichero = defaultForm.getUploadFile();
        EntityApp entityapp = catalogAPI.getCTDefaultEntityApp(entityId, getRealPath(""));

        // Comprobar si existe otra plantilla con el mismo nombre
        IItemCollection itemcol =
            catalogAPI.queryCTEntities(
                ICatalogAPI.ENTITY_CT_TEMPLATE,
                " WHERE NOMBRE = '" + DBUtil.replaceQuotes(name) + "'");
        if (itemcol.next() && !isGeneric(templateAPI, itemcol)) {
          ActionMessages errors = new ActionMessages();
          errors.add(
              "property(NOMBRE)",
              new ActionMessage("error.template.nameDuplicated", new String[] {name}));
          saveAppErrors(request, errors);

          return new ActionForward(mapping.getInput());
        }

        // Comprobar si existe otra plantilla con el mismo código
        if (StringUtils.isNotBlank(code)) {
          itemcol =
              catalogAPI.queryCTEntities(
                  ICatalogAPI.ENTITY_CT_TEMPLATE,
                  " WHERE COD_PLANT = '" + DBUtil.replaceQuotes(code) + "'");
          if (itemcol.next()) {
            ActionMessages errors = new ActionMessages();
            errors.add(
                "property(COD_PLANT)",
                new ActionMessage("error.template.codeDuplicated", new String[] {code}));
            saveAppErrors(request, errors);

            return new ActionForward(mapping.getInput());
          }
        }

        if (!entityapp.validate()) {

          ActionMessages errors = new ActionMessages();
          List errorList = entityapp.getErrors();
          Iterator iteError = errorList.iterator();
          while (iteError.hasNext()) {

            ValidationError validError = (ValidationError) iteError.next();
            ActionMessage error = new ActionMessage(validError.getErrorKey(), validError.getArgs());
            errors.add(ActionMessages.GLOBAL_MESSAGE, error);
          }
          saveAppErrors(request, errors);

          return new ActionForward(mapping.getInput());
        }

        if (fichero.getFileName().equals("")) {
          template = templateAPI.newTemplate(type, name, code, 0, expresion, null);
        } else {
          if (fichero.getFileSize() > 0) {

            // Comprobar si el tipo MIME de la plantilla está soportado
            String mimeType = MimetypeMapping.getFileMimeType(fichero.getFileName());
            // Se comprueba si esta habilitado el uso de plantillas ODT
            if (StringUtils.equals(mimeType, "application/vnd.oasis.opendocument.text")
                && !ConfigurationMgr.getVarGlobalBoolean(
                    session.getClientContext(), ConfigurationMgr.USE_ODT_TEMPLATES, false)) {
              throw new ISPACInfo(
                  getResources(request).getMessage("exception.template.odt.disabled"));
            }

            if (templateAPI.isMimeTypeSupported(mimeType)) {
              template =
                  templateAPI.newTemplate(
                      type, name, code, 0, expresion, fichero.getInputStream(), mimeType);
            } else {
              throw new ISPACInfo(
                  getResources(request).getMessage("exception.template.document.invalidFile"));
            }
          } else {
            throw new ISPACInfo("exception.uploadfile.empty");
          }
        }
      } else {
        EntityApp entityapp = catalogAPI.getCTDefaultEntityApp(entityId, getRealPath(""));

        // Comprobar si existe otra plantilla con el mismo nombre
        IItemCollection itemcol =
            catalogAPI.queryCTEntities(
                ICatalogAPI.ENTITY_CT_TEMPLATE,
                " WHERE NOMBRE = '" + DBUtil.replaceQuotes(name) + "' AND ID != " + keyId);
        if (itemcol.next() && !isGeneric(templateAPI, itemcol)) {
          ActionMessages errors = new ActionMessages();
          errors.add(
              "property(NOMBRE)",
              new ActionMessage("error.template.nameDuplicated", new String[] {name}));
          saveAppErrors(request, errors);

          return new ActionForward(mapping.getInput());
        }

        // Comprobar si existe otra plantilla con el mismo código
        if (StringUtils.isNotBlank(code)) {
          itemcol =
              catalogAPI.queryCTEntities(
                  ICatalogAPI.ENTITY_CT_TEMPLATE,
                  " WHERE COD_PLANT = '" + DBUtil.replaceQuotes(code) + "' AND ID != " + keyId);
          if (itemcol.next()) {
            ActionMessages errors = new ActionMessages();
            errors.add(
                "property(COD_PLANT)",
                new ActionMessage("error.template.codeDuplicated", new String[] {code}));
            saveAppErrors(request, errors);

            return new ActionForward(mapping.getInput());
          }
        }

        defaultForm.processEntityApp(entityapp);
        entityapp.getItem().set("FECHA", new Date());
        entityapp.store();
      }

    } catch (Exception e) {
      ActionForward action = mapping.findForward("success");
      String url =
          action.getPath()
              + "?entity="
              + entityId
              + "&type="
              + defaultForm.getProperty("ID_TPDOC")
              + "&key="
              + keyId;

      request.getSession().setAttribute(BaseAction.LAST_URL_SESSION_KEY, url);

      if (e instanceof ISPACInfo) {
        throw e;
      } else {
        throw new ISPACInfo(e.getMessage());
      }
    }

    if (template != null) {
      keyId = template.getInt("TEMPLATE:ID");
    }

    ActionForward action = mapping.findForward("success");
    String redirected =
        action.getPath()
            + "?entity="
            + entityId
            + "&type="
            + defaultForm.getProperty("ID_TPDOC")
            + "&key="
            + keyId;
    return new ActionForward(action.getName(), redirected, true);
  }
  public ActionForward createCopyCalendar(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response,
      SessionAPI session)
      throws Exception {

    // Comprobar si el usuario tiene asignadas las funciones adecuadas
    FunctionHelper.checkFunctions(
        request, session.getClientContext(), new int[] {ISecurityAPI.FUNC_COMP_CALENDARS_EDIT});

    ClientContext cct = session.getClientContext();
    IInvesflowAPI invesFlowAPI = session.getAPI();
    ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI();

    // Formulario asociado a la acción
    CalendarForm defaultForm = (CalendarForm) form;

    String entityId = request.getParameter("entityId");
    String keyId = request.getParameter("regId");
    String name = defaultForm.getProperty("NEW_CALENDAR_NAME");
    IItemCollection calendar = null;
    IItem icalendar = null;
    IItem newCalendar = null;

    // Ejecución en un contexto transaccional
    boolean bCommit = false;

    try {
      // Abrir transacción
      cct.beginTX();

      List errorList = validate(name, session);

      if (!errorList.isEmpty()) {

        ActionMessages errors = new ActionMessages();
        Iterator iteError = errorList.iterator();
        while (iteError.hasNext()) {
          ValidationError validError = (ValidationError) iteError.next();
          ActionMessage error = new ActionMessage(validError.getErrorKey(), validError.getArgs());
          errors.add("property(NEW_CALENDAR_NAME)", error);
        }
        saveErrors(request, errors);

        return mapping.findForward("validate");
      }

      calendar =
          (IItemCollection)
              catalogAPI.queryCTEntities(ICatalogAPI.ENTITY_SPAC_CALENDARIOS, "where ID=" + keyId);
      icalendar = calendar.value();
      newCalendar = catalogAPI.createCTEntity(ICatalogAPI.ENTITY_SPAC_CALENDARIOS);
      newCalendar.set("NOMBRE", name);
      newCalendar.set("CALENDARIO", icalendar.get("CALENDARIO"));
      newCalendar.store(cct);

      // Si todo ha sido correcto se hace commit de la transacción
      bCommit = true;
    } catch (ISPACException e) {

      throw new ISPACInfo(e.getMessage());
    } finally {
      cct.endTX(bCommit);
    }

    request.setAttribute("target", "top");
    request.setAttribute(
        "url",
        "?method=show&entityId=" + entityId + "&regId=" + newCalendar.getKeyInteger().toString());

    return mapping.findForward("loadOnTarget");
  }