Exemplo n.º 1
0
  /**
   * This code is currently common to all {@link ViewHandlingStrategy} instances.
   *
   * @see ViewHandler#calculateLocale(javax.faces.context.FacesContext)
   */
  public Locale calculateLocale(FacesContext context) {

    Util.notNull("context", context);

    Locale result = null;
    // determine the locales that are acceptable to the client based on the
    // Accept-Language header and the find the best match among the
    // supported locales specified by the client.
    Iterator<Locale> locales = context.getExternalContext().getRequestLocales();
    while (locales.hasNext()) {
      Locale perf = locales.next();
      result = findMatch(context, perf);
      if (result != null) {
        break;
      }
    }
    // no match is found.
    if (result == null) {
      if (context.getApplication().getDefaultLocale() == null) {
        result = Locale.getDefault();
      } else {
        result = context.getApplication().getDefaultLocale();
      }
    }
    return result;
  }
  public void command_removeSelMetric() {
    FacesContext context = FacesContext.getCurrentInstance();
    Object o1 = context.getExternalContext().getRequestParameterMap().get("removeMetricInternalID");
    Object o2 = context.getExternalContext().getRequestParameterMap().get("table");

    if ((o1 != null) && (o2 != null)) {
      String removeMetricID = o1.toString();
      String fromTable = o2.toString();

      List<MetricBean> dataTable = null;
      if (fromTable.equals("table_verygood")) {
        dataTable = this.lVeryGoodMT;
      }
      if (fromTable.equals("table_good")) {
        dataTable = this.lGoodMT;
      }
      if (fromTable.equals("table_bad")) {
        dataTable = this.lBadMT;
      }
      if (fromTable.equals("table_verybad")) {
        dataTable = this.lVeryBadMT;
      }
      // check from which table to remove the data
      MetricBean del = null;
      Iterator<MetricBean> itTableData = dataTable.iterator();
      while (itTableData.hasNext()) {
        MetricBean mb = itTableData.next();
        if (mb.getInternalID().equals(removeMetricID)) {
          del = mb;
        }
      }
      if (del != null) dataTable.remove(del);
    }
  }
Exemplo n.º 3
0
  /**
   * Perform actions that need to happen on the <code>afterPhase</code> event.
   *
   * <p>For after restore-view, if this is a postback, we extract the sequenceId from the request
   * and store it in the request scope.
   *
   * <p>For after render-response, we clear out the flash for the postback, while leaving the
   * current one intact.
   */
  public void afterPhase(PhaseEvent e) {
    FacesContext context = e.getFacesContext();
    ExternalContext extContext = context.getExternalContext();
    Map<String, Object> requestMap = extContext.getRequestMap();
    Object request = extContext.getRequest(), response = extContext.getResponse();
    ELFlash elFlash = ELFlash.getELFlash();

    if (e.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
      expireEntries(context);
    }

    // If this requset is ending normally...
    if (e.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
      // and the user requested we save all request scoped data...
      if (null != elFlash && elFlash.isKeepMessages()) {
        // save it all.
        elFlash.saveAllMessages(context);
      }
    }
    // Otherwise, if this request is ending early...
    else if ((context.getResponseComplete() || context.getRenderResponse())
        && elFlash.isRedirect()) {
      // and the user requested we save all request scoped data...
      if (null != elFlash && elFlash.isKeepMessages()) {
        // save it all.
        addCookie(extContext, elFlash);
        elFlash.saveAllMessages(context);
      }
    }
  }
Exemplo n.º 4
0
  public String processCreateNew() {
    try {
      if (!this.checkAccess()) {
        throw new PermissionException(
            SessionManager.getCurrentSessionUserId(), "syllabus_access_athz", "");
      }

    } catch (PermissionException e) {
      // logger.info(this + ".getEntries() in PostemTool " + e);
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              MessageUtils.getMessage(
                  FacesMessage.SEVERITY_ERROR,
                  "error_permission",
                  (new Object[] {e.toString()}),
                  FacesContext.getCurrentInstance()));
      return "permission_error";
    }
    this.userId = SessionManager.getCurrentSessionUserId();
    this.siteId = ToolManager.getCurrentPlacement().getContext();
    this.currentGradebook = gradebookManager.createEmptyGradebook(this.userId, this.siteId);
    this.oldGradebook = gradebookManager.createEmptyGradebook(this.userId, this.siteId);
    this.csv = null;
    this.newTemplate = null;
    this.delimiter = COMMA_DELIM_STR;

    return "create_gradebook";
  }
