@RequestMapping(value = "/loginCheck", method = RequestMethod.POST)
  public String validateUser(
      Model model,
      @Valid @ModelAttribute("user") Users user,
      BindingResult result,
      HttpSession session) {
    if (result.hasErrors()) {
      System.out.println("has errors");
      return "login";
    }

    System.out.println("user.getUsername()>>>>" + user.getUsername());
    if (user.getUsername() == "admin" || user.getUsername().equals("admin")) {
      session.setAttribute("user", user);
      return "redirect:/admin";
    }
    Customer customer =
        customerService.getCustomerByUsernameAndPassword(user.getUsername(), user.getPassword());

    if (customer != null) {
      session.setAttribute("user", user);
      return "redirect:/product/productList";
    } else {
      model.addAttribute("logincheckMsg", "Invalid Credentials");
      return "login";
    }
  }
  /** Implementacao do metodo doPost() Servlet de Autenticacao de Usuario. */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    HttpSession session = request.getSession(); // obtem a sessao do usuario, caso exista
    UsuarioBC usuarioBC = new UsuarioBC();
    Usuario user = null;
    String email_form = request.getParameter("email"); // Pega o email vindo do formulario
    String senha_form = request.getParameter("senha"); // Pega a senha vinda do formulario
    Boolean saudacao = false;

    try {
      user = usuarioBC.consultarUsuarioPorEmail_Senha(email_form, senha_form);
    } catch (Exception e) {

    }

    // se nao encontrou usuario no banco, redireciona para a pagina de login
    if (user == null) {
      session.setAttribute("erro", "E-mail ou Senha inválidos!");
      request.getRequestDispatcher("/login.jsp").forward(request, response);
    } else {
      saudacao = true;
      // se o dao retornar um usuario, coloca o mesmo na sessao
      session.setAttribute("usuarioLogado", user);
      session.setAttribute("saudacao", saudacao);
      request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    RequestDispatcher rd;

    // HttpSession
    HttpSession session;
    session = request.getSession(false);
    String dni;
    String password;

    if (session == null) {
      rd = this.getServletContext().getRequestDispatcher("/error.jsp");
      rd.forward(request, response);
    } else {
      Administrador a = (Administrador) session.getAttribute("entidad");
      Integer idRol = (Integer) session.getAttribute("id");

      session.setAttribute("entidad", a);
      session.setAttribute("id", idRol);
    }

    List<Especialidad> especialidad;
    //   List <Roles> rol;

    especialidad = (List<Especialidad>) facadeEspecialidad.findAll();
    //  rol = (List <Roles>) facadeRoles.findAll();
    request.setAttribute("lista_especialidad", especialidad);
    //  request.setAttribute("lista_rol", rol);

    rd = this.getServletContext().getRequestDispatcher("/inma/NuevoMedico.jsp");
    rd.forward(request, response);
  }
  @Override
  public String execute(HttpServletRequest request, HttpServletResponse repsonse)
      throws DAOException {

    List<Car> allCars = new ArrayList<Car>();

    String forwardToJsp = "";

    String viewType = (String) request.getParameter("boolean");
    System.out.println(viewType);

    PublicDAO publicDao = new PublicDAO();

    allCars = publicDao.getAllVehicles();

    if (!allCars.isEmpty()) {

      HttpSession session = request.getSession();

      session.setAttribute("car", allCars);
      session.setAttribute("view", "0");

      forwardToJsp = "/allCars.jsp";
    } else {
      forwardToJsp = "/loginFailure.jsp";
    }
    return forwardToJsp;
  }
  @SuppressWarnings("unchecked")
  @ResponseBody
  @RequestMapping(value = "/order/getOrder.ajax", method = RequestMethod.POST)
  public ResponseEntity<byte[]> getOrder(HttpServletRequest request) throws Exception {

    Map<String, Object> model = new HashMap<String, Object>();

    try {
      HttpSession session = request.getSession(true);
      String orderId = (String) session.getAttribute("orderid");
      String restaurantId = (String) session.getAttribute("restaurantid");
      Order order = null;
      if (orderId != null) {
        order = orderRepository.findByOrderId(orderId);

        // If the current order has no items but is linked to another restauarant, update it now
        if (order.getOrderItems().size() == 0 && !order.getRestaurantId().equals(restaurantId)) {
          order.setRestaurant(restaurantRepository.findByRestaurantId(restaurantId));
        }
        order.updateCosts();

        // Update can checkout status of order
        session.setAttribute("cancheckout", order.getCanCheckout());
        session.setAttribute("cansubmitpayment", order.getCanSubmitPayment());
      }

      model.put("success", true);
      model.put("order", order);
    } catch (Exception ex) {
      LOGGER.error("", ex);
      model.put("success", false);
      model.put("message", ex.getMessage());
    }
    return buildOrderResponse(model);
  }
