Example #1
0
  /**
   * Obtener el contenido del documento que tenga asignado el CSV recibido.
   *
   * @param context Contexto de tramitación.
   * @param csv CSV del documento
   * @return Contenido del documento.
   * @throws ISPACException Si se produce algún error.
   */
  public static byte[] getContenidoDocumento(IClientContext context, String csv)
      throws ISPACException {

    // Contenido del documento
    byte[] content = null;

    // Consulta
    String sqlQuery = "WHERE COD_COTEJO = '" + DBUtil.replaceQuotes(csv) + "'";
    IItemCollection documents =
        context.getAPI().getEntitiesAPI().queryEntities(SpacEntities.SPAC_DT_DOCUMENTOS, sqlQuery);
    if (documents.next()) {

      IItem document = documents.value();

      // Obtener el identificador del documento en el repositorio
      String guid = document.getString("INFOPAG_RDE");
      if (StringUtils.isBlank(guid)) {
        guid = document.getString("INFOPAG");
      }

      // Obtener el contenido del documento
      content =
          ieci.tdw.ispac.services.helpers.DocumentsHelper.getContenidoDocumento(context, guid);
    }

    return content;
  }
Example #2
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;
    }
  }
Example #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;
  }
Example #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);
    }
  }
Example #5
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();
  }
Example #6
0
  public boolean isSupervised(IResponsible responsible, String sUID, String type)
      throws ISPACException {
    // Supervisados del usuario, del departamento y de los grupos a los que pertenece el usuario
    IItemCollection collection = getAllSuperviseds(responsible, type);
    Iterator iterator = collection.iterator();
    while (iterator.hasNext()) {
      IItem supervised = (IItem) iterator.next();
      Responsible respSupervised = getResp(supervised.getString("UID_SUPERVISADO"));

      if (respSupervised.isInResponsibleList(sUID)) return true;
    }

    return false;
  }
Example #7
0
  /**
   * Obtener los recursos de una entidad, las etiquetas de los campos en el idioma establecido.
   *
   * @param entityId Identificador de la entidad.
   * @param entityName Nombre de la entidad.
   * @param language Idioma.
   * @throws ISPACException Si se produce algún error.
   */
  public void getEntityResources(int entityId, String entityName, String language)
      throws ISPACException {

    IEntitiesAPI entitiesAPI = mContext.getAPI().getEntitiesAPI();

    // Obtener todos los recursos de la entidad para el idioma establecido
    IItemCollection collection = entitiesAPI.getEntityResources(entityId, language);
    while (collection.next()) {

      // Establecer las etiquetas
      IItem item = collection.value();
      setLabel(entityName + ":" + item.getString("CLAVE"), item.getString("VALOR"));
    }
  }
Example #8
0
  public IItem getStage(String numExp) throws ISPACException {

    String resp = getRespString();
    DbCnt cnt = context.getConnection();
    try {
      IItemCollection fasesDelExpediente = WLStageDAO.getStage(cnt, resp, numExp).disconnect();
      for (Iterator itFases = fasesDelExpediente.iterator(); itFases.hasNext(); ) {
        IItem fase = (IItem) itFases.next();
        return fase;
      }
      return null;
    } catch (ISPACException ie) {
      throw new ISPACException("Error en WLWorklist:getStage(" + numExp + ")", ie);
    } finally {
      context.releaseConnection(cnt);
    }
  }
Example #9
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);
    }
  }
Example #10
0
 public String getDeadlineXML(DbCnt cnt) throws ISPACException {
   // obtener el id del proceso
   int idProcedure = getIdProcedure();
   CollectionDAO collDAO =
       PPlazoDAO.getDeadline(cnt, PRelPlazoDAO.DEADLINE_OBJ_PROCEDURE, idProcedure);
   // con el id del proceso obtener el plazo
   if (collDAO != null) {
     IItemCollection coll = collDAO.disconnect();
     if (coll != null) {
       List collList = coll.toList();
       for (Iterator iter = collList.iterator(); iter.hasNext(); ) {
         IItem element = (IItem) iter.next();
         String plazo = element.getString("PLAZO");
         return plazo;
       }
     }
   }
   return null;
 }
  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;
  }