Exemplo n.º 5
0
  public String processDelete() {
    try {
      if (!this.checkAccess()) {
        throw new PermissionException(
            SessionManager.getCurrentSessionUserId(), "syllabus_access_athz", "");
      }

    } catch (PermissionException e) {
      // logger.info(this + ".getEntries() in PostemTool " + e);
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              MessageUtils.getMessage(
                  FacesMessage.SEVERITY_ERROR,
                  "error_permission",
                  (new Object[] {e.toString()}),
                  FacesContext.getCurrentInstance()));
      return "permission_error";
    }
    gradebookManager.deleteGradebook(currentGradebook);
    gradebooks = null;
    currentGradebook = null;
    csv = null;
    newTemplate = null;
    students = null;
    return "main";
  }
 public String showDetailsContact(Contact contact) {
   FacesContext context = FacesContext.getCurrentInstance();
   HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
   HttpSession httpSession = request.getSession(false);
   httpSession.setAttribute("contact", contact);
   return "showDetailsContact";
 }
Exemplo n.º 7
0
 private void resolveBindings() {
   FacesContext context = null;
   if (parameters != null) {
     for (int i = 0; i < parameters.length; i++) {
       Object o = parameters[i];
       if (o instanceof ValueBinding) {
         if (context == null) {
           context = FacesContext.getCurrentInstance();
         }
         o = ((ValueBinding) o).getValue(context);
       }
       if (o instanceof ValueExpression) {
         if (context == null) {
           context = FacesContext.getCurrentInstance();
         }
         o = ((ValueExpression) o).getValue(context.getELContext());
       }
       // to avoid 'null' appearing in message
       if (o == null) {
         o = "";
       }
       resolvedParameters[i] = o;
     }
   }
 }
 /**
  * Metodo que busca una historia clinica
  *
  * @author David Carranza
  */
 public void buscarListado() {
   String nombreMetodo = Thread.currentThread().getStackTrace()[1].getMethodName() + "()";
   FacesContext context = FacesContext.getCurrentInstance();
   try {
     lista = new ArrayList<>();
     lista =
         admin.listarOrdenada(
             object.getClass(),
             "cplFechaMuestra",
             fechaInicio,
             "cplEstado",
             3,
             "cplOrdenLlegada",
             true);
     if (lista.isEmpty()) {
       FacesContext.getCurrentInstance()
           .addMessage(
               findComponent(context.getViewRoot(), "formDatos").getClientId(),
               new FacesMessage(
                   FacesMessage.SEVERITY_ERROR,
                   "Busqueda sin resultados",
                   "No se encontro paciente"));
     }
   } catch (Exception e) {
     log.error("{}: {} ", nombreMetodo, e);
   }
 }
