public ActionForward updateWeekEnd(
      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});

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

    CalendarForm defaultForm = (CalendarForm) form;

    IItem item = (IItem) request.getSession().getAttribute("CALENDAR");

    String calendarioXML = (String) item.getString("CALENDARIO");

    CalendarDef calendarDef = new CalendarDef(calendarioXML);
    String[] daysSelected = defaultForm.getWeekDaysSelect();

    calendarDef.addWeekEnd(daysSelected);

    item.set("CALENDARIO", calendarDef.getXmlValues());
    item.store(session.getClientContext());

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

    String regId = request.getParameter("regId");
    if (regId == null) {
      regId = defaultForm.getKey();
    }

    return getActionForwardShow(entityId, regId);
  }
  public ActionForward deleteHolyday(
      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});

    CalendarForm defaultForm = (CalendarForm) form;

    IItem item = (IItem) request.getSession().getAttribute("CALENDAR");

    String calendarioXML = (String) item.getString("CALENDARIO");
    CalendarDef calendarDef = new CalendarDef(calendarioXML);
    String[] datesSelected = defaultForm.getMultibox();

    if (datesSelected != null) {
      for (int i = 0; i < datesSelected.length; i++) {
        calendarDef.removeHolyday(datesSelected[i]);
      }

      item.set("CALENDARIO", calendarDef.getXmlValues());
      item.store(session.getClientContext());
    }

    return getActionForwardShowDelete(
        request.getParameter("entityId"),
        request.getParameter("regId"),
        request.getParameter("nombre"),
        request.getParameter("weekDaysSelect"));
    // return getActionForwardShow(request.getParameter("entityId"),request.getParameter("regId"));
  }
  public ActionForward executeAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response,
      SessionAPI session)
      throws Exception {

    ClientContext cct = session.getClientContext();

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

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

    Upload2Form upload2Form = (Upload2Form) form;
    String upload = request.getParameter("upload");

    try {

      if (upload.equals("design")) {

        FormFile formfile = upload2Form.getUploadFile();
        String htmlCode = new String(formfile.getFileData());

        if (!StringUtils.isEmpty(htmlCode)) {

          // Obtener el formulario JSP de la aplicación
          IItem application =
              catalogAPI.getCTEntity(
                  ICatalogAPI.ENTITY_CT_APP, Integer.parseInt(upload2Form.getKey()));
          if (application != null) {

            List entities = new ArrayList();

            // Entidad principal
            entities.add(application.getString("ENT_PRINCIPAL_NOMBRE"));

            // Entidades de composición y de relación múltiple
            String parameters = application.getString("PARAMETROS");
            if (!StringUtils.isEmpty(parameters)) {

              ParametersDef xmlParameters = ParametersDef.parseParametersDef(parameters);
              List compositeEntities = xmlParameters.getCompositeMultipleRelationEntities();
              Iterator it = compositeEntities.iterator();
              while (it.hasNext()) {

                EntityParameterDef entityParameterDef = (EntityParameterDef) it.next();
                entities.add(entityParameterDef.getTable());
              }
            }

            String frm_jsp = application.getString("FRM_JSP");
            String jspCode = HTMLBuilder.updateHTML(htmlCode, frm_jsp, entities);
            if (jspCode != null) {

              application.set("FRM_JSP", jspCode);

              // Incrementar la versión del formulario
              int version = 1;
              String sVersion = application.getString("FRM_VERSION");
              if (!StringUtils.isEmpty(sVersion)) {
                version += Integer.parseInt(sVersion);
              }
              application.set("FRM_VERSION", version);

              application.store(cct);
            }
          }
        } else {
          throw new ISPACInfo("exception.uploadfile.empty");
        }
      } else if (upload.equals("code")) {

        FormFile formfile2 = upload2Form.getUploadFile2();
        String jspCode = new String(formfile2.getFileData());

        if (!StringUtils.isEmpty(jspCode)) {

          // Obtener la aplicación
          IItemCollection itemcol =
              catalogAPI.queryCTEntities(
                  ICatalogAPI.ENTITY_CT_APP, "where ID =" + upload2Form.getKey());
          if (itemcol.next()) {

            IItem application = itemcol.value();
            application.set("FRM_JSP", jspCode);

            // Incrementar la versión del formulario
            int version = 1;
            String sVersion = application.getString("FRM_VERSION");
            if (!StringUtils.isEmpty(sVersion)) {
              version += Integer.parseInt(sVersion);
            }
            application.set("FRM_VERSION", version);

            application.store(cct);
          }
        } else {
          throw new ISPACInfo("exception.uploadfile.empty");
        }
      }
    } catch (IOException e) {
      throw new ISPACInfo("exception.uploadfile.error");
    }

    return mapping.findForward("success");

    /*
    request.setAttribute("refresh", "true");
    return mapping.findForward("success_upload");
    */
  }
  public ActionForward show(
      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_READ, ISecurityAPI.FUNC_COMP_CALENDARS_EDIT});

    CalendarForm defaultForm = (CalendarForm) form;

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

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

    // Indica si se viene de añadir un nuevo dia festivo o no
    Boolean save = new Boolean(request.getParameter("save"));

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

    String strURL = null;
    EntityApp entityapp = catalogAPI.getCTDefaultEntityApp(entityId, keyId, getRealPath(""));

    try {
      if (entityapp == null) throw new ISPACNullObject();
      // Si se debe crear una entrada cuando se guarden los datos del registro,
      // se marca debidamente el campo clave del registro como nulo.
      if (keyId == ISPACEntities.ENTITY_NULLREGKEYID) {
        entityapp.getItem().setKey(ISPACEntities.ENTITY_NULLREGKEYID);
      }
    } catch (ISPACNullObject e) {
      ISPACRewrite ispacPath = new ISPACRewrite(getServlet().getServletContext());
      strURL = ispacPath.rewriteRelativePath("common/missingapp.jsp");
    } catch (ISPACException eie) {
      throw new ISPACInfo(eie.getMessage());
    }

    if (strURL == null) {
      strURL = entityapp.getURL();
    }

    // Visualiza los datos de la entidad
    // Si hay errores no se recargan los datos de la entidad
    // manteniéndose los datos introducidos que generan los errores
    if (((defaultForm.getActions() == null) || (defaultForm.getActions().equals("success")))
        && (request.getAttribute(Globals.ERROR_KEY) == null)) {

      defaultForm.setEntity(Integer.toString(entityId));
      defaultForm.setKey(Integer.toString(keyId));
      defaultForm.setReadonly("false");

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

    if (save.booleanValue()) defaultForm.setProperty("NOMBRE", request.getParameter("nombre"));

    // Lista de festivos y fin de semana
    List holydaysList = null;
    List allDayList = null;

    IItem item = defaultForm.getEntityApp().getItem();
    if (keyId > 0) {
      CalendarDef caldef = new CalendarDef(item.getString("CALENDARIO"));
      // Dias festivos
      holydaysList = caldef.getHolydays();
      // Dias de la semana
      allDayList = caldef.getAllWeekDays();
      // Dias de la semana
      if (save.booleanValue()) {
        String dias = request.getParameter("weekDaysSelect");
        String[] diasSeleccionados = new String[dias.length()];
        if (!dias.equals("")) diasSeleccionados = dias.split(",");
        caldef.addWeekEnd(diasSeleccionados);
      }

      defaultForm.setWeekDaysSelect(caldef.getWeekEndDays());

    } else {
      item.set("CALENDARIO", (new CalendarDef()).getXmlValues());
    }

    request.setAttribute("HOLYDAYS_LIST", holydaysList);
    request.setAttribute("WEEKDAYS_LIST", allDayList);

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

    // Generamos la ruta de navegación hasta la pantalla actual.
    BreadCrumbsContainer bcm = BreadCrumbsManager.getInstance(catalogAPI).getBreadCrumbs(request);
    request.setAttribute("BreadCrumbs", bcm.getList());

    // poner el item en session
    request.getSession().setAttribute("CALENDAR", entityapp.getItem());

    return mapping.findForward("success_show");
  }
  public ActionForward saveholydays(
      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();
    CalendarForm defaultForm = (CalendarForm) form;
    // Validar el formulario
    defaultForm.setEntityAppName("SaveHolydaysCalendar");
    ActionMessages errors = defaultForm.validate(mapping, request);

    String entityId = defaultForm.getEntity();
    String regId = defaultForm.getKey();
    String nombre = request.getParameter("nombre");
    String dias = request.getParameter("weekDaysSelect");

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

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

      if (errors.isEmpty()) {

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

        // Bloqueo
        catalogAPI.queryCTEntities(ICatalogAPI.ENTITY_SPAC_CALENDARIOS, "");

        IItem item = (IItem) request.getSession().getAttribute("CALENDAR");
        // deberia ir abajo
        String calendarioXML = (String) item.getString("CALENDARIO");
        validateHolyday(item, defaultForm.getProperty("HOLYDAY_DATE"), session, errors);

        if (!errors.isEmpty()) {

          saveErrors(request, errors);
          return mapping.findForward("success_holydays");
        }

        CalendarDef calendarDef = new CalendarDef(calendarioXML);
        calendarDef.addHolyday(
            defaultForm.getProperty("HOLYDAY_NAME"), defaultForm.getProperty("HOLYDAY_DATE"));
        item.set("CALENDARIO", calendarDef.getXmlValues());
        item.store(session.getClientContext());

        // Si todo ha sido correcto se hace commit de la transacción
        bCommit = true;

        // Para que vaya a la direccion donde yo quiero
        String url =
            "?method=show&entityId="
                + entityId
                + "&regId="
                + regId
                + "&save=true&nombre="
                + nombre
                + "&weekDaysSelect="
                + dias;

        request.setAttribute("target", "top");
        request.setAttribute("url", url);

        return mapping.findForward("loadOnTarget");
      } else {
        saveErrors(request, errors);
        return getActionForwardHolydays();
      }
    } catch (ISPACException e) {

      throw new ISPACInfo(e.getMessage());
    } finally {
      cct.endTX(bCommit);
    }
  }
  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");
  }
  // Esta función guarda en la base de datos correspondiente los dias seleccionados en la página.
  public ActionForward saveFixedHolidays(
      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();
    CalendarForm defaultForm = (CalendarForm) form;
    String[] selectFixedHolidays = (String[]) defaultForm.getSelectFixedHolidays();
    String year = (String) defaultForm.getProperty("YEAR");

    // Validación
    ActionMessages errors = new ActionMessages();
    defaultForm.setEntityAppName("EditCTCalendar");
    errors = defaultForm.validate(mapping, request);

    if (errors.isEmpty()) {

      String entityId = defaultForm.getEntity();
      String regId = defaultForm.getKey();
      String nombre = request.getParameter("nombre");
      String dias = request.getParameter("weekDaysSelect");

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

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

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

        // Bloquear
        catalogAPI.queryCTEntities(ICatalogAPI.ENTITY_SPAC_CALENDARIOS, "");
        IItem item = (IItem) request.getSession().getAttribute("CALENDAR");

        String calendarioXML = (String) item.getString("CALENDARIO");
        CalendarDef calendarDef = new CalendarDef(calendarioXML);

        for (int i = 0; i < selectFixedHolidays.length; i++) {
          String[] date = selectFixedHolidays[i].split("---");
          ActionMessages errorsFixedHolidays = new ActionMessages();
          validateHolyday(item, date[0] + "/" + year, session, errorsFixedHolidays);

          if (errorsFixedHolidays.isEmpty()) {
            calendarDef.addHolyday(date[1], date[0] + "/" + year);
          }
        }

        item.set("CALENDARIO", calendarDef.getXmlValues());
        item.store(session.getClientContext());

        // Si todo ha sido correcto se hace commit de la transacción
        bCommit = true;

        String url =
            "?method=show&entityId="
                + entityId
                + "&regId="
                + regId
                + "&save=true&nombre="
                + nombre
                + "&weekDaysSelect="
                + dias;

        request.setAttribute("target", "top");
        request.setAttribute("url", url);

        return mapping.findForward("loadOnTarget");
      } catch (ISPACException e) {

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

    saveErrors(request, errors);
    request.setAttribute(DAYS_LIST, request.getAttribute(DAYS_LIST));

    return mapping.findForward("errorYear");
  }