Example #6
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    BiorganSQL db = new BiorganSQL("root", "root");
    String passwd = request.getParameter("user_passwd");
    String mail = request.getParameter("user_mail");
    BiorganUser user = null;

    if (mail == null || passwd == null || mail.length() == 0 || passwd.length() == 0) {
      System.err.print("No field should be empty");
      this.getServletContext().getRequestDispatcher("/signin.jsp?e=2").forward(request, response);
    } else {
      try {
        user = db.getUser(mail, passwd);
        if (user != null) {
          HttpSession session = request.getSession();
          session.setAttribute("user", user);
          session.setAttribute("name", user.getFname());

          this.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
        } else {
          System.err.print("Wrong password or email");
          this.getServletContext()
              .getRequestDispatcher("/signin.jsp?e=1")
              .forward(request, response);
        }
      } catch (BiorganSqlException e) {
        e.printStackTrace();
      }
    }
  }
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, NamingException, SQLException {

    try {
      HttpSession session = request.getSession(true);
      String usuid = "";
      // usuario encryptado
      String usuarioEncriptado = (request.getParameter("xphsumf"));
      String modulo = (request.getParameter("ldmjcgd"));
      usuid = segUsuarioFacade.p_decript_palabra(usuarioEncriptado);
      // llama a la vista de usuarios donde se encuentra integrada
      // la información
      VUsuariosClasif vUsuariosClasif = vUsuariosClasifFacade.find(new BigDecimal(usuid));
      session.setAttribute("vUsuariosClasif", vUsuariosClasif);
      session.setAttribute("modulo", modulo);
      // refirecciona a la primera página del módulo

      String usuario = "";

      session.setAttribute("usuarioDB", vUsuariosClasif.getPerCodigo());
      session.setAttribute("perfilDB", "");
      session.setAttribute("usuarioBase", "");
      String perfil = "";
      response.sendRedirect("faces/template/Template.xhtml");

    } catch (SQLException | NamingException | NumberFormatException e) {
      System.out.println("e.getLocalizedMessage() = " + e.getLocalizedMessage());
    }
  }
  @RequestMapping(value = "login", method = RequestMethod.POST)
  public String doLogin(
      HttpServletRequest request,
      HttpSession session,
      @Valid LoginModel loginModel,
      BindingResult result,
      RedirectAttributes redirectAttrs) {
    if (result.hasErrors()) {
      return "login";
    }
    UserSessionModel userSession = new UserSessionModel();
    userSession.setUserId(loginModel.getSubject().getUserId());
    userSession.setToken(loginModel.getSubject().getSsoToken().getToken());
    userSession.setLogin(loginModel.getSubject().getPrincipal().trim());
    userSession.setDomainId(loginModel.getDomainId());

    session.setAttribute(CommonWebConstant.userSession.name(), userSession);
    // get the menus that the user has permissions too
    List<Menu> menuList =
        navigationDataService
            .menuGroupByUser(rootMenu, loginModel.getSubject().getUserId(), "en")
            .getMenuList();
    session.setAttribute("permissions", menuList);

    return "redirect:secure/dashboard";
  }
  @RequestMapping(value = "/rest-caixa/", method = RequestMethod.POST)
  public ResponseEntity<String> createCaixa(@RequestBody Caixa caixa, HttpSession session) {
    msg = "";
    caixaDao = new CaixaDao();
    System.out.println(
        "gastoRecebimento : "
            + caixa.getGastoRecebimento()
            + "\nencomendaId "
            + caixa.getEncomendaId()
            + "\nDataTransacao "
            + caixa.getDataTransacao()
            + " - insere no Dao"
            + "\nValor "
            + caixa.getValor()
            + "\nForma "
            + caixa.getForma());

    try {
      if (caixaDao.inserir(caixa)) {
        msg = "ok";
        session.setAttribute("respostaCaixa", msg);
      } else {
        msg = "erro";
        session.setAttribute("respostaCaixa", msg);
      }
    } catch (Exception e) {
      // Auto-generated catch block
      e.printStackTrace();
    }
    return new ResponseEntity<String>(msg, HttpStatus.OK);
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // get all zipcodes
    System.out.println("Reached");
    List<Integer> l = new DAOOrderToBillOracle().getAllZipcodes();
    System.out.println("zipcodes" + l.toString());

    request.setAttribute("l", l);

    //
    DAOOrderToBillOracle dest = new DAOOrderToBillOracle();
    System.out.println("order key " + request.getAttribute("orderKey"));
    Order order = dest.getOrderDetails((int) request.getAttribute("orderKey"));

    // ad-hoc
    // Order order = dest.getOrderDetails(1);

    System.out.println("Hey order" + order);

    System.out.println("order cust id" + order.getCustomerId());
    System.out.println("Service Address Id: " + dest.getServiceAddressId(order.getCustomerId()));
    int dzip = dest.getZipcode(dest.getServiceAddressId(order.getCustomerId()));
    System.out.println("dzip " + dzip);
    request.setAttribute("dzip", dzip);

    List<String> ddevice = dest.getDeviceIdsInZipcode(dzip);
    System.out.println("ddevic e ids in zipcode " + ddevice);

    HttpSession hs = request.getSession();
    hs.setAttribute("ddevice", ddevice);
    hs.setAttribute("order", order);

    RequestDispatcher rd = request.getRequestDispatcher("AddOrder.jsp");
    rd.forward(request, response);
  }
  /**
   * @param mapping - mapping
   * @param form - ActionForm
   * @param request - HttpServletRequest object
   * @param response - HttpServletResponse
   * @return ActionForward
   * @throws Exception - Exception
   */
  @Override
  protected ActionForward executeAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    final AnnotationForm annotationForm = (AnnotationForm) form;
    // Get static entity id and store in cache
    String staticEntityId = annotationForm.getSelectedStaticEntityId();
    String[] conditions = new String[] {"All"};

    if (annotationForm.getConditionVal() != null) {
      conditions = annotationForm.getConditionVal();
    }
    if (staticEntityId == null) {
      staticEntityId = request.getParameter("staticEntityId");
    }
    final HttpSession session = request.getSession();
    session.setAttribute(AnnotationConstants.SELECTED_STATIC_ENTITYID, staticEntityId);
    session.setAttribute(AnnotationConstants.SELECTED_STATIC_RECORDID, conditions);

    // Get Dynamic extensions URL
    final String dynamicExtensionsURL = this.getDynamicExtensionsURL(request);
    // Set as request attribute
    request.setAttribute(AnnotationConstants.DYNAMIC_EXTN_URL_ATTRIB, dynamicExtensionsURL);
    return mapping.findForward(Constants.SUCCESS);
  }
