public String displayCustomerReport() {

    try {
      this.setBillId(0);
      this.transactionList = null;
      FacesContext ctx = FacesContext.getCurrentInstance();
      ExternalContext etx = ctx.getExternalContext();
      HttpSession session = (HttpSession) etx.getSession(true);
      this.userName = (String) session.getAttribute("userName");

      Myshopee_Wrapper myshopee_Wrapper = new Myshopee_Wrapper();
      this.billList = new ArrayList<Myshopee_BillingTO>();
      this.billList =
          myshopee_Wrapper.getTransactionByCustomer(this.fromDate, this.toDate, this.userName);
      this.transactionList = null;
      this.setMessage("");
      return "success";
    } catch (NoBillingForThisRangeException exception) {
      this.billList = null;
      this.setMessage(exception.getMessage());
      return "fail";
    } catch (ToDateGreaterThanFromDateException exception) {
      // TODO Auto-generated catch block
      this.billList = null;
      this.setMessage(exception.getMessage());
      return "fail";
    }
  }
示例#2
0
 /**
  * Downloads a blob and sends it to the requesting user, in the JSF current context.
  *
  * @param doc the document, if available
  * @param xpath the blob's xpath or blobholder index, if available
  * @param blob the blob, if already fetched
  * @param filename the filename to use
  * @param reason the download reason
  * @param extendedInfos an optional map of extended informations to log
  * @since 7.3
  */
 public static void download(
     DocumentModel doc,
     String xpath,
     Blob blob,
     String filename,
     String reason,
     Map<String, Serializable> extendedInfos) {
   FacesContext facesContext = FacesContext.getCurrentInstance();
   if (facesContext.getResponseComplete()) {
     // nothing can be written, an error was probably already sent. don't bother
     log.debug("Cannot send " + filename + ", response already complete");
     return;
   }
   if (facesContext.getPartialViewContext().isAjaxRequest()) {
     // do not perform download in an ajax request
     return;
   }
   ExternalContext externalContext = facesContext.getExternalContext();
   HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
   HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
   try {
     DownloadService downloadService = Framework.getService(DownloadService.class);
     downloadService.downloadBlob(
         request, response, doc, xpath, blob, filename, reason, extendedInfos);
   } catch (IOException e) {
     log.error("Error while downloading the file: " + filename, e);
   } finally {
     facesContext.responseComplete();
   }
 }
  /**
   * 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();
    }
  }
 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 void registrarMatrinonio() throws IOException {
    getMatrimonio().setNormal(false);
    getMatrimonio().setHistorico(true);
    getMatrimonio().setEspecial(false);

    setMatrimonioDetalle(
        getMatrimonioService()
            .registrarMatrimonio(
                getMatrimonio(),
                getConsentimientoContrayenteUno(),
                getConsentimientoContrayenteDos()));
    if (getMatrimonioDetalle().getCodigoRespuesta().equals(0)) {
      FacesContext context = FacesContext.getCurrentInstance();
      context.getExternalContext().getFlash().setKeepMessages(true);

      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              new FacesMessage(
                  FacesMessage.SEVERITY_INFO, "El registro se ha guardado correctamente.", ""));

      ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      externalContext.redirect(
          externalContext.getRequestContextPath().concat(ConstantesComunes.DETALLE_MATRIMONIO));
    } else {
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              new FacesMessage(
                  FacesMessage.SEVERITY_ERROR,
                  "Ocurri\u00f3 un error al guardar el registro.",
                  ""));
      RequestContext.getCurrentInstance().execute("errorDialog.show()");
    }
  }
 public void generarArchivo() {
   String salida = "nombres";
   System.out.println("tamanho " + contenido.size());
   for (int x = 0; x < contenido.size(); x++) {
     salida += "\n" + contenido.get(x).getNombre();
   }
   salida += "\nimagenes";
   for (int x = 0; x < contenido.size(); x++) {
     salida += "\n" + contenido.get(x).getDirImagen();
   }
   salida += "\nsonidos";
   for (int x = 0; x < contenido.size(); x++) {
     salida += "\n" + contenido.get(x).getDirSonido();
   }
   // crear archivo de texto
   try {
     ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
     File file =
         new File(extContext.getRealPath("//resources//txtLecciones//" + nombreLeccion + ".txt"));
     // if file doesnt exists, then create it
     if (!file.exists()) {
       file.createNewFile();
     }
     FileWriter fw = new FileWriter(file.getAbsoluteFile());
     BufferedWriter bw = new BufferedWriter(fw);
     bw.write(salida);
     bw.close();
     System.out.println("Done");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
示例#7
0
 private URL[] getWebappResourceRoots(ExternalContext extContext) {
   URL[] result = null;
   int size = 0, i = 0;
   Set<String> resourceRoots = extContext.getResourcePaths("/resources/");
   if (null != resourceRoots && !resourceRoots.isEmpty()) {
     // Determine the size of script roots that end with "/"
     for (String cur : resourceRoots) {
       if (cur.endsWith("/")) {
         size++;
       }
     }
     result = new URL[size];
     for (String cur : resourceRoots) {
       if (cur.endsWith("/")) {
         try {
           result[i++] = extContext.getResource(cur);
         } catch (MalformedURLException ex) {
           if (LOGGER.isLoggable(Level.SEVERE)) {
             LOGGER.log(Level.SEVERE, null, ex);
           }
         }
       }
     }
   }
   if (null == result) {
     result = new URL[0];
   }
   return result;
 }
  public static Object resolveBean(String beanName, TabScopeManager context) {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext externalContext = fc.getExternalContext();
    if (externalContext instanceof ServletExternalContext) {
      HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

      // save backup of current binding to cope with nested tags?
      Object contextBackup = request.getAttribute(PARAM_CURRENT_MANAGER);
      request.setAttribute(PARAM_CURRENT_MANAGER, context);
      try {
        return FacesUtils.getBeanFromContext(fc, beanName);
      } finally {
        if (null != contextBackup) {
          request.setAttribute(PARAM_CURRENT_MANAGER, contextBackup);
        } else {
          request.removeAttribute(PARAM_CURRENT_MANAGER);
        }
      }
    } else if (externalContext instanceof PortletExternalContext) {
      // TODO portlets
      trace.warn("Portlets are not yet supported.");
    }

    return null;
  }
  public DownloadMaterialApoioBean() {

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    HttpSession session = (HttpSession) externalContext.getSession(true);
    login = (LoginBean) session.getAttribute("loginBean");

    fachada = FacadeAuth.getInstance();

    root = new CheckboxTreeNode(new Documents("Arquivos", "-", "Pasta"), null);

    TreeNode documents = new CheckboxTreeNode(new Documents("Documentos", "-", "Folder"), root);

    try {

      List<MaterialDeApoio> list = fachada.getMaterialApoio(login.getSession());

      if (null != list) {

        for (int i = 0; i < list.size(); i++) {

          Documents d = new Documents(list.get(i).getUrlArquivo(), "--", list.get(i).getNucleo());

          @SuppressWarnings("unused")
          TreeNode expenses = new CheckboxTreeNode("document", d, documents);
        }
      }

    } catch (NoSuchSessionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public void register(ActionEvent actionEvent) {
    CustomerDAO cdao = HibernateDAOFactory.instance().getCustomerDAO();

    RequestContext context = RequestContext.getCurrentInstance();
    FacesMessage msg = null;
    boolean loggedIn = false;
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    if (cdao.checklemail(email)) {
      Customer cs = new Customer();
      cs.setEmail(email);
      cs.setPass(pass);
      cs.setFullName(fullName);
      cs.setAddress(address);
      cs.setPhone(phone);
      cs.setVip(vip);
      cdao.add(cs);
      loggedIn = true;
      msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Registe succes! Welcome", email);
      String url = "index.xhtml";
      try {
        ec.redirect(url);
      } catch (IOException ex) {

      }
    } else {
      loggedIn = false;
      msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Registe Error", "Invalid credentials");
    }

    FacesContext.getCurrentInstance().addMessage(null, msg);
    context.addCallbackParam("loggedIn", loggedIn);
  }
示例#11
0
  private boolean compressionPathIsValid(ClientResourceInfo resource) throws IOException {

    ExternalContext extContext = getFacesContext().getExternalContext();
    File tempDir = (File) extContext.getApplicationMap().get("javax.servlet.context.tempdir");
    File expected = new File(tempDir, "/jsf-compressed" + File.separatorChar + resource.getPath());
    return expected.getCanonicalPath().equals(resource.getCompressedPath());
  }
示例#12
0
  public void payOrder() throws PayPalRESTException, IOException {
    // registering order and redirect  to payment service
    if (!(loginBean.isLinked())) {
      user.setActive(false);
    }
    user = userService.update(user);
    if (order.getDeliveryType() == DeliveryType.courierInKiev) {
      order.setAddressOrStorageNum(
          user.getCountry()
              + ", "
              + user.getCity()
              + ", "
              + user.getStreet()
              + ", "
              + user.getHouse()
              + ", кв. "
              + user.getApartment());
    }
    PaymentResultDto paymentResultDto = cartBean.buy(user.getId(), order);
    if (!paymentResultDto.approvalUrl.isEmpty()) {
      ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
      ec.redirect(paymentResultDto.approvalUrl);
    }

    orderMade = true;
    emailService.sendManagerNotificationByOrderId(paymentResultDto.orderId, getApplicationUri());
    //        return null;
  }
 public QuotationCreationPageBean getQuotationBean() {
   ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
   HttpSession session = (HttpSession) ectx.getSession(false);
   QuotationCreationPageBean quotationBean =
       (QuotationCreationPageBean) session.getAttribute("newquote");
   return quotationBean;
 }
示例#14
0
  @PostConstruct
  public void controllerSetup() {
    logger.debug("Start init of EntityController");
    ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
    String entity = extContext.getRequestParameterMap().get("entityClassName");
    this.setEntityClassName(entity);
    ejb.setEntityClass(this.getEntityClassName());
    this.entityClass = ejb.getEntityClass();
    Properties props = this.ejb.getEntityProperties(this.getEntityClass());

    if (props != null) {
      columns = new ArrayList<ColumnModel>();
      Enumeration<?> i = props.keys();

      while (i.hasMoreElements()) {
        String key = (String) i.nextElement();
        columns.add(new ColumnModel(props.getProperty(key), key));
      }
    }

    this.getLazyDataModel().setEntityClass(entity);
    this.getLazyDataModel().init();
    logger.debug("Data filled for entity " + entity);
    this.setCurrentEntity(null);
  }
  /**
   * Return an existing scoped object for the specified name (if any); otherwise, return <code>null
   * </code>.
   *
   * @param context <code>ELContext</code> for evaluating this value
   * @param base Base object against which this evaluation occurs (must be null because we are
   *     evaluating a top level variable)
   * @param property Property name to be accessed
   */
  public Object getValue(ELContext context, Object base, Object property) {

    if (base != null) {
      return null;
    }
    if (property == null) {
      throw new PropertyNotFoundException("No property specified");
    }

    FacesContext fcontext = (FacesContext) context.getContext(FacesContext.class);
    ExternalContext econtext = fcontext.getExternalContext();
    Object value = null;
    value = econtext.getRequestMap().get(property);
    if (value != null) {
      context.setPropertyResolved(true);
      return value;
    }
    value = econtext.getSessionMap().get(property);
    if (value != null) {
      context.setPropertyResolved(true);
      return value;
    }
    value = econtext.getApplicationMap().get(property);
    if (value != null) {
      context.setPropertyResolved(true);
      return value;
    }

    return null;
  }
