Beispiel #1
0
  /**
   * Valida la información del formulario.
   *
   * @throws ISPACException si ocurre algún error.
   */
  public boolean validate() throws ISPACException {

    boolean ret = super.validate();

    if (ret) {

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

      // Bloqueo de la tabla
      catalogAPI.setCTEntitiesForUpdate(ICatalogAPI.ENTITY_CT_STAGE, "");

      // Nombre único de fase
      String nombre = getString("NOMBRE");
      IItemCollection itemcol =
          catalogAPI.queryCTEntities(
              ICatalogAPI.ENTITY_CT_STAGE,
              " WHERE NOMBRE = '"
                  + DBUtil.replaceQuotes(nombre)
                  + "' AND ID != "
                  + getString("ID"));
      if (itemcol.next()) {

        addError(
            new ValidationError(
                "property(NOMBRE)", "error.stage.nameDuplicated", new String[] {nombre}));
        return false;
      }

      return true;
    } else {
      return false;
    }
  }
Beispiel #2
0
  public void store() throws ISPACException {

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

    if (getString("ORDEN") == null) {

      // Bloqueo de las fases para obtener el último orden
      // IItemCollection itemcol = catalogAPI.queryCTEntitiesForUpdate(ICatalogAPI.ENTITY_CT_STAGE,
      // " ORDER BY ORDEN DESC ");
      IItemCollection itemcol =
          catalogAPI.queryCTEntities(ICatalogAPI.ENTITY_CT_STAGE, " ORDER BY ORDEN DESC ");

      int nextOrden = 1;
      if (itemcol != null) {

        for (Iterator iter = itemcol.iterator(); iter.hasNext(); ) {

          IItem element = (IItem) iter.next();
          String orden = element.getString("ORDEN");
          if (orden != null) {

            nextOrden = Integer.parseInt(element.getString("ORDEN")) + 1;
            break;
          }
        }
      }

      setProperty("ORDEN", new Integer(nextOrden));
    }

    super.store();
  }
Beispiel #3
0
  public String getRespStringSubProceso(int idStagePCD, int id_pcd) throws ISPACException {
    String responsibles = "";
    try {
      IInvesflowAPI invesFlowApi = context.getAPI();
      int idPcd = id_pcd;
      ISecurityAPI securityAPI = invesFlowApi.getSecurityAPI();
      responsibles = getRespString();

      // Comprobar si el usuario es SUPERVISOR
      if (!Responsible.SUPERVISOR.equalsIgnoreCase(responsibles)) {

        if (idStagePCD != 0) {
          IItem stage = invesFlowApi.getProcedureStage(idStagePCD);
          idPcd = stage.getInt("ID_PCD");
        }

        IItemCollection itemcol =
            securityAPI.getPermission(ISecurityAPI.PERMISSION_TPOBJ_PROCEDURE, idPcd, null);
        while (itemcol.next()) {
          responsibles += " , '" + itemcol.value().getString("ID_RESP") + "'";
        }
      }

    } catch (ISPACException ie) {
      logger.error("Error en WLWorklist:getRespStringSubProceso(" + idStagePCD + ")", ie);
      throw new ISPACException(
          "Error en WLWorklist:getRespStringSubProceso(" + idStagePCD + ")", ie);
    }
    return responsibles;
  }