Example #12
0
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    @SuppressWarnings("unchecked")
    Map<String, String[]> params = req.getParameterMap();

    HttpSession session = req.getSession(true);
    session.setAttribute(LANG, "en"); // Defaults to English //$NON-NLS-1$

    if (params.containsKey("lang")) { // $NON-NLS-1$
      String lang = params.get("lang")[0]; // $NON-NLS-1$
      Messages.setLang(lang);
      if (this.availableLanguages.contains(lang)) {
        session.setAttribute(LANG, lang);
        resp.getWriter()
            .print(
                Messages.getString("localeservlet.lang_set_to")
                    + lang
                    + "'"); //$NON-NLS-1$ //$NON-NLS-2$
      } else {
        resp.sendError(
            HttpServletResponse.SC_BAD_REQUEST,
            Messages.getString("localeservlet.lang_not_available")); // $NON-NLS-1$
      }
    } else {
      resp.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          Messages.getString("localeservlet.not_lang_parameter") // $NON-NLS-1$
              + this.availableLanguages.toString());
    }
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {

    try {

      // System.out.println("Invoke Search User Servlet.......");
      List userDetails = new ArrayList();

      UserMasterBean userMasterBean = new UserMasterBean();
      userMasterBean.setUserName(request.getParameter("un"));
      userDetails = UserMasterDAO.findSelectedUser(userMasterBean);

      HttpSession session = request.getSession(true);

      if (userDetails != null && userDetails.size() > 0) {
        System.out.println("User Details Found....");
        session.setAttribute("UserInfo", userDetails);
        response.sendRedirect("jsp/SelectedUserListing.jsp");
      } else {
        System.out.println("User Does Not Exist...");
        session.setAttribute("userCreationStatus", "User Does Not Exist...");
        response.sendRedirect("jsp/UserStatus.jsp");
      }

    } catch (Throwable theException) {
      System.out.println(theException);
    }
  }