示例#16
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  public byte[] gerarRelatorioJasper(
      String nomeJasper, List<?> dataSource, Map parametros, String tipo)
      throws JRException, IOException {

    FacesContext fContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = fContext.getExternalContext();

    // Busca o local onde esta o jasper
    InputStream fis = externalContext.getResourceAsStream(PATH + nomeJasper);
    JasperReport jasperReport = (JasperReport) JRLoader.loadObject(fis);

    // Abre a figura e seta o parâmetro do relatório
    InputStream imgInputStream =
        this.getClass().getResourceAsStream("/resources/images/logo/" + "fmb.gif");
    parametros.put("IMG_BRASAO", imgInputStream);

    JRDataSource ds = new JRBeanCollectionDataSource(dataSource);
    byte[] bytes = null;

    if (tipo.equals("P")) {
      bytes = this.gerarRelatorioJasperPDF(jasperReport, parametros, ds);
    } else if (tipo.equals("X")) {
      bytes = this.gerarRelatorioJasperXLS(jasperReport, parametros, ds);
    } else if (tipo.equals("D")) {
      bytes = this.gerarRelatorioJasperDoc(jasperReport, parametros, ds);
    }

    return bytes;
  }
示例#17
0
  public static String getParam(String paramName) {
    ExternalContext ext = FacesUtils.extContext();
    Map<String, String> p = ext.getRequestParameterMap();
    if (p.containsKey(paramName)) return p.get(paramName);

    return null;
  }
  public void registrarReconocimiento() throws IOException {

    setReconocimientoDetalle(
        getReconocimientoService()
            .registrarReconocimiento(getReconocimiento(), getPersonaOtorgaConsentimiento()));

    if (getReconocimientoDetalle().getCodigoRespuesta().equals(0)) {

      FacesContext context = FacesContext.getCurrentInstance();
      context.getExternalContext().getFlash().setKeepMessages(true);

      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              new FacesMessage(
                  FacesMessage.SEVERITY_INFO, "El registro se ha guardado correctamente.", ""));

      ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      externalContext.redirect(
          externalContext.getRequestContextPath().concat(ConstantesComunes.DETALLE_RECONOCIMIENTO));

    } else {

      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              new FacesMessage(
                  FacesMessage.SEVERITY_ERROR,
                  "Ocurri\u00f3 un error al guardar el registro.",
                  ""));
      RequestContext.getCurrentInstance().execute("errorDialog.show()");
    }
  }