Beispiel #4
0
  public IItemCollection getStages(int idProcedure, String resp) throws ISPACException {
    // Comprobamos si es un subprocesos

    DbCnt cnt = context.getConnection();
    List id_pcd_padres = null;
    try {
      IInvesflowAPI invesFlowAPI = context.getAPI();
      IProcedure iProcedure = invesFlowAPI.getProcedure(idProcedure);

      if (iProcedure.getInt("TIPO") == IPcdElement.TYPE_SUBPROCEDURE) {
        IItemCollection itemcol =
            invesFlowAPI
                .getCatalogAPI()
                .queryCTEntities(
                    ICatalogAPI.ENTITY_P_TASK,
                    "where id_cttramite in (select id from spac_ct_tramites where id_subproceso="
                        + idProcedure
                        + ")");
        // Obtenemos la lista de padres
        id_pcd_padres = new ArrayList();
        while (itemcol.next()) {

          id_pcd_padres.add(((IItem) itemcol.value()).get("ID_PCD"));
        }
      }
      return WLStageDAO.getStages(cnt, resp, idProcedure, id_pcd_padres).disconnect();
    } catch (ISPACException ie) {
      throw new ISPACException("Error en WLWorklist:getStages(" + idProcedure + ")", ie);
    } finally {
      context.releaseConnection(cnt);
    }
  }
Beispiel #5
0
  /**
   * Inicializa los valores del formulario.
   *
   * @throws ISPACException si ocurre algún error.
   */
  public void initiate() throws ISPACException {

    // Obtenermos el procedimiento asociado
    int subPcdId = getItem().getInt("ID_SUBPROCESO");
    if (subPcdId > 0) {
      IItem item = mContext.getAPI().getProcedure(subPcdId);
      ((CompositeItem) mitem).addItem(item, "SPAC_P_PROCEDIMIENTOS:");
    }

    super.initiate();

    if (getString("ID") == null) {
      setProperty("AUTOR", mContext.getUser().getName());
      setProperty("FCREACION", DateUtil.getToday());
    }
    if (getItem().get("ID") != null) {
      // Comprobar si tiene tipos de documentos asociados

      IInvesflowAPI invesFlowAPI = mContext.getAPI();
      ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI();
      if (catalogAPI.countTaskTpDoc(getItem().get("ID").toString()) > 0) {
        setProperty("EXISTE_TIPOS_DOCS_ASOCIADOS", "1");
      } else {
        setProperty("EXISTE_TIPOS_DOCS_ASOCIADOS", "");
      }
    } else {
      setProperty("EXISTE_TIPOS_DOCS_ASOCIADOS", "");
    }
  }
  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_READ, ISecurityAPI.FUNC_INV_DOCTYPES_EDIT});

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

    String scttaskId = request.getParameter("cttaskId");
    String filtro = " WHERE CTTRTD.ID_TPDOC =CTTPDOC.ID  AND CTTRTD.ID_TRAMITE = " + scttaskId;
    HashMap tablemap = new HashMap();
    tablemap.put("CTTPDOC", new Integer(ICatalogAPI.ENTITY_CT_TYPEDOC));
    tablemap.put("CTTRTD", new Integer(ICatalogAPI.ENTITY_CT_TASKTYPEDOC));

    IItemCollection itemcol = catalogAPI.queryCTEntities(tablemap, filtro);
    List cttasklist = CollectionBean.getBeanList(itemcol);

    int cttaskId = Integer.parseInt(scttaskId);

    IItem cttask = catalogAPI.getCTEntity(ICatalogAPI.ENTITY_CT_TASK, cttaskId);
    ItemBean cttaskbean = new ItemBean(cttask);
    request.setAttribute("CTTask", cttaskbean);

    CacheFormatterFactory factory = CacheFormatterFactory.getInstance();
    BeanFormatter formatter = null;

    // Establece el formateador de las fases del catálogo
    if (FunctionHelper.userHasFunction(
        request, session.getClientContext(), ISecurityAPI.FUNC_INV_TASKS_EDIT)) {
      formatter = factory.getFormatter(getISPACPath("/formatters/cttasktpdocsformatter.xml"));
    } else {
      formatter =
          factory.getFormatter(getISPACPath("/formatters/cttasktpdocsreadonlyformatter.xml"));
    }

    request.setAttribute("Formatter", formatter);
    request.setAttribute("ItemList", cttasklist);

    // Identificador para los enlaces del menu.
    request.setAttribute("KeyId", scttaskId);

    return mapping.findForward("success");
  }