Example #12
0
  private Map getUidsResponsible(IResponsible res) throws ISPACException {
    Map supervisorsUID = new HashMap();

    // Responsable
    supervisorsUID.put(res.getUID(), null);
    // Departamento al que pertenece
    IResponsible dept = res.getRespOrgUnit();
    if (dept != null) {
      supervisorsUID.put(dept.getUID(), null);
    }

    // Grupos a los que pertenece el responsable
    IItemCollection groups = res.getUserRespGroups();
    while (groups.next()) {

      IResponsible group = (IResponsible) groups.value();
      supervisorsUID.put(group.getUID(), null);
    }
    return supervisorsUID;
  }
  public boolean validate(IRuleContext rctx) throws ISPACRuleException {
    try {
      String numexp = rctx.getNumExp();
      IEntitiesAPI entitiesAPI = rctx.getClientContext().getAPI().getEntitiesAPI();
      IItemCollection itemcol = entitiesAPI.getEntities(SecretariaConstants.ENTITY_DECRETO, numexp);
      if (itemcol.next()) {
        IItem decreto = itemcol.value();
        if (StringUtils.isNotBlank(
            decreto.getString(SecretariaConstants.FIELD_DECRETO_NUM_DECRETO))) {
          if (logger.isDebugEnabled()) {
            logger.debug(
                "No se puede eliminar el expediente de decretos: "
                    + numexp
                    + " porque ya tiene número de decreto generado");
          }
          // Si hay que hacer mas comprobación de operaciones permitidas o no en base al num decreto
          // habri que especificar
          // el mensaje en las reglas que hereden de checknumdecretoempty
          rctx.setInfoMessage(
              SecretariaResourcesHelper.getMessage(
                  rctx.getClientContext().getLocale(), "aviso.not.allowed.delete.exp.decreto"));

          return false;
        }
      } else {
        // Si no hay registro no hay núm decreto generado
        if (logger.isDebugEnabled()) {
          logger.debug(
              "Se está intentando eliminar el expediente de decretos:"
                  + numexp
                  + " que no tiene ningún dato en la entidad decretos");
        }
      }

    } catch (ISPACException e) {
      logger.error("Error en la regla " + getClass().getName(), e);
      throw new ISPACRuleException(e);
    }
    return true;
  }
Example #14
0
  public IProcess getProcess(String numExp) throws ISPACException {
    DbCnt cnt = null;
    try {
      cnt = mcontext.getConnection();
      IItemCollection itemcol = TXProcesoDAO.getProcess(cnt, numExp, mcontext);
      if (!itemcol.next())
        //				throw new ISPACNullObject(
        //						"No se ha encontrado el proceso con número de expediente ["
        //								+ numExp + "]");

        throw new ISPACNullObject("exception.expedients.unknown", new Object[] {numExp});

      return (IProcess) itemcol.value();
    } catch (ISPACException e) {
      if (e instanceof ISPACNullObject) {
        throw new ISPACInfo(e.getMessage(), e.getArgs(), false);
      }
      throw new ISPACException("Error en InvesflowAPI:getProcess(" + numExp + ")", e);
    } finally {
      mcontext.releaseConnection(cnt);
    }
  }
Example #15
0
  private void addRespListFromEntryUID(
      Collection respList, IItemCollection collection, String campo) throws ISPACException {

    Iterator iterator = collection.iterator();
    while (iterator.hasNext()) {
      IItem item = (IItem) iterator.next();
      List respListUser = getRespListFromEntryUID(item.getString(campo));
      int i = 0;
      for (i = 0; i < respListUser.size(); i++) {
        if (!respList.contains(respListUser.get(i))) {
          respList.add(respListUser.get(i));
        }
      }
    }
  }
Example #16
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_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);
  }
Example #17
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 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");
  }