Example #14
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html; charset=Shift_JIS");
    PrintWriter out = response.getWriter();

    String user = request.getParameter("user");
    String pass = request.getParameter("pass");

    HttpSession session = request.getSession(true);

    boolean check = authUser(user, pass);
    if (check) {
      /*認証済みにセット*/
      session.setAttribute("login", "OK");

      /*本来のリンク先へ飛ばす*/
      String target = (String) session.getAttribute("target");
      response.sendRedirect(target);
    } else {
      /*認証失敗したら、ログイン画面に戻す*/
      session.setAttribute("status", "Not Auth");
      response.sendRedirect("./Login2");
    }
  }
 @Override
 public void getAllSessionAttributes(String appSessionId)
     throws SpartanPersistenceException, Exception {
   HttpServletRequest request =
       ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
   HttpSession session = request.getSession();
   // Iterate JSONObject
   List<SessionDataInterface> sessionData =
       loginSessionDataRepository.findByAppSessionId(appSessionId);
   for (SessionDataInterface sessiondata : sessionData) {
     if (sessiondata.getBooleanValue() != null) {
       session.setAttribute(sessiondata.getSessionKey(), sessiondata.getBooleanValue());
     }
     if (sessiondata.getNumberValue() != null) {
       session.setAttribute(sessiondata.getSessionKey(), sessiondata.getNumberValue());
     }
     if (sessiondata.getDateTimeValue() != null) {
       session.setAttribute(sessiondata.getSessionKey(), sessiondata.getDateTimeValue());
     }
     if (sessiondata.getJsonValue() != null) {
       session.setAttribute(sessiondata.getSessionKey(), sessiondata.getJsonValue());
     }
     if (sessiondata.getStringValue() != null) {
       session.setAttribute(sessiondata.getSessionKey(), sessiondata.getStringValue());
     }
   }
 }
  public static void updateLanguage(HttpServletRequest request, HttpServletResponse response) {

    String languageId =
        ParamUtil.getString(request, "companyLocale", PropsValues.COMPANY_DEFAULT_LOCALE);

    Locale locale = LocaleUtil.fromLanguageId(languageId);

    List<Locale> availableLocales = ListUtil.fromArray(LanguageUtil.getAvailableLocales());

    if (!availableLocales.contains(locale)) {
      return;
    }

    HttpSession session = request.getSession();

    session.setAttribute(Globals.LOCALE_KEY, locale);
    session.setAttribute(WebKeys.SETUP_WIZARD_DEFAULT_LOCALE, languageId);

    LanguageUtil.updateCookie(request, response, locale);

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    themeDisplay.setLanguageId(languageId);
    themeDisplay.setLocale(locale);
  }
 /**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
  *
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   HttpSession signIn = request.getSession(true);
   signIn.setAttribute("username", "");
   signIn.setAttribute("role", "");
   request.getRequestDispatcher("/Home.jsp").forward(request, response);
 }
  public static void updateSetup(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    UnicodeProperties unicodeProperties =
        PropertiesParamUtil.getProperties(request, _PROPERTIES_PREFIX);

    unicodeProperties.setProperty(
        PropsKeys.LIFERAY_HOME, SystemProperties.get(PropsKeys.LIFERAY_HOME));

    boolean databaseConfigured = _isDatabaseConfigured(unicodeProperties);

    _processDatabaseProperties(request, unicodeProperties, databaseConfigured);

    updateLanguage(request, response);

    unicodeProperties.put(PropsKeys.SETUP_WIZARD_ENABLED, String.valueOf(false));

    PropsUtil.addProperties(unicodeProperties);

    if (!databaseConfigured) {
      _reloadServletContext(request, unicodeProperties);
    }

    _updateCompany(request);
    _updateAdminUser(request, unicodeProperties);

    _initPlugins();

    boolean propertiesFileCreated = _writePropertiesFile(unicodeProperties);

    HttpSession session = request.getSession();

    session.setAttribute(WebKeys.SETUP_WIZARD_PROPERTIES, unicodeProperties);
    session.setAttribute(WebKeys.SETUP_WIZARD_PROPERTIES_FILE_CREATED, propertiesFileCreated);
  }
  @Override
  public ModelAndView execute(HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mv = new ModelAndView();
    BoardService service = BoardService.getInstance();
    ArrayList accList = new ArrayList();
    String acc_id = request.getParameter("acc_id");
    boolean isRemove = false;
    try {
      isRemove = service.removeAcc(Integer.parseInt(acc_id));
      accList = service.getLoninInfo();
      HttpSession session = request.getSession();

      if (isRemove) {
        // 삭제 성공 --> accountDel.jsp 이동
        mv.setPath("DispatcherServlet?command=home");
      } else {
        session.setAttribute("isRemove", false);

        mv.setPath("accountDel.jsp");
      }
      session.setAttribute("loginInfo", accList);

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

    return mv;
  }
Example #20
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    // doGet(request, response);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession(true);
    String user = (String) session.getAttribute("currentuser");

    String plname = request.getParameter("plname");
    String ispublic = request.getParameter("secure");
    String[] tracks = request.getParameterValues("track");

    if (tracks.length <= 0) {
      session.setAttribute("playlistdata", "Invalid");
      response.sendRedirect("newplaylist.jsp");
    }

    if (ispublic == "") {
      session.setAttribute("playlistdata", "checkradio");
      response.sendRedirect("newplaylist.jsp");
    } else {
      if (HomepageAct.addPlaylist(user, tracks, plname, ispublic) == 0) {
        session.setAttribute("datavalid", "Valid");
        response.sendRedirect("myplaylist.jsp");
      } else {
        out.println("Sorry! there was some error during creating the playlist Please try again.");
        response.sendRedirect("newplaylist.jsp");
      }
    }
  }
Example #21
0
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    HttpSession session = request.getSession();
    InternalStaff employee = (InternalStaff) session.getAttribute("user");
    InternalStaff changedEmployee = null;
    InternalStaff admin = null;
    String userId = request.getParameter("userId");
    String adminParam = request.getParameter("admin");

    if (userId != null) {
      changedEmployee = InternalStaffDao.getInternalAuthorByStaffId(Integer.parseInt(userId));
      System.out.println(changedEmployee.getEmployee().getName());
      session.removeAttribute("user");
      session.setAttribute("user", changedEmployee);
      response.sendRedirect("Home.jsp");

    } else if (adminParam != null && adminParam.equals("yes")) {
      session.removeAttribute("user");
      admin = InternalStaffDao.getAdmin();
      session.setAttribute("user", admin);
      response.sendRedirect("Home.jsp");

    } else if (employee != null) {
      response.sendRedirect("Home.jsp");
    } else response.sendRedirect("login.jsp");
  }
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response) {
   try (InputStream inputStream =
       getClass().getClassLoader().getResourceAsStream("Aconfig/adminconfig.properties")) {
     String S_error = "";
     HttpSession session;
     String _uname = request.getParameter("adusnam");
     String _pass = request.getParameter("adpass");
     Properties properties = new Properties();
     if (inputStream != null) {
       properties.load(inputStream);
     }
     if (_uname.equals(properties.get("adus")) && _pass.equals(properties.get("adpas"))) {
       session = request.getSession(true);
       session.setAttribute("username", _uname);
       response.sendRedirect("WriteConfig");
     } else {
       session = request.getSession(true);
       session.setAttribute("status", "The username and password did not match");
       response.sendRedirect("AdminAuth");
     }
   } catch (IOException e) {
     Logger.getLogger(AdminAuthServlet.class.getName()).log(Level.SEVERE, null, e);
     response.setStatus(500);
   }
 }
  /*
   * score the previous question and add its
   */
  void scorePreviousAnswer(HttpSession session, HttpServletRequest request) {
    Integer previousQuestionIndex =
        (Integer) session.getAttribute(Constants.session_currentQuestionIndex);

    Integer score = (Integer) session.getAttribute(Constants.session_currentScore);
    Question prevQuestion = (Question) session.getAttribute(Constants.session_currentQuestion);
    if (prevQuestion != null) score += prevQuestion.scoreAnswer(request);

    if (((Quiz) session.getAttribute(Constants.session_currentQuiz)).immediateFeedback) {
      if (prevQuestion != null)
        session.setAttribute(Constants.session_previousFeedback, prevQuestion.getFeedback(request));
    }
    String allFeedback = (String) session.getAttribute(Constants.session_allFeedback);

    ArrayList<Feedback> allFeedbacks =
        (ArrayList<Feedback>) session.getAttribute(Constants.session_allFeedbackObjs);
    if (allFeedbacks == null) allFeedbacks = new ArrayList<Feedback>();
    if (prevQuestion != null) {
      Feedback f =
          new Feedback(
              prevQuestion.displayQuestion(),
              prevQuestion.getFeedback(request),
              prevQuestion.scoreAnswer(request),
              previousQuestionIndex);
      allFeedbacks.add(f);
      session.setAttribute(Constants.session_previousFeedbackObj, f);
    }
    session.setAttribute(Constants.session_allFeedbackObjs, allFeedbacks);

    if (allFeedback != null) allFeedback += "<br><br> " + prevQuestion.getFeedback(request);
    else if (prevQuestion != null) allFeedback = "<br><br> " + prevQuestion.getFeedback(request);
    else allFeedback = "";
    session.setAttribute(Constants.session_allFeedback, allFeedback);
    session.setAttribute(Constants.session_currentScore, score);
  }
  /**
   * Зарегестрировать
   *
   * @param registrationInfo - Информация о пользователе и его организации
   * @return - отображение запрашиваемого ресурса
   * @throws UnsupportedEncodingException - ошибка о не правильной раскодировке
   */
  @RequestMapping(method = RequestMethod.POST)
  public String registration(@Valid RegistrationInfo registrationInfo, BindingResult result)
      throws UnsupportedEncodingException {

    HttpSession session = getSession();

    // Получаем сообщения об ошибках, если они есть
    List<ObjectError> erorList = result.getAllErrors();
    List<String> erorMessageList = new ArrayList<>();
    try {
      if (!erorList.isEmpty()) {
        erorMessageList = CompanyController.getListMessageForEror(erorList);
        session.setAttribute("uncorrectRegistrationUserCompany", registrationInfo);
        session.setAttribute("listErorRegistration", erorMessageList);
        return "redirect:/registration";
      }

      OrganizationInfo regestratingCompany = userService.registration(registrationInfo);

      session.removeAttribute("uncorrectRegistrationUserCompany");
      session.removeAttribute("listErorRegistration");
      return "redirect:/login";

    } catch (Exception e) {
      erorMessageList.add("Системная ошибка!");
      session.setAttribute("listErorRegistration", erorMessageList);
      session.setAttribute("uncorrectRegistrationUserCompany", registrationInfo);
      return "redirect:/registration";
    }
  }
  /**
   * Default Method of this controller. Logged in teams are redirected to this controller.
   *
   * @param request
   * @param response
   * @return
   */
  public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    session.setAttribute("CURRENT_LINK", Constants.HOME_LINK);
    int currentPeriod = (Integer) session.getAttribute(Constants.CURRENT_PERIOD);
    Team loggedInTeamObj = (Team) session.getAttribute(Constants.TEAM_OBJECT);

    String marketShareChartString = bizlabsJDBCDao.getMarketShareDataString(currentPeriod);
    session.setAttribute("MARKET_SHARE", marketShareChartString);
    System.out.println("************* Market share: " + marketShareChartString);

    String stockPriceIndexChartString =
        bizlabsJDBCDao.getStockPriceIndexDataString(currentPeriod, loggedInTeamObj);
    session.setAttribute("STOCK_PRICE_INDEX", stockPriceIndexChartString);
    System.out.println("************* Stock Price Index: " + stockPriceIndexChartString);

    String teamRevenueAndProfitChartString =
        bizlabsJDBCDao.getRevenueAndProfitDataString(currentPeriod, loggedInTeamObj);
    session.setAttribute("TEAM_REVENUE_AND_PROFIT", teamRevenueAndProfitChartString);
    System.out.println("************* Team Revenue and Profit: " + teamRevenueAndProfitChartString);

    String brandGrowthMatrixChartString = bizlabsJDBCDao.getGrowthMatrixDataString(currentPeriod);
    session.setAttribute("BRAND_GROWTH_MATRIX", brandGrowthMatrixChartString);
    System.out.println("************* Brand Growth Matrix: " + brandGrowthMatrixChartString);

    ModelAndView mav = new ModelAndView("teamHome");
    return mav;
  }