示例#19
0
  /**
   * Environments like portlets need to namespace the components in order to uniquely identify them
   * on the page in case there are multiple instances of the same portlet or different portlets that
   * use the same ids. This method will prepend the namespace properly taking care to ensure that
   * the namespace is not added twice and that a colon (:) is added if necessary.
   *
   * @param fc The current FacesContext instance
   * @param id The id to encode
   * @return The namespace encoded id
   */
  public static String encodeNameSpace(FacesContext fc, String id) {

    if (id == null || id.trim().length() == 0) {
      return id;
    }

    String tempId = id;
    ExternalContext ec = fc.getExternalContext();
    String encodedId = ec.encodeNamespace(tempId);

    // If no namespace was applied, we're done.
    if (encodedId.equals(id)) {
      return id;
    }

    // Extract the actual namespace.
    int idStart = encodedId.indexOf(id);
    String ns = encodedId.substring(0, idStart);

    // Check if the id already had the namespace.  If so, we're done.
    if (id.startsWith(ns)) {
      return id;
    }

    // If necessary, add the separator character before including the namespace.
    String sep = String.valueOf(UINamingContainer.getSeparatorChar(fc));
    if (!id.startsWith(sep)) {
      id = ":" + id;
    }

    // Add the namespace.
    id = ns + id;
    return id;
  }