Beispiel #7
0
  /* (non-Javadoc)
   * @see ieci.tdw.ispac.api.IWorklistAPI#findActiveStages(int)
   */
  public IItemCollection findActiveStages(int nIdProcess) throws ISPACException {
    IInvesflowAPI invesFlowAPI = context.getAPI();
    IProcess iprocess = invesFlowAPI.getProcess(nIdProcess);
    String resp = "";

    if (iprocess.getInt("TIPO") == IPcdElement.TYPE_SUBPROCEDURE) {
      resp = getRespStringSubProceso(0, context.getStateContext().getPcdId());
    } else {
      resp = getRespString();
    }

    return findActiveStages(nIdProcess, resp);
  }
Beispiel #8
0
  public IItemCollection getActivities(int subProcedureId, String resp) throws ISPACException {

    DbCnt cnt = context.getConnection();
    List<Integer> id_pcd_padres = new ArrayList<Integer>();
    IItemCollection activities = null;

    try {

      IInvesflowAPI invesFlowAPI = context.getAPI();
      IProcedure iProcedure = invesFlowAPI.getProcedure(subProcedureId);

      if (iProcedure.getInt("TIPO") == IPcdElement.TYPE_SUBPROCEDURE) {

        // Obtenemos la lista de padres
        IItemCollection itemcol =
            invesFlowAPI
                .getCatalogAPI()
                .queryCTEntities(
                    ICatalogAPI.ENTITY_P_TASK,
                    "where id_cttramite in (select id from spac_ct_tramites where id_subproceso="
                        + subProcedureId
                        + ")");
        while (itemcol.next()) {
          id_pcd_padres.add(itemcol.value().getInt("ID_PCD"));
        }

        activities =
            WLActivityDAO.getActivities(cnt, resp, subProcedureId, id_pcd_padres).disconnect();
      }

      return activities;

    } catch (ISPACException ie) {
      logger.error(
          "Error al obtener las actividades del subprocedimiento ["
              + subProcedureId
              + "] y resp ["
              + resp
              + "]",
          ie);
      throw new ISPACException(
          "Error en WorklistAPI:getActivities(" + subProcedureId + ", " + resp + ")", ie);
    } finally {
      context.releaseConnection(cnt);
    }
  }
  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_PUB_RULES_EDIT});

    IInvesflowAPI invesFlowAPI = session.getAPI();
    IPublisherAPI publisherAPI = invesFlowAPI.getPublisherAPI();

    // Formulario asociado a la regla
    EntityForm defaultForm = (EntityForm) form;

    int keyId = Integer.parseInt(defaultForm.getKey());

    // Información de la regla
    IItem rule = publisherAPI.getRule(keyId);

    // Eliminar la regla
    publisherAPI.deleteRule(keyId);

    String pcdId = request.getParameter("pcdId");
    if (!StringUtils.isEmpty(pcdId)) {

      return new ActionForward(
          new StringBuffer()
              .append("/showPubRulesList.do?pcdId=")
              .append(pcdId)
              .append("&stageId=")
              .append(rule.getString("ID_FASE"))
              .append("&taskId=")
              .append(rule.getString("ID_TRAMITE"))
              .append("&typeDoc=")
              .append(rule.getString("TIPO_DOC"))
              .toString(),
          true);
    } else {
      return new ActionForward("/showPubRulesGroupList.do", true);
    }
  }
  public List validate(String name, SessionAPI session) throws ISPACException {

    ArrayList mErrorList = new ArrayList();

    ValidationError error = null;

    if (StringUtils.isBlank(name)) {

      error =
          new ValidationError(
              "property(NEW_CALENDAR_NAME)",
              "errors.required",
              new String[] {
                Messages.getString(
                    session.getClientContext().getAppLanguage(), "form.calendar.propertyLabel.name")
              });
      mErrorList.add(error);
    } else {
      IInvesflowAPI invesFlowAPI = session.getAPI();
      ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI();

      // Bloqueo
      IItemCollection itemcol = catalogAPI.queryCTEntities(ICatalogAPI.ENTITY_SPAC_CALENDARIOS, "");
      // Nombre único de calendario

      itemcol =
          (IItemCollection)
              catalogAPI.queryCTEntities(
                  ICatalogAPI.ENTITY_SPAC_CALENDARIOS,
                  " WHERE NOMBRE = '" + DBUtil.replaceQuotes(name) + "'");
      if (itemcol.next()) {

        error =
            new ValidationError(
                "property(NEW_CALENDAR_NAME)",
                "error.calendar.nameDuplicated",
                new String[] {name});
        mErrorList.add(error);
      }
    }
    return mErrorList;
  }
  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, cct, new int[] {ISecurityAPI.FUNC_INV_PROCEDURES_EDIT});

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

    int itemId = Integer.parseInt(request.getParameter("idfstd"));

    IItem item = catalogAPI.getCTEntity(ICatalogAPI.ENTITY_P_FSTD, itemId);
    item.delete(cct);

    TreeView tree =
        (TreeView)
            request
                .getSession()
                .getAttribute(ManageVistaCuadroProcedimientoAction.CUADRO_PROCEDIMIENTO);
    if (tree != null) {
      TreeNode actualnode = tree.getSelectedNode().getParent();
      tree.setSelectedNode(actualnode);
      actualnode.refresh();
    }

    request.setAttribute("Refresh", "true");

    return mapping.findForward("success");
  }
  // 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");
  }
  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 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");
  }