Example #26
0
  public String login() {

    user = auth.authentifier(username, password, statut);

    if (user != null) {

      /*
       * ExternalContext ec =
       * FacesContext.getCurrentInstance().getExternalContext(); try {
       * ec.redirect(ec.getRequestContextPath() + "/Acceuil.xhtml"); }
       * catch (IOException e) { // TODO Auto-generated catch block
       * System.out.print(e.getMessage()); e.printStackTrace(); }
       */
      session.setAttribute("user", user);
      session.setAttribute("statut", statut);
      setConnecte(true);

      session.setAttribute("connecte", connecte);
      return "Acceuil";
      /*
       * if (statut.equals("etudiant")) {
       *
       * return "AcceuilEt"; } else { return "AcceuilCh"; }
       */
    } else {
      setConnecte(false);
      FacesMessage message = new FacesMessage("your login  is unsuccessfull !");
      FacesContext.getCurrentInstance().addMessage(null, message);
    }

    return "";
  }
  /**
   * Looks for existing user object in session scope. If user object exists then goes to download
   * page.
   *
   * <p>If user does not exist then checks all cookies to see if cookie name emailCookie exists. If
   * Cookie exists then gets email value from Cookie and looks up the emailAddres in a file that on
   * OpenShift lives in the folder identified by the folder OPENSHIFT_DATA_DIR. If not OpenShift
   * then file will live in WEB-INF. The reason for difference is that OpenShift cannot write to any
   * web apps folder. If email address is found and the assumption is that it will be then User
   * object is created and url is constructed to go to proper album page.
   *
   * <p>If there is no cookie then control is sent to register.jsp *
   *
   * @param request
   * @param response
   * @return
   */
  private String checkUser(HttpServletRequest request, HttpServletResponse response) {

    String productCode = request.getParameter("productCode");
    HttpSession session = request.getSession();
    session.setAttribute("productCode", productCode);
    User user = (User) session.getAttribute("user");

    String url;
    // if User object doesn't exist, check email cookie
    if (user == null) {
      Cookie[] cookies = request.getCookies();
      String emailAddress = CookieUtil.getCookieValue(cookies, "emailCookie");

      // if cookie doesn't exist, go to Registration page
      if (emailAddress == null || emailAddress.equals("")) {
        url = "/register.jsp";
      } // if cookie exists, create User object and go to Downloads page
      else {
        // ServletContext sc = getServletContext();
        // String path = sc.getRealPath("/WEB-INF/EmailList.txt");

        String path = this.getActualFile();
        System.out.println("Path: " + path);
        user = UserIO.getUser(emailAddress, path);
        session.setAttribute("user", user);
        url = "/" + productCode + "_download.jsp";
      }
    } // if User object exists, go to Downloads page
    else {
      url = "/" + productCode + "_download.jsp";
    }
    return url;
  }