示例#20
0
  /**
   * Inspects the incoming request parameters for the standardized state parameter name. In this
   * case, the parameter value will be the composite ID generated by
   * ServerSideStateHelper#writeState(FacesContext, Object, StringBuilder).
   *
   * <p>The composite key will be used to find the appropriate view within the session obtained from
   * the provided <code>FacesContext</code>
   */
  public Object getState(FacesContext ctx, String viewId) {

    String compoundId = getStateParamValue(ctx);

    if (compoundId == null) {
      return null;
    }

    if ("stateless".equals(compoundId)) {
      return "stateless";
    }

    int sep = compoundId.indexOf(':');
    assert (sep != -1);
    assert (sep < compoundId.length());

    String idInLogicalMap = compoundId.substring(0, sep);
    String idInActualMap = compoundId.substring(sep + 1);

    ExternalContext externalCtx = ctx.getExternalContext();
    Object sessionObj = externalCtx.getSession(false);

    // stop evaluating if the session is not available
    if (sessionObj == null) {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(
            Level.FINE,
            "Unable to restore server side state for view ID {0} as no session is available",
            viewId);
      }
      return null;
    }

    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (sessionObj) {
      Map logicalMap = (Map) externalCtx.getSessionMap().get(LOGICAL_VIEW_MAP);
      if (logicalMap != null) {
        Map actualMap = (Map) logicalMap.get(idInLogicalMap);
        if (actualMap != null) {
          RequestStateManager.set(ctx, RequestStateManager.LOGICAL_VIEW_MAP, idInLogicalMap);
          Object[] state = (Object[]) actualMap.get(idInActualMap);
          Object[] restoredState = new Object[2];

          restoredState[0] = state[0];
          restoredState[1] = state[1];

          if (state != null) {
            RequestStateManager.set(ctx, RequestStateManager.ACTUAL_VIEW_MAP, idInActualMap);
            if (state.length == 2 && state[1] != null) {
              restoredState[1] = handleRestoreState(state[1]);
            }
          }

          return restoredState;
        }
      }
    }

    return null;
  }
  /**
   * This method writes a <noop/> to the response.
   *
   * @param context the FacesContext
   * @throws IOException
   */
  public static void renderNoopResponse(FacesContext context) throws IOException {
    ExternalContext external = context.getExternalContext();
    Writer writer = ExternalContextUtils.getResponseWriter(external);
    Object response = external.getResponse();

    if (response instanceof HttpServletResponse) {
      HttpServletResponse httpResponse = (HttpServletResponse) response;

      // Prevent caching
      httpResponse.setHeader("Cache-Control", "no-cache");
      httpResponse.setHeader("Pragma", "no-cache");
      httpResponse.setHeader("Expires", "-1");
    }

    XmlResponseWriter xrw = new XmlResponseWriter(writer, "utf-8");
    xrw.startDocument();

    xrw.startElement("partial-response", null);
    xrw.startElement("noop", null);
    xrw.endElement("noop");
    xrw.endElement("partial-response");

    xrw.endDocument();
    xrw.close();
  }