Beispiel #15
0
  public boolean isInResponsibleList(String sUID, int supervisionType, IItem item)
      throws ISPACException {

    DbCnt cnt = context.getConnection();
    List listSupervisados = new ArrayList();
    List listSustituidos = new ArrayList();
    int i = 0;

    try {
      // Comprobar el UID en la cadena de responsabilidad directa del usuario
      Responsible user = context.getUser();
      if (user.isInResponsibleList(sUID)) {
        return true;
      }

      if (mWorkMode == IWorklistAPI.SUPERVISOR) {

        SecurityMgr securityMgr = new SecurityMgr(cnt);

        // Comprobar si el usuario es Supervisor en Modo Modificación
        if (securityMgr.isFunction(user.getUID(), ISecurityAPI.FUNC_TOTALSUPERVISOR)) {
          return true;
        }

        // Comprobar si el usuario es Supervisor en Modo Consulta, si aplica
        if ((supervisionType != ISecurityAPI.SUPERV_TOTALMODE)
            && securityMgr.isFunction(user.getUID(), ISecurityAPI.FUNC_MONITORINGSUPERVISOR)) {
          return true;
        }

        // Comprobar las responsabilidades referentes a las supervisiones
        IItemCollection collection = null;
        if (supervisionType == ISecurityAPI.SUPERV_TOTALMODE) {
          collection = securityMgr.getAllSuperviseds(user, ISecurityAPI.SUPERV_TOTALMODE);
        } else {
          collection = securityMgr.getAllSuperviseds(user);
        }

        while (collection.next()) {
          IItem supervisor = (IItem) collection.value();
          listSupervisados = getRespListFromEntryUID(supervisor.getString("UID_SUPERVISADO"));
          if (listSupervisados.contains(sUID)) {
            return true;
          }
        }

        // Comprobar las responsabilidades referentes a las sustituciones
        collection = securityMgr.getAllSubstitutes(user);
        while (collection.next()) {

          IItem substitute = (IItem) collection.value();
          listSustituidos = getRespListFromEntryUID(substitute.getString("UID_SUSTITUIDO"));
          if (listSustituidos.contains(sUID)) return true;
        }

        // Comprobar si tenemos permisos a nivel de catálogo
        if (item != null) {
          if (logger.isDebugEnabled()) {
            logger.debug(
                "El responsable "
                    + sUID
                    + "No tiene permisos genéricos, "
                    + "vamos a comprobar si tiene permisos a nivel"
                    + "de catálogo (permisos sobre un procedimiento)");
          }
          ISecurityAPI securityAPI = context.getAPI().getSecurityAPI();
          int[] permisos = new int[1];
          permisos[0] = ISecurityAPI.PERMISSION_TYPE_EDIT;

          // Componemos la cadena de responsabilidad separada por comas
          List resp = user.getRespList();
          String cadenaResp = "";
          // Al menos esta el propio usuario
          cadenaResp = "'" + DBUtil.replaceQuotes(resp.get(0).toString()) + "'";
          for (i = 1; i < resp.size(); i++) {
            cadenaResp += " , '" + DBUtil.replaceQuotes(resp.get(i).toString()) + "'";
          }

          for (i = 0; i < listSupervisados.size(); i++) {
            cadenaResp += " , '" + DBUtil.replaceQuotes(listSupervisados.get(i).toString()) + "'";
          }
          for (i = 0; i < listSustituidos.size(); i++) {
            cadenaResp += " , '" + DBUtil.replaceQuotes(listSustituidos.get(i).toString()) + "'";
          }
          // Item puede ser IProcess ,  IStage , ITask
          if (item instanceof ITask) {
            return securityAPI.existPermissions((ITask) item, cadenaResp, permisos);

          } else if (item instanceof IStage) {

            if (IPcdElement.TYPE_SUBPROCEDURE == item.getInt("TIPO")) {
              IInvesflowAPI api = context.getAPI();
              IEntitiesAPI entitiesAPI = api.getEntitiesAPI();
              String sql = "WHERE TIPO=" + IPcdElement.TYPE_PROCEDURE + " AND";
              sql += " NUMEXP = '" + DBUtil.replaceQuotes(item.getString("NUMEXP")) + "'";
              IItemCollection col = entitiesAPI.queryEntities(SpacEntities.SPAC_FASES, sql);
              if (col.next()) {
                IItem fasePadre = col.value();
                int id = fasePadre.getKeyInt();
                IStage stage = api.getStage(id);
                return securityAPI.existPermissions(stage, cadenaResp, permisos);
              }
            }
            return securityAPI.existPermissions((IStage) item, cadenaResp, permisos);
          } else if (item instanceof IProcess) {
            return securityAPI.existPermissions((IProcess) item, cadenaResp, permisos);
          }
        }
      }
    } finally {
      context.releaseConnection(cnt);
    }

    return false;
  }
  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 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;
  }