Example #28
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession(true); // Get client session

    String email = request.getParameter("email");
    String password = request.getParameter("password");

    if (!validUser(request, email, password)) {
      session.setAttribute("login", false);
      response.sendRedirect("/project2_10/login.jsp");
    } else {
      session.setAttribute("login", true);
      session = request.getSession();
      session.setAttribute("user.login", email);
      ShoppingCart.initCart(request, response);
      try {
        String target = (String) session.getAttribute("user.dest");
        // retrieve address if user goes to a page w/o logging in
        if (target != null) {
          session.removeAttribute("user.dest");
          // redirect to page the user was originally trying to go to
          response.sendRedirect(target);
          return;
        }
      } catch (Exception ignored) {
      }

      // Couldn't redirect to the target. Redirect to the site's homepage.
      response.sendRedirect("/project2_10/");
    }
  }
Example #29
0
  public void registroUsuario() {
    try {

      dusu = cusu.registrarUsuario(nombre, apellido, nick, password, email, fechaNacimiento, file);
      if (dusu != null) {
        logueado = true;
        HttpSession session = SesionBean.getSession();
        session.setAttribute("nickname", nick);
        session.setAttribute("dataUsuario", dusu);
        DataUsuario dataUsuario = (DataUsuario) session.getAttribute("dataUsuario");
        String emailEnviar = dataUsuario.getEmail();
        session.setAttribute("AVs", cusu.mostrarListaAv(nick));
        Url.redireccionarURL("usuario_sapo");
        Mensajeria enviar = new Mensajeria();
        String mensaje =
            "Bienvenido a SAPo "
                + dataUsuario.getNombre()
                + " "
                + dataUsuario.getApellido()
                + "Agradecemos su preferencia";
        enviar.enviarCorreo(emailEnviar, "SAPo - Bienvenido al Sistema de Inventarios", mensaje);
      } else {
        Url.redireccionarURL("error");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public String addSerpsKeywordGoal() {

    objRequest = ServletActionContext.getRequest();

    objSession = objRequest.getSession();
    int i = 0;
    if (objSession.getAttribute("customerID") != null) {
      Integer keywordID = Integer.parseInt(keywordId);
      System.out.println("keywordID = " + keywordID);
      Integer goalRank = Integer.parseInt(goalrank);
      System.out.println("goalRank = " + goalRank);
      System.out.println("dategoal = " + dategoal);
      if (goalRank < 1 || goalRank > 502) {
        i = 2;
      } else {
        i = objKeywordsService.setSerpsKeywordGoal(keywordID, goalRank, dategoal);
      }
    }
    if (i == 1) {
      message = "Goal Added";
      objSession.setAttribute("message", message);
      return SUCCESS;
    } else if (i == 2) {
      message = "Improper Rank!! Set Valid Rank !";
      objSession.setAttribute("message", message);
      return SUCCESS;
    } else {
      message = "Goal has not been added";
      objSession.setAttribute("message", message);
      return SUCCESS;
    }
  }