示例#22
0
 private String getViewParameter(String name) {
   FacesContext facesContext = FacesContext.getCurrentInstance();
   ExternalContext externalContext = facesContext.getExternalContext();
   String param = (String) externalContext.getRequestParameterMap().get(name);
   if (param != null && param.trim().length() > 0) return param;
   return null;
 }
  @Override
  public void handle() throws FacesException {
    final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();

    while (i.hasNext()) {
      ExceptionQueuedEvent event = i.next();
      ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

      Throwable t = context.getException();

      final FacesContext fc = FacesContext.getCurrentInstance();
      final Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();

      try {
        System.out.printf(">>> Exception caught: %s", t.getMessage());
        t.printStackTrace();

        requestMap.put("exceptionMessage", t.getMessage());

        ExternalContext extContext = fc.getExternalContext();
        String url = extContext.encodeActionURL(extContext.getRequestContextPath() + "/500.xhtml");
        extContext.redirect(url);
      } catch (Exception e) {
        String errorPageLocation = "/WEB-INF/500.xhtml";
        fc.setViewRoot(fc.getApplication().getViewHandler().createView(fc, errorPageLocation));
        fc.getPartialViewContext().setRenderAll(false);
        fc.renderResponse();
      } finally {
        i.remove();
      }
    }

    getWrapped().handle();
  }