Beispiel #18
0
  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_PROCEDURES_EDIT});

    int intTpObj = Integer.parseInt(request.getParameter("TpObj"));
    int intIdObj = Integer.parseInt(request.getParameter("IdObj"));

    // Prepara las API's a utilizar
    IInvesflowAPI invesFlowAPI = session.getAPI();
    ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI();

    if (request.getParameter("idRule") != null) {
      catalogAPI.addPRuleEvent(
          intTpObj,
          intIdObj,
          Integer.parseInt(request.getParameter("codEvent")),
          Integer.parseInt(request.getParameter("idRule")));

      ActionForward forward = mapping.findForward("showevents");
      String path = forward.getPath() + "?TpObj=" + intTpObj + "&IdObj=" + intIdObj;
      return new ActionForward(forward.getName(), path, forward.getRedirect());
    }

    request.setAttribute("TpObj", String.valueOf(intTpObj));
    request.setAttribute("IdObj", String.valueOf(intIdObj));

    CacheFormatterFactory factory = CacheFormatterFactory.getInstance();
    String ispacbase = (String) servlet.getServletContext().getAttribute("ispacbase");

    if (request.getParameter("codEvent") != null) {
      request.setAttribute("codEvent", request.getParameter("codEvent"));
      IItemCollection rulecol = catalogAPI.getCTRules();
      List rulelist = CollectionBean.getBeanList(rulecol);

      request.setAttribute("RulesList", rulelist);

      BeanFormatter formatter =
          factory.getFormatter(getISPACPath("/formatters/events/ruleslistformatter.xml"));

      request.setAttribute("RulesListFormatter", formatter);
      request.setAttribute(
          "application", StaticContext.rewritePage(ispacbase, "common/events/ruleslist.jsp"));
    } else {
      List eventlist = DescriptionsPEvents.getDescEventsList(intTpObj, intIdObj);
      request.setAttribute("EventsList", eventlist);

      BeanFormatter formatter =
          factory.getFormatter(getISPACPath("/formatters/events/eventslistformatter.xml"));

      request.setAttribute("EventsListFormatter", formatter);
      request.setAttribute(
          "application", StaticContext.rewritePage(ispacbase, "common/events/eventslist.jsp"));
    }

    return mapping.findForward("success");
  }