Exemplo n.º 9
0
  public void createBuyCardItem(ActionEvent event) {
    System.err.println("TEST");
    FacesMessage msg = new FacesMessage("Your Transaction is succesfully added to Shopping Cart!");
    setMemberAccount(
        (MemberAccount)
            FacesContext.getCurrentInstance()
                .getExternalContext()
                .getSessionMap()
                .get("currentMember"));
    System.err.println("Get memberID = " + getMemberAccount().getId());
    String valuePackage = getBuyCardValue().getTopupType();
    System.err.println(valuePackage);

    if (valuePackage.equals("1000")) {
      this.setBuyCardValue(bimbl.addCardBuyItem(getMemberAccount(), valuePackage, 1000));
      System.err.println("ValueCardValue ID = " + getBuyCardValue());
    } else if (valuePackage.equals("2000")) {
      this.setBuyCardValue(bimbl.addCardBuyItem(getMemberAccount(), valuePackage, 1960));
    } else if (valuePackage.equals("3000")) {
      this.setBuyCardValue(bimbl.addCardBuyItem(getMemberAccount(), valuePackage, 2850));
    } else if (valuePackage.equals("5000")) {
      this.setBuyCardValue(bimbl.addCardBuyItem(getMemberAccount(), valuePackage, 4600));
    } else if (valuePackage.equals("8000")) {
      this.setBuyCardValue(bimbl.addCardBuyItem(getMemberAccount(), valuePackage, 7200));
    } else if (valuePackage.equals("10000")) {
      this.setBuyCardValue(bimbl.addCardBuyItem(getMemberAccount(), valuePackage, 8800));
    }

    FacesContext.getCurrentInstance().addMessage(null, msg);
  }
Exemplo n.º 10
0
  protected void encodeRowExpansion(FacesContext context, DataTable table) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    Map<String, String> params = context.getExternalContext().getRequestParameterMap();
    int expandedRowIndex =
        Integer.parseInt(params.get(table.getClientId(context) + "_expandedRowIndex"));
    String rowIndexVar = table.getRowIndexVar();

    table.setRowIndex(expandedRowIndex);

    if (rowIndexVar != null) {
      context.getExternalContext().getRequestMap().put(rowIndexVar, expandedRowIndex);
    }

    writer.startElement("tr", null);
    writer.writeAttribute("style", "display:none", null);
    writer.writeAttribute(
        "class", DataTable.EXPANDED_ROW_CONTENT_CLASS + " ui-widget-content", null);

    writer.startElement("td", null);
    writer.writeAttribute("colspan", table.getColumnsCount(), null);

    table.getRowExpansion().encodeAll(context);

    writer.endElement("td");

    writer.endElement("tr");

    table.setRowIndex(-1);
  }
  /**
   * Resets/restores the values in the portletPreferences.xhtml Facelet composition with portlet
   * preference default values.
   */
  public void reset() {

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
    PortletPreferences portletPreferences = portletRequest.getPreferences();

    try {
      Enumeration<String> preferenceNames = portletPreferences.getNames();

      while (preferenceNames.hasMoreElements()) {
        String preferenceName = preferenceNames.nextElement();
        portletPreferences.reset(preferenceName);
      }

      portletPreferences.store();

      // Switch the portlet mode back to VIEW.
      ActionResponse actionResponse = (ActionResponse) externalContext.getResponse();
      actionResponse.setPortletMode(PortletMode.VIEW);
      actionResponse.setWindowState(WindowState.NORMAL);

      FacesContextHelperUtil.addGlobalSuccessInfoMessage();
    } catch (Exception e) {
      FacesContextHelperUtil.addGlobalUnexpectedErrorMessage();
    }
  }
Exemplo n.º 12
0
  protected void encodeFrozenRows(FacesContext context, DataTable table) throws IOException {
    Collection<?> frozenRows = table.getFrozenRows();
    if (frozenRows == null || frozenRows.isEmpty()) {
      return;
    }

    ResponseWriter writer = context.getResponseWriter();
    String clientId = table.getClientId(context);
    String var = table.getVar();
    String rowIndexVar = table.getRowIndexVar();
    Map<String, Object> requestMap = context.getExternalContext().getRequestMap();

    writer.startElement("tbody", null);
    writer.writeAttribute("class", DataTable.DATA_CLASS, null);

    int index = 0;
    for (Iterator<? extends Object> it = frozenRows.iterator(); it.hasNext(); ) {
      requestMap.put(var, it.next());

      if (rowIndexVar != null) {
        requestMap.put(rowIndexVar, index);
      }

      encodeRow(context, table, clientId, index, rowIndexVar);
    }

    writer.endElement("tbody");
  }
