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;
  }
示例#2
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);
  }
  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");
  }