Beispiel #19
0
  public void run(ClientContext cs, TXTransactionDataContainer dtc, ITXTransaction itx)
      throws ISPACException {

    EventManager eventmgr = new EventManager(cs, mparams);
    TXDAOGen genDAO = new TXDAOGen(cs, eventmgr);

    TXFaseDAO stage = dtc.getStage(mnIdStage);
    int nIdProc = stage.getInt("ID_EXP");
    int nIdPCDStage = stage.getInt("ID_FASE");

    TXProcesoDAO process = dtc.getProcess(nIdProc);
    TXProcedure procedure = TXProcedureMgr.getInstance().getProcedure(cs, process.getIdProcedure());

    PTramiteDAO pcdtask = procedure.getTaskDAO(mnIdTaskPCD);

    if (process.getInt("ESTADO") == TXConstants.STATUS_CLOSED) {
      throw new ISPACInfo(
          "exception.expedients.createTask.statusClosed",
          new String[] {pcdtask.getString("NOMBRE"), process.getString("NUMEXP")});
    } else if (process.getInt("ESTADO") == TXConstants.STATUS_CANCELED) {
      throw new ISPACInfo(
          "exception.expedients.createTask.statusCanceled",
          new String[] {pcdtask.getString("NOMBRE"), process.getString("NUMEXP")});
    } else if (process.getInt("ESTADO") == TXConstants.STATUS_ARCHIVED) {
      throw new ISPACInfo(
          "exception.expedients.createTask.statusArchived",
          new String[] {pcdtask.getString("NOMBRE"), process.getString("NUMEXP")});
    }

    // -----
    // BPM
    // ----
    IBPMAPI bpmAPI = dtc.getBPMAPI();
    IInvesflowAPI invesFlowAPI = cs.getAPI();
    IRespManagerAPI respManagerAPI = invesFlowAPI.getRespManagerAPI();
    // Se calcula el responsable del trámite
    String taskRespId = ResponsibleHelper.calculateTaskResp(eventmgr, pcdtask, stage, process, cs);

    String nombreRespId = ((Responsible) respManagerAPI.getResp(taskRespId)).getName();
    String taskActivityRespId = null;

    // boolean isSubProcess = false;
    boolean isSubProcess = mnIdProcedure != 0;
    int taskType = ITask.SIMPLE_TASK_TYPE;
    String idSubPcdBPM = null;
    // Si el tramite es complejo se calcula el responsable a asignar a la actividad inicial del
    // subproceso
    // if (StringUtils.isNotEmpty(pcdtask.getString("ID_PCD_SUB")) &&
    // !StringUtils.equals(pcdtask.getString("ID_PCD_SUB"), "0")){
    if (isSubProcess) {
      taskType = ITask.COMPLEX_TASK_TYPE;

      TXProcedure subProcess = TXProcedureMgr.getInstance().getProcedure(cs, mnIdProcedure);
      Iterator it = subProcess.getStateTable().getStartStages().iterator();

      if (!it.hasNext())
        throw new ISPACException(
            "No se han encontrado actividades para el subproceso '"
                + pcdtask.getString("ID_PCD_SUB")
                + "'");
      int activityId = ((Integer) it.next()).intValue();
      PFaseDAO pActivity = subProcess.getStageDAO(activityId);
      taskActivityRespId =
          ResponsibleHelper.calculateTaskActivityResp(
              eventmgr, pActivity, pcdtask, process, cs, taskRespId);

      IItem itemSubprocedure = invesFlowAPI.getProcedure(pcdtask.getInt("ID_PCD_SUB"));
      idSubPcdBPM = itemSubprocedure.getString("ID_PCD_BPM");
    }

    // BpmUIDs bpmUIDs = bpmAPI.instanceTask(pcdtask.getString("ID_TRAMITE_BPM"),
    // pcdtask.getString("ID_PCD_SUB"), taskRespId,
    // taskActivityRespId,String.valueOf(stage.getKeyInt()));
    BpmUIDs bpmUIDs =
        bpmAPI.instanceTask(
            pcdtask.getString("ID_TRAMITE_BPM"),
            idSubPcdBPM,
            taskRespId,
            taskActivityRespId,
            stage.getString("ID_FASE_BPM"));

    // Identificador de tramite creado
    String taskUID = bpmUIDs.getTaskUID();
    // Identificador de subproceso instanciado
    String subProcessUID = bpmUIDs.getSubProcessUID();
    // Identificador de actividad creada
    String activityUID = bpmUIDs.getActivityUID();

    TXTramiteDAO task = dtc.newTask();
    genDAO.instance(pcdtask, task, stage, process);

    // Establecemos el UID del tramite instanciado retornado por el BPM
    if (taskUID == null) taskUID = "" + task.getKeyInt();
    task.set("ID_TRAMITE_BPM", taskUID);
    task.set("ID_RESP", taskRespId);
    task.set("RESP", nombreRespId);
    task.set("TIPO", taskType);
    // Si es un tramite complejo (subproceso) habrá que instanciar el subproceso
    if (isSubProcess) {
      int[] ids =
          itx.createSubProcess(
              pcdtask.getInt("ID_PCD_SUB"),
              mnumexp,
              subProcessUID,
              activityUID,
              taskRespId,
              taskActivityRespId);
      task.set("ID_SUBPROCESO", (int) ids[0]);
      mnIdActivity = (int) ids[1];
      //			//Obtenemos la actividad inicia
      //			Iterator it =dtc.getStages();
      //			while (it.hasNext()){
      //				TXFaseDAO _stage = (TXFaseDAO)((Map.Entry)it.next()).getValue();
      //				if (_stage.getInt("ID_EXP") == idSubProcess){
      //					mnIdActivity = _stage.getKeyInt();
      //					break;
      //				}

      eventmgr.getRuleContextBuilder().addContext(RuleProperties.RCTX_SUBPROCESS, "" + ids[0]);
    }

    // Guardar la información del trámite
    task.store(cs);

    dtc.createTaskEntity(task);

    mnIdTask = task.getKeyInt();

    // Insertar el hito
    TXHitoDAO hito =
        dtc.newMilestone(
            process.getKeyInt(), nIdPCDStage, mnIdTaskPCD, TXConstants.MILESTONE_TASK_START);
    hito.set("INFO", composeInfo());

    // Se construye el contexto de ejecución de scripts.
    eventmgr.getRuleContextBuilder().addContext(process);
    eventmgr.getRuleContextBuilder().addContext(task);

    // Ejecutar eventos de sistema de creación de trámite.
    eventmgr.processSystemEvents(EventsDefines.EVENT_OBJ_TASK, EventsDefines.EVENT_EXEC_START);

    // Ejecutar evento al cancelar trámite.
    eventmgr.processEvents(
        EventsDefines.EVENT_OBJ_TASK, mnIdTaskPCD, EventsDefines.EVENT_EXEC_START);
  }
  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");
  }
  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);
  }