Exemplo n.º 13
0
  @Override
  protected void doDecode(FacesContext context, UIComponent component) {

    Map<String, String> requestMap = context.getExternalContext().getRequestParameterMap();

    AbstractPanelMenuItem menuItem = (AbstractPanelMenuItem) component;
    String compClientId = component.getClientId(context);
    if (requestMap.get(compClientId) != null) {
      AbstractPanelMenu pm = getParentPanelMenu(menuItem);

      if (pm.isImmediate()) {
        menuItem.setImmediate(true);
      }
      new ActionEvent(menuItem).queue();

      if (context.getPartialViewContext().isPartialRequest()) {

        // TODO nick - why render item by default?
        context.getPartialViewContext().getRenderIds().add(component.getClientId(context));

        // TODO nick - this should be done on encode, not on decode
        addOnCompleteParam(context, component.getClientId(context));
      }
    }
  }
  protected void MensagemErro(String titulo, String msg) {
    FacesContext context = FacesContext.getCurrentInstance();

    FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, titulo);
    context.addMessage(null, m);
    context.getExternalContext().getFlash().setKeepMessages(true);
  }
Exemplo n.º 15
0
  protected void verify(PhaseEvent phaseEvent) {
    FacesContext facesContext = phaseEvent.getFacesContext();
    String viewId = facesContext.getViewRoot().getViewId();
    SecurityBean securityBean = SecurityBean.getInstance();

    /*
     * Primero se valida que la sesión no haya caducado
     * */
    if (SecurityBean.isSessionExpired(facesContext)) {
      try {
        doRedirect(facesContext, "/resources/errorpages/errorSessionExpired.jsp");
        facesContext.responseComplete();

      } catch (Exception e) {
        e.printStackTrace();
      }

    } else if (!securityBean.verifyPageAccess(viewId)) {
      /*
       * Luego se valida que no se esté accediendo a un recurso sin autenticación
       * */
      HttpServletResponse response =
          (HttpServletResponse) facesContext.getExternalContext().getResponse();
      try {
        response.sendError(403); // 403: Forbidden error
        facesContext.responseComplete();

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 16
0
  public void createBuyShowItem(ActionEvent event) throws IOException {
    System.err.println("test show item shopping cart!");
    setMemberAccount(
        (MemberAccount)
            FacesContext.getCurrentInstance()
                .getExternalContext()
                .getSessionMap()
                .get("currentMember"));
    System.err.println("select section num" + getTicketmanager().getSelectSectionNum());
    System.err.println("Show name : " + getTicketmanager().getSelectShowInfo().getName());
    System.err.println("section ticket : " + getTicketmanager().getSelectSectionTicket());

    String orderName =
        getTicketmanager().getSelectShowInfo().getName()
            + " ( section : "
            + getTicketmanager().getSelectSectionTicket().getSeatSection().getNum()
            + " )";
    System.err.println("Order Name : " + orderName);
    int quantity = getTicketmanager().getSelectSeats().size();
    System.err.println("ticket quantity : " + quantity);
    float price = getTicketmanager().getSelectSectionTicket().getPrice();
    System.err.println("ticket unit price : " + price);
    this.setShowItem(bimbl.addBuyShowItem(getMemberAccount(), orderName, quantity, (double) price));
    FacesMessage msg = new FacesMessage("Your ticket order is succesfully added to Shopping Cart!");
    FacesContext.getCurrentInstance().addMessage(null, msg);
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();
    ec.redirect("../CRM/Payment/cart.xhtml");
  }
Exemplo n.º 17
0
 public void startupSystem(System system) throws Exception {
   FacesContext context = FacesContext.getCurrentInstance();
   system.setStatus(System.Status.ON);
   update(system);
   context.addMessage(
       null, new FacesMessage(FacesMessage.SEVERITY_INFO, "System start up successfully", ""));
 }
Exemplo n.º 18
0
 @Override
 public void beforePhase(PhaseEvent event) {
   FacesContext context = event.getFacesContext();
   HttpServletRequest httpRequest = (HttpServletRequest) context.getExternalContext().getRequest();
   try {
     URLPolicyService service = getURLPolicyService();
     if (service.isCandidateForDecoding(httpRequest)) {
       // Make sure we're in a transaction, and that Seam knows it.
       // Sometimes, when there is a page action, SeamPhaseListener
       // commits the transaction in RENDER_RESPONSE before this
       // phase listener executes, but does not start a new one.
       // (SeamPhaseListener.handleTransactionsAfterPageActions)
       if (!Transaction.instance().isActiveOrMarkedRollback()) {
         Transaction.instance().begin();
       }
       // hot reload hook, maybe to move up so that it's handled on
       // all requests, not only the ones using the URLservice
       // framework (?)
       resetHotReloadContext(context);
       // restore state
       service.navigate(context);
       // apply requests parameters after - they may need the state
       // to be restored first.
       service.applyRequestParameters(context);
     }
   } catch (RuntimeException | SystemException | NotSupportedException e) {
     handleException(context, e);
   }
 }
 public String showDetailsEntreprise(Entreprise entreprise) {
   FacesContext context = FacesContext.getCurrentInstance();
   HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
   HttpSession httpSession = request.getSession(false);
   httpSession.setAttribute("entreprise", entreprise);
   return "showDetailsEntreprise";
 }
Exemplo n.º 20
0
 public String process() {
   if (!this.loggedIn) {
     try {
       this.loggedIn =
           this.authenticateObject.check(new AuthenticateDTO(this.login, this.password));
     } catch (EJBException ejbex) {
       this.loggedIn = false;
       System.out.println(ejbex.toString());
     }
   } else {
     this.loggedIn = false;
   }
   if (this.loggedIn) {
     ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest())
         .getSession(true);
     this.cartObject.initialize();
   } else {
     FacesContext facesContext = FacesContext.getCurrentInstance();
     ExternalContext externalContext = facesContext.getExternalContext();
     Locale loc = externalContext.getRequestLocale();
     externalContext.invalidateSession();
     facesContext.getViewRoot().setLocale(loc);
     if (this.cartObject != null) {
       this.cartObject.setClientId(null);
       this.cartObject.setMerchandiseId(null);
       this.cartObject.setAmount(null);
       this.cartObject.destroy();
     }
     this.currencyObject.setLocalizationLocale(loc);
   }
   return null;
 }
 public String delete() {
   statusMessage = SUCCESS_MESSAGE;
   result = "true";
   setDeleteId(new Long((linkDelete.getAttributes().get("deleteId").toString())));
   setClassificationName((String) linkDelete.getAttributes().get("classificationName"));
   try {
     VDCGroup vdcgroup = vdcGroupService.findById(deleteId);
     vdcGroupService.removeVdcGroup(vdcgroup);
     HttpServletRequest request =
         (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
     String referer = (String) request.getHeader("referer");
     result = referer.substring(referer.lastIndexOf("/") + 1, referer.indexOf("."));
     result = getFriendlyLinkName();
     resultLink = referer;
     // this.vdcGroupService.updateGroupOrder(order); // TBD
   } catch (Exception e) {
     statusMessage = FAIL_MESSAGE + " " + e.getCause().toString();
     result = "failed";
   } finally {
     Iterator iterator =
         FacesContext.getCurrentInstance().getMessages("AddClassificationsPageForm");
     while (iterator.hasNext()) {
       iterator.remove();
     }
     FacesContext.getCurrentInstance()
         .addMessage("AddClassificationsPageForm", new FacesMessage(statusMessage));
     return "success";
   }
 }
Exemplo n.º 22
0
  /**
   * Creates and returns a FacesMessage for the specified Locale.
   *
   * @param context - the <code>FacesContext</code> for the current request
   * @param messageId - the key of the message in the resource bundle
   * @param params - substittion parameters
   * @return a localized <code>FacesMessage</code> with the severity of FacesMessage.SEVERITY_ERROR
   */
  protected static FacesMessage getMessage(
      FacesContext context, String messageId, Object... params) {

    if (context == null || messageId == null) {
      throw new NullPointerException(" context " + context + " messageId " + messageId);
    }
    Locale locale;
    // viewRoot may not have been initialized at this point.
    if (context.getViewRoot() != null) {
      locale = context.getViewRoot().getLocale();
    } else {
      locale = Locale.getDefault();
    }

    if (null == locale) {
      throw new NullPointerException(" locale is null ");
    }

    FacesMessage message = getMessage(locale, messageId, params);
    if (message != null) {
      return message;
    }
    locale = Locale.getDefault();
    return (getMessage(locale, messageId, params));
  }
Exemplo n.º 23
0
  public String processInstructorView() {
    try {
      if (!this.checkAccess()) {
        throw new PermissionException(
            SessionManager.getCurrentSessionUserId(), "syllabus_access_athz", "");
      }

    } catch (PermissionException e) {
      // logger.info(this + ".getEntries() in PostemTool " + e);
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              MessageUtils.getMessage(
                  FacesMessage.SEVERITY_ERROR,
                  "error_permission",
                  (new Object[] {e.toString()}),
                  FacesContext.getCurrentInstance()));
      return "permission_error";
    }
    Long currentGbId = ((Gradebook) gradebookTable.getRowData()).getId();
    currentGradebook = gradebookManager.getGradebookByIdWithHeadingsAndStudents(currentGbId);

    students = new ArrayList(currentGradebook.getStudents());

    return "view_gradebook";
  }
 public String doForgotPassword() {
   TypedQuery<User> query = em.createNamedQuery(User.FIND_BY_EMAIL, User.class);
   query.setParameter("email", user.getEmail());
   try {
     user = query.getSingleResult();
     String temporaryPassword = Lorem.getWords(1);
     user.setPassword(PasswordUtils.digestPassword(temporaryPassword));
     em.merge(user);
     facesContext.addMessage(
         null,
         new FacesMessage(
             FacesMessage.SEVERITY_INFO,
             "Email sent",
             "An email has been sent to "
                 + user.getEmail()
                 + " with temporary password :"******"dummyPassword"
     return doLogout();
   } catch (NoResultException e) {
     facesContext.addMessage(
         null,
         new FacesMessage(
             FacesMessage.SEVERITY_WARN,
             "Unknown email",
             "This email address is unknonw in our system"));
     return null;
   }
 }
  public void activarDescuento(ActionEvent e) {
    FacesContext context = FacesContext.getCurrentInstance();
    Integer productoId =
        Integer.parseInt(context.getExternalContext().getRequestParameterMap().get("productoId"));

    logger.debug("## >> activarDescuento: productoId=" + productoId);
    boolean selectedFromDetalle = false;
    for (PedidoVentaDetalleWrapper dvp : pedidoVentaDetalleList) {
      logger.debug(
          "## >> activarDescuento: ["
              + dvp.getProducto().getId()
              + "] == "
              + productoId
              + " ? "
              + (dvp.getProducto().getId() == productoId)
              + " , or use .equals ?"
              + (dvp.getProducto().getId().equals(productoId)));
      if (dvp.getProducto().getId().equals(productoId)) {
        // dvp.setDescuentoAplicado(dvp.getProducto().getFactorMaxDesc());
        selectedFromDetalle = true;
        break;
      }
    }
    if (!selectedFromDetalle) {
      logger.warn(
          "\t## >> productoId=" + productoId + " => selectedFromDetalle=" + selectedFromDetalle);
    }
    logger.debug("## >> end: activarDescuento");
  }
  public String doSignup() {
    // Does the login already exists ?
    if (em.createNamedQuery(User.FIND_BY_LOGIN, User.class)
            .setParameter("login", user.getLogin())
            .getResultList()
            .size()
        > 0) {
      facesContext.addMessage(
          null,
          new FacesMessage(
              FacesMessage.SEVERITY_WARN,
              "Login already exists " + user.getLogin(),
              "You must choose a different login"));
      return null;
    }

    // Everything is ok, we can create the user
    user.setPassword(password1);
    em.persist(user);
    resetPasswords();
    facesContext.addMessage(
        null,
        new FacesMessage(
            FacesMessage.SEVERITY_INFO, "Hi " + user.getFirstName(), "Welcome to this website"));
    loggedIn = true;
    if (user.getRole().equals(UserRole.ADMIN)) admin = true;
    return "/main";
  }
Exemplo n.º 27
0
  public String removerCategoria() {

    HttpServletRequest request =
        (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

    try {
      long idCategoria = Long.parseLong(request.getParameter("idCategoria"));

      CategoriaDAO categoriaDao = new CategoriaJPADAO();
      Categoria categoria = categoriaDao.find(idCategoria);

      categoriaDao.delete(categoria);

    } catch (NumberFormatException ex) {
      ex.printStackTrace();
      FacesContext.getCurrentInstance()
          .addMessage(
              "Aviso", new FacesMessage(FacesMessage.SEVERITY_WARN, "Categoria inexistente!", ""));

    } catch (PersistenceException e) {
      e.printStackTrace();
      new CategoriaJPADAO().rollback();
      FacesContext.getCurrentInstance()
          .addMessage(
              "Aviso",
              new FacesMessage(
                  FacesMessage.SEVERITY_WARN, "Já existem atividades nesta categoria!", ""));
    }

    return "?faces-redirect=true";
  }
    public void processEvent(FacesEvent event) throws AbortProcessingException {

      FacesContext faces = FacesContext.getCurrentInstance();
      if (faces == null) {
        return;
      }

      L instance = null;
      if (this.binding != null) {
        instance = (L) binding.getValue(faces.getELContext());
      }
      if (instance == null && this.type != null) {
        try {
          instance = (L) TagHandlerUtils.loadClass(this.type, Object.class).newInstance();
        } catch (Exception e) {
          throw new AbortProcessingException("Couldn't Lazily instantiate EventListener", e);
        }
        if (this.binding != null) {
          binding.setValue(faces.getELContext(), instance);
        }
      }

      if (instance != null) {
        event.processListener(instance);
      }
    }
Exemplo n.º 29
0
  /**
   * Collect all messages associated with components identified by <code>for</code> attribute and
   * return it. An empty list will be returned when there are no messages.
   *
   * @param context The involved faces context.
   * @param component The messages component.
   * @return All messages associated with components identified by <code>for</code> attribute.
   */
  protected List<FacesMessage> getMessages(FacesContext context, OmniMessages component) {
    String forClientIds = component.getFor();

    if (forClientIds == null) {
      return component.isGlobalOnly() ? context.getMessageList(null) : context.getMessageList();
    }

    List<FacesMessage> messages = new ArrayList<>();

    for (String forClientId : forClientIds.split("\\s+")) {
      UIComponent forComponent = component.findComponent(forClientId);

      if (forComponent == null) {
        continue;
      }

      messages.addAll(context.getMessageList(forComponent.getClientId(context)));

      if (!(forComponent instanceof UIInput)) {
        for (UIInput child : findComponentsInChildren(forComponent, UIInput.class)) {
          messages.addAll(context.getMessageList(child.getClientId(context)));
        }
      }
    }

    return messages;
  }
Exemplo n.º 30
0
 public static String getArrayValue(String name, Long id, FacesContext fc) {
   if (name.compareTo("Nazioni") == 0) {
     return (String)
         ((PropertiesHandler) JSFUtils.getManagedBean("propertiesHandler"))
             .getNazioni()
             .get(id)
             .getNazione();
   } else if (name.compareTo("Province") == 0) {
     return (String)
         ((PropertiesHandler) JSFUtils.getManagedBean("propertiesHandler"))
             .getProvince()
             .get(id)
             .getProvincia();
   } else if (name.compareTo("Comuni") == 0) {
     return (String)
         ((PropertiesHandler) JSFUtils.getManagedBean("propertiesHandler"))
             .getComuni()
             .get(id)
             .getComune();
   } else {
     ArrayList<Object> array =
         (ArrayList<Object>)
             fc.getApplication().getELResolver().getValue(fc.getELContext(), null, name);
     return (String) array.get(id.intValue());
   }
 }