示例#24
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");
  }
  @Override
  public void decode(FacesContext context, UIComponent component) {
    ExternalContext external = context.getExternalContext();
    Map requestParams = external.getRequestParameterMap();
    UIInputListOfValues inputLov = (UIInputListOfValues) component;
    String clientId = inputLov.getClientId(context);
    String id = (String) inputLov.getAttributes().get("objectName");
    String nameId = clientId;
    if (id != null) {
      clientId = id + "Id";
      nameId = id + "Name";
    }

    String submittedValue = (String) requestParams.get(clientId);
    String nameValue = (String) requestParams.get(nameId);
    if (submittedValue != null) inputLov.setSubmittedValue(submittedValue);

    if (JSFUtil.isNotEmpty(submittedValue)) {
      inputLov.setValueName(nameValue);
      inputLov.setValueId(submittedValue);
      inputLov.setValid(true);
    } else {
      inputLov.setValueName(null);
      inputLov.setValueId(null);
    }
  }
示例#26
0
  private void addCookie(ExternalContext extContext, Flash flash) {
    // Do not update the cookie if redirect after post
    if (flash.isRedirect()) {
      return;
    }

    String thisRequestSequenceString = null;
    HttpServletResponse servletResponse = null;
    // PortletRequest portletRequest = null;
    Object thisRequestSequenceStringObj, response = extContext.getResponse();

    thisRequestSequenceStringObj =
        extContext.getRequestMap().get(Constants.FLASH_THIS_REQUEST_ATTRIBUTE_NAME);
    if (null == thisRequestSequenceStringObj) {
      return;
    }
    thisRequestSequenceString = thisRequestSequenceStringObj.toString();

    if (response instanceof HttpServletResponse) {
      servletResponse = (HttpServletResponse) response;
      Cookie cookie =
          new Cookie(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, thisRequestSequenceString);
      cookie.setMaxAge(-1);
      servletResponse.addCookie(cookie);
    } else {
      /**
       * *** portletRequest = (PortletRequest) request; // You can't add a cookie in portlet. //
       * http://wiki.java.net/bin/view/Portlet/JSR168FAQ#How_can_I_set_retrieve_a_cookie
       * portletRequest.getPortletSession().setAttribute(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME,
       * thisRequestSequenceString, PortletSession.PORTLET_SCOPE); *******
       */
    }
  }
示例#27
0
  // Decodes Behaviors if any match the behavior source/event.
  // As a convenience, returns component id, but only if it
  // was retrieved.  This allows us to avoid duplicating
  // calls to getClientId(), which can be expensive for
  // deep component trees.
  protected final String decodeBehaviors(FacesContext context, UIComponent component) {

    if (!(component instanceof ClientBehaviorHolder)) {
      return null;
    }

    ClientBehaviorHolder holder = (ClientBehaviorHolder) component;
    Map<String, List<ClientBehavior>> behaviors = holder.getClientBehaviors();
    if (behaviors.isEmpty()) {
      return null;
    }

    ExternalContext external = context.getExternalContext();
    Map<String, String> params = external.getRequestParameterMap();
    String behaviorEvent = params.get("javax.faces.behavior.event");

    if (null != behaviorEvent) {
      List<ClientBehavior> behaviorsForEvent = behaviors.get(behaviorEvent);

      if (behaviorsForEvent != null && behaviorsForEvent.size() > 0) {
        String behaviorSource = params.get("javax.faces.source");
        String clientId = component.getClientId();
        if (isBehaviorSource(context, behaviorSource, clientId)) {
          for (ClientBehavior behavior : behaviorsForEvent) {
            behavior.decode(context, component);
          }
        }

        return clientId;
      }
    }

    return null;
  }
示例#28
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);
      }
    }
  }
示例#29
0
 /**
  * Retorna el nombre del proyecto de la aplicación web
  *
  * @return
  */
 public String getNombreProyecto() {
   ExternalContext iecx = FacesContext.getCurrentInstance().getExternalContext();
   HttpServletRequest request = (HttpServletRequest) iecx.getRequest();
   String contexto = request.getContextPath() + "";
   contexto = contexto.replace("/", "");
   contexto = contexto.trim();
   return contexto;
 }
 public void doRedirect(FacesContext fc, String redirectPage) {
   ExternalContext ec = fc.getExternalContext();
   try {
     ec.redirect(ec.getRequestContextPath() + (redirectPage != null ? redirectPage : ""));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }