public ActionForward execute(
      ActionMapping actionMapping,
      ActionForm actionForm,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse) {
    // Seta o caminho de retorno
    ActionForward retorno = actionMapping.findForward("exibirManterLeiturasTemeletriaAction");

    HttpSession sessao = httpServletRequest.getSession(false);

    FiltrarLeiturasTelemetriaHelper helper =
        (FiltrarLeiturasTelemetriaHelper) sessao.getAttribute("filtro");

    // 1º Passo - Pegar o total de registros através de um count da consulta que aparecerá na tela
    Integer qtdTotalRegistros = (Integer) sessao.getAttribute("qtdTotalRegistros");

    // 2º Passo - Chamar a função de Paginação passando o total de registros
    retorno = this.controlarPaginacao(httpServletRequest, retorno, qtdTotalRegistros);
    helper.setNumeroPagina((Integer) httpServletRequest.getAttribute("numeroPaginasPesquisa"));

    // 3º Passo - Obter a coleção da consulta que aparecerá na tela passando o numero de paginas
    Collection<TelemetriaMovReg> colecaoTelemetriaMovReg =
        this.getFachada().filtrarLeiturasTelemetria(helper);

    sessao.setAttribute("colecao", colecaoTelemetriaMovReg);

    return retorno;
  }
  /**
   * 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;
  }
  public String[] getSessionHTML(HttpSession session, HttpServletRequest request)
      throws ServletException, IOException {

    String user = null;
    String group = null;
    String userName = null;
    String groupname = null;
    String redirect = "";
    try {

      redirect = UserRecord;
      if (session.getAttribute("user") == null) {

        session.invalidate();
        request.getRequestDispatcher(redirect).include(request, response);
      } else {
        user = (String) session.getAttribute("user");
        group = (String) session.getAttribute("group");
      }
      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("user")) sess[0] = cookie.getValue();
          if (cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
          if (cookie.getName().equals("group")) sess[1] = cookie.getValue();
          break;
        }
      }

    } catch (NullPointerException n) {
      n.printStackTrace();
    }
    return sess;
  }
 private void LoadMenu2(String menuparentid) {
   HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
   HttpSession session = request.getSession();
   String contextPath = request.getContextPath();
   int userable = ((LogonForm) session.getAttribute("logonuser")).getUserable();
   JspWriter jspwriter = pageContext.getOut();
   String selectmenu2 = (String) session.getAttribute("selectmenu2");
   if (selectmenu2 == null) selectmenu2 = "";
   ArrayList menulist2 = new ArrayList();
   String sql =
       "select * from "
           + Content.TB_MENU
           + " where "
           + Content.MENUPARENTID
           + "='"
           + menuparentid
           + "' and "
           + Content.MENUJIBIE
           + "='2' and "
           + Content.USERABLE
           + " <= "
           + userable
           + " order by "
           + Content.MENUORDER;
   DB db = new DB();
   menulist2 = db.getmenulist(sql);
   try {
     if (menulist2 != null && menulist2.size() != 0) {
       jspwriter.write(
           "<tr><td align='center' colspan='2' style='padding-top:5;padding-bottom:5;padding-left:5;padding-right:5' background='"
               + contextPath
               + "/image/menu2b.jpg'><table border='0' width='187' cellpadding='0' cellspacing='1' bordercolor='#6DB0CB' rules='none'>");
       for (int i = 0; i < menulist2.size(); i++) {
         MenuSigle menu2sigle = (MenuSigle) menulist2.get(i);
         if (selectmenu2.equals((menu2sigle).getMenuid())) {
           jspwriter.write(
               "<tr bgcolor='#FFFCED'><td height='28' style='text-indent:20' valign='bottom' nowrap>◆<b>&nbsp;<a href='"
                   + contextPath
                   + menu2sigle.getMenuaction()
                   + "'>"
                   + menu2sigle.getMenuname()
                   + "</b></td></tr>");
           session.setAttribute("pagepath", menu2sigle.getMenuaction());
           LoadMenu3(menu2sigle.getMenuid());
         } else {
           jspwriter.write(
               "<tr bgcolor='#FFFCED'><td height='28' style='text-indent:20' valign='bottom' nowrap>◆&nbsp;<a href='"
                   + contextPath
                   + menu2sigle.getMenuaction()
                   + "'>"
                   + menu2sigle.getMenuname()
                   + "</a></td></tr>");
         }
       }
       jspwriter.write("</table></td></tr>");
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  @RequestMapping(value = "/buildOrder.html", method = RequestMethod.GET)
  public ModelAndView get(HttpServletRequest request) {

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Redirecting to current order details page");
    }

    HttpSession session = request.getSession(true);
    String orderrestaurantid = (String) session.getAttribute("orderrestaurantid");
    String restaurantid = (String) session.getAttribute("restaurantid");
    Search search = (Search) session.getAttribute("search");

    if (orderrestaurantid != null) {
      restaurantid = orderrestaurantid;
    }

    if (restaurantid == null) {
      if (search == null) {
        return new ModelAndView("redirect:/home.html", null);
      } else {
        return new ModelAndView("redirect:/search.html" + search.getQueryString());
      }
    } else {
      Restaurant restaurant = restaurantRepository.findByRestaurantId(restaurantid);
      return new ModelAndView("redirect:/" + restaurant.getUrl());
    }
  }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      HttpSession session = request.getSession(false);
      Long bierId = Long.parseLong(request.getParameter("bierId"));
      if (session != null) {
        request.setAttribute("mandje", session.getAttribute("mandje"));
        @SuppressWarnings("unchecked")
        Map<Long, Integer> mandje = (Map<Long, Integer>) session.getAttribute("mandje");
        if (mandje.containsKey(bierId)) {
          request.setAttribute(
              "bierAlInMandje", "Bier is al in mandje. Nieuwe waarde overschrijft oude.");
          request.setAttribute("oudAantal", mandje.get(bierId));
        }
      }
      if (bierId < 0) {
        request.setAttribute("fout", "bierNr moet een positief getal zijn.");
      } else {
        request.setAttribute("bier", bierService.readBierSoortAndBrouwer(bierId));
      }
    } catch (NumberFormatException ex) {
      request.setAttribute("fout", "BierNr mag niet leeg zijn. Mag enkel cijfers bevatten.");
    } catch (NoResultException ex) {

    }
    request.getRequestDispatcher(VIEW).forward(request, response);
  }
 @Override
 public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory)
     throws ServerAuthException {
   HttpServletRequest request = ((HttpServletRequest) req);
   if (getAdapterConfig().isBearerOnly() == false
       && request.getQueryString() != null
       && request.getQueryString().contains("code=")) {
     // we receive a code as part of the query string that is returned by OAuth
     // but only assume control is this is not bearer only!
     mandatory = true;
   } else if (request.getHeaders("Authorization").hasMoreElements()) {
     // we receive Authorization, might be Bearer or Basic Auth (both supported by Keycloak)
     mandatory = true;
   }
   HttpSession session = ((HttpServletRequest) req).getSession(false);
   if (session != null
       && session.getAttribute(JettyAdapterSessionStore.CACHED_FORM_PARAMETERS) != null) {
     // this is a redirect after the code has been received for a FORM
     mandatory = true;
   } else if (session != null
       && session.getAttribute(KeycloakSecurityContext.class.getName()) != null) {
     // there is an existing authentication in the session, use it
     mandatory = true;
   }
   Authentication authentication = super.validateRequest(req, res, mandatory);
   if (authentication instanceof DeferredAuthentication) {
     // resolving of a deferred authentication later will otherwise lead to a NullPointerException
     authentication = null;
   }
   return authentication;
 }
  @Test
  public void testUpdatePasswordBadCurrentPassword() throws Exception {
    String username = "******";
    String currentPassword = "******";
    String password = "******";

    mockMvc =
        MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    // user must ge logged in
    HttpSession session =
        mockMvc
            .perform(
                post("/j_security_check").param("j_username", "admin").param("j_password", "admin"))
            .andExpect(status().is(HttpStatus.FOUND.value()))
            .andExpect(redirectedUrl("/"))
            .andReturn()
            .getRequest()
            .getSession();

    mockMvc
        .perform(
            post("/updatePassword")
                .session((MockHttpSession) session)
                .param("username", username)
                .param("currentPassword", currentPassword)
                .param("password", password))
        .andExpect(status().isOk());

    assertNull(session.getAttribute(BaseFormController.MESSAGES_KEY));
    assertNotNull(session.getAttribute(BaseFormController.ERRORS_MESSAGES_KEY));
  }
 @Override
 public String execute(HttpServletRequest request, HttpServletResponse response) {
   String login = request.getParameter("name");
   String password = request.getParameter("password");
   Authorization au = new Authorization();
   au.setLogin(login);
   au.setPassword(password);
   DaoFactory factory = DaoFactory.getDaoFactory();
   AuthorizationDao udao = factory.getAuthorizationDao();
   StaffDao sdao = factory.getStaffDao();
   DepartmentDao ddao = factory.getDepartmentDao();
   PatientDao pdao = factory.getPatientDao();
   if (udao.isAuthorization(au)) {
     HttpSession session = request.getSession(true);
     Authorization forSession = udao.readByLogin(login);
     Staff forAccess = sdao.readById(forSession.getStaff());
     String fa = forAccess.getSpecialization();
     session.setAttribute("access", fa);
     if (session.getAttribute("access").equals("admin")) {
       List<Department> departments = ddao.getAllDepartments();
       request.setAttribute("departments", departments);
       return "/views/adminUserInformation.jsp";
     } else if (session.getAttribute("access").equals("doctor")) {
       return "/views/doctorStartPage.html";
     } else if (session.getAttribute("access").equals("nurse")) {
       List<Patient> patients = pdao.getAllPatients();
       request.setAttribute("patients", patients);
       return "/views/nurseStart.jsp";
     } else {
       return "/views/test.html";
     }
   } else {
     return "../index.html";
   }
 }
  public void addFriend(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, Exception {

    HttpSession session = request.getSession();
    userLoggedIn = (User) session.getAttribute("login");
    userProfile = (User) session.getAttribute("profileUser");

    XmlManager manager = new XmlManager();
    manager.marshall(userLoggedIn);

    String addFriend =
        new FriendWS2_Service()
            .getFriendWS2Port()
            .addFriend(
                manager.convertXMLFileToString(WEBUSER_XML),
                Integer.toString(userProfile.getIduser()));

    if (addFriend.equalsIgnoreCase("isFriend")) {
      this.sendMailRequest(userProfile);
      session.setAttribute("status", (Character) 'y');
    } else if (addFriend.equalsIgnoreCase("isPending"))
      session.setAttribute("status", (Character) 'p');
    else session.setAttribute("status", (Character) 'n');

    session.setAttribute("profileUser", userLoggedIn);
    response.sendRedirect("/Phasebook-war/jsp/pending-requests.jsp");
  }
Example #11
0
 /**
  * Method to create a role
  *
  * @param roleData : data of role in String(JSON String)
  * @param request : object of HttpServletRequest
  * @return ResponseEntity<Void> with http status code if user is not logged in then return
  *     HttpStatus.FORBIDDEN else if user is not Admin the return HttpStatus.UNAUTHORIZED else if
  *     role already exists then return HttpStatus.CONFLICT else return HttpStatus.OK
  * @throws JSONException
  */
 @RequestMapping(value = "/createRole", method = RequestMethod.POST)
 public ResponseEntity<Void> saveRole(@RequestBody String roleData, HttpServletRequest request)
     throws JSONException {
   HttpSession session = request.getSession(false);
   if (session == null || session.getAttribute("user") == null) {
     return new ResponseEntity<Void>(HttpStatus.FORBIDDEN);
   }
   if (roleData == null) {
     return new ResponseEntity<Void>(HttpStatus.UNAUTHORIZED);
   }
   JSONObject jsonObj = new JSONObject(roleData);
   User user = (User) session.getAttribute("user");
   if (user.isAdmin()) {
     String roleName = jsonObj.getString("name");
     Role role = roleService.getRoleByName(roleName);
     if (role == null) {
       role = new Role();
       role.setName(roleName);
       roleService.createRole(role);
       return new ResponseEntity<Void>(HttpStatus.OK);
     } else {
       return new ResponseEntity<Void>(HttpStatus.CONFLICT);
     }
   } else {
     return new ResponseEntity<Void>(HttpStatus.UNAUTHORIZED);
   }
 }
  // Check position for difference between new and current (in database)
  private List<String> crossCheckPosition(HttpServletRequest request) {
    List<String> newPositionList = new ArrayList();
    List<String> oldPositionList = new ArrayList();
    HttpSession session = request.getSession(true);
    String levelName = session.getAttribute("TempLevelName").toString();
    System.out.println("Level Name" + levelName);

    String departmentName = session.getAttribute("TempDepartmentName").toString();
    System.out.println("Department Name" + departmentName);
    String position;
    position = request.getParameter("positionName");

    // Count number of commas (breakpoint(s))
    int count = position.length() - position.replace(",", "").length();
    System.out.println("Count is " + count);
    String[] parts = position.split(",");

    for (int i = 0; i < count + 1; i++) {
      newPositionList.add(parts[i]);
      System.out.println("Position added" + parts[i]);
    }
    System.out.println("New Position Size is: " + newPositionList);

    try {
      System.out.println("Performing crossCheckPosition");
      oldPositionList = cabl.retrieveDepartmentPosition(levelName, departmentName);
      System.out.println("Old Position Size is " + oldPositionList.size());
      newPositionList.removeAll(oldPositionList);
      System.out.println("Difference" + newPositionList);
    } catch (Exception ex) {

    }

    return newPositionList;
  }
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   HttpSession session = request.getSession(false);
   if (session == null || session.getAttribute("klant") == null) {
     response.sendRedirect(String.format(LOGIN_REDIRECT, request.getContextPath()));
   } else {
     Klant klant = klantService.read(((Klant) session.getAttribute("klant")).getId());
     if (klant != null) {
       Set<InterfaceLijn> oud = new TreeSet<>();
       Set<InterfaceLijn> huidig = new TreeSet<>();
       for (InterfaceLijn lijn : klant.getReservaties()) {
         if (lijn.getOpvoering().getDatum().before(Calendar.getInstance().getTime())) {
           oud.add(lijn);
         } else {
           huidig.add(lijn);
         }
       }
       if (!oud.isEmpty()) {
         request.setAttribute("oud", oud);
       }
       if (!huidig.isEmpty()) {
         request.setAttribute("huidig", huidig);
       }
       session.setAttribute("klant", klant);
       request.getRequestDispatcher(VIEW).forward(request, response);
     }
   }
 }
Example #14
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    /* Check Login Status */
    request
        .getRequestDispatcher(
            "/components/CLS?user_type=faculty&firstTime=true&returnType=redirect")
        .include(request, response);
    if (response.isCommitted()) return; // CLS preempting
    /* Get Connection */
    HttpSession session = request.getSession();
    Connection conn = null;
    synchronized (session) {
      DBConnector dbcon = (DBConnector) session.getAttribute("dbcon"); // fetch

      if (dbcon == null) {
        dbcon = new DBConnector();
        session.setAttribute("dbcon", dbcon);
      }
      conn = dbcon.getConnection();
    }

    String query =
        "select B.class_id, "
            + "xmlserialize(content xmlelement (name \"day\", "
            + "				xmlattributes(A.d_id as \"d_id\"), "
            + "				xmlagg(xmlelement(name \"slot\", "
            + "						xmlattributes(A.no as \"no\"), "
            + "						xmlelement(name \"subject_name\", su.name), "
            + "						xmlelement(name \"teacher_name\", na.fname||' '|| na.mname||' '||na.lname), "
            + "						xmlelement(name \"infra_name\", in.name) ))) as clob) "
            + "from pietons.faculty fa, "
            + "xmltable('$c/personal_details' passing fa.personal_details as \"c\" "
            + "columns fname varchar(20) path './name/fname', "
            + "		mname varchar(20) path './name/mname', "
            + "		lname varchar(20) path './name/lname') as na, "
            + "pietons.subject su, pietons.infrastructure in, pietons.allocation B, "
            + "xmltable ('$d/schedule/day/slot' passing B.schedule as \"d\" "
            + "columns d_id varchar(2) path '../@d_id', "
            + "		subject_id int path './subject_id', "
            + "		no varchar(2) path './@no', "
            + "		teacher_id varchar(10) path './teacher_id', "
            + "		infra_id int path './infra_id') as A "
            + "where A.teacher_id = fa.gr_no and A.subject_id = su.id and A.infra_id=in.id and fa.gr_no=?"
            + "group by B.class_id, A.d_id";
    PreparedStatement ps = null;
    try {
      ps = conn.prepareStatement(query);
      ps.setString(1, session.getAttribute("user_id").toString());
      ResultSet rs = ps.executeQuery();
      PrintWriter out = response.getWriter();
      out.println(
          "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
              + "<?xml-stylesheet type=\"text/xsl\" href=\"/ITEA/components/tt.xsl\" ?>"
              + "<schedule>");
      while (rs.next()) out.println(rs.getString(2));
      out.println("</schedule>");
    } catch (SQLException e) {
      System.err.println(e.toString());
    }
  }
  public String getTokenValue(HttpServletRequest request, String uri) {
    String tokenValue = null;
    HttpSession session = request.getSession(false);

    if (session != null) {
      if (isTokenPerPageEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, String> pageTokens =
            (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

        if (pageTokens != null) {
          if (isTokenPerPagePrecreate()) {
            createPageToken(pageTokens, uri);
          }
          tokenValue = pageTokens.get(uri);
        }
      }

      if (tokenValue == null) {
        tokenValue = (String) session.getAttribute(getSessionKey());
      }
    }

    return tokenValue;
  }
Example #16
0
 /**
  * Retrieve the vip info
  *
  * @param model
  * @return
  */
 @RequestMapping(value = "/vi_userCenter")
 public String getInfo(Model modelmap, HttpSession httpSession, HttpServletResponse response) {
   String account = (String) httpSession.getAttribute("accountName");
   Integer flag = (Integer) httpSession.getAttribute("flag");
   AccountClient accountClient =
       accountClientDao.findClientByAccount(
           account); // For testing ...................................
   if (accountClient != null && flag != null && flag == Constant.account_client) {
     Map<String, Object> map = new HashMap<String, Object>();
     map.put("id", accountClient.getAccountClient());
     map.put("gender", accountClient.getSexClient());
     map.put("identity", accountClient.getIdentityCardNumber());
     map.put("mobilephone", accountClient.getPhoneClient());
     map.put("officephone", "无");
     map.put("email", accountClient.getEmailClient());
     map.put("address", accountClient.getAddressClient());
     map.put("sicknesshistory", accountClient.getSicknessHistory());
     map.put("salesman", "Unknown");
     map.put("name", accountClient.getAccountClient());
     modelmap.addAttribute("user", map);
   } else {
     modelmap.addAttribute("user", null);
   }
   return "/vip/vi_userCenter";
 }
Example #17
0
  /**
   * This is the action called from the Struts framework.
   *
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @throws java.lang.Exception
   * @return
   */
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    String defaultImage = "/images/profilepics/Chuirer.jpg";
    profile form2 = (profile) form;

    HttpSession ses = request.getSession();
    if (ses.getAttribute("usuarioLogueado") == null) {
      return mapping.findForward(NOEXISTE);
    }

    EnUsuario pro =
        (new DaUsuarios()).recuperaUsuario(ses.getAttribute("usuarioLogueado").toString());
    EnPeticiones peticiones = (new DaPeticiones()).recuperaPeticiones(pro.getUserName());
    form2.setUsername(pro.getUserName());
    form2.setDescripcion(pro.getDscripcion());
    form2.setRealname(pro.getNombreReal() + " " + pro.getApellidos());
    form2.setUrl(pro.getUrl());
    form2.setProtegida(pro.getPerfilPrivado());
    form2.setPeticiones(peticiones.getNumero_peticiones());
    form2.setImgUrl(
        (pro.getImgUrl() != null && !pro.getImgUrl().isEmpty()
            ? ".." + pro.getImgUrl()
            : ".." + defaultImage));
    return mapping.findForward(SUCCESS);
  }
Example #18
0
  public RolOpcionesVO validarSesion(int formulario) throws IOException {
    RolOpcionesVO roles = new RolOpcionesVO();
    try {
      faceContext = FacesContext.getCurrentInstance();
      httpServletRequest = (HttpServletRequest) faceContext.getExternalContext().getRequest();
      HttpSession session = httpServletRequest.getSession();
      listaUsuarios = (List<UsuarioVO>) session.getAttribute("listaUsuario");
      listaRolOpciones = (List<RolOpcionesVO>) session.getAttribute("listaPermisos");

      for (RolOpcionesVO rolO : listaRolOpciones) {
        if (rolO.getMenId() == formulario) parametroValidacion = true;
      }
      if (!parametroValidacion) {
        logout();
      } else {
        for (RolOpcionesVO rolOpcion : listaRolOpciones) {
          if (rolOpcion.getMenId() == formulario) return rolOpcion;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      logout();
    }
    return null;
  }
  @RequestMapping(value = "informationboardwrite.do")
  public ModelAndView board(
      Locale locale, HttpServletRequest request, HttpServletResponse response) {
    logger.info("Welcome InformationInsert! The client locale is {}.", locale);

    ModelAndView modelAndView = new ModelAndView();

    // login Information
    HttpSession session = request.getSession();
    int log = 0;
    try {
      log = Integer.parseInt(request.getParameter("log"));
    } catch (Exception e) {
      log = 0;
    }
    if (log == 1) {
      UserVo user = new UserVo();
      user.setUserId((String) session.getAttribute("userId"));
      user.setUserPassword((String) session.getAttribute("userPassword"));
      user.setUserName((String) session.getAttribute("userName"));
      user.setUserBirthday((String) session.getAttribute("userBirthday"));
      user.setUserSeq((Integer) session.getAttribute("userSeq"));
      modelAndView.addObject("user", user);
    }
    modelAndView.addObject("log", log);
    ///////////////////////////////////////////////
    Category category =
        categoryService.showCategory(Integer.parseInt(request.getParameter("category")));

    modelAndView.addObject("category", category);
    modelAndView.setViewName("informationboardwrite");

    return modelAndView;
  }
Example #20
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    HttpSession session = req.getSession(false);

    if (session != null) {
      if (session.getAttribute("user") != null)
        if (session.getAttribute("user") instanceof User) {
          User user = (User) session.getAttribute("user");
          Gson gson = new Gson();
          String json = gson.toJson(user);
          resp.getWriter().write(json);
        }
    } else {
      if (req.getParameter("id") != null && req.getParameter("password") != null) {
        UserServ serv;
        serv = new UserServ();
        UserDAO udao = new UserDAO();
        udao.setSessionFactory(factory);
        serv.setDao(udao);
        if (serv.isValidUser(req.getParameter("id"), req.getParameter("password"))) {
          User user = serv.getUser();
          Gson gson = new Gson();
          String json = gson.toJson(user);
          resp.getWriter().write(json);
          session = req.getSession();
          session.setAttribute("user", user);
        }
      }
    }
  }
Example #21
0
 /**
  * Method execute
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  */
 public ActionForward execute(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response) {
   try {
     // 从session获取list
     HttpSession session = request.getSession();
     ArrayList<Result6FormBean> list = new ArrayList<Result6FormBean>();
     list = (ArrayList<Result6FormBean>) session.getAttribute("DANLULIST"); // 此时取出来的是Object,
     // 需要强转
     // 定义导出excel名字
     String fileName = "单炉生产数据统计表.xls";
     fileName = new String(fileName.getBytes("UTF-8"), "utf-8");
     // 取得检索日期
     String riqi = (String) session.getAttribute("RIQI");
     // 导出excel到服务器
     Excel.exportResult6Excel(list, fileName, riqi);
     // 下载excel到本地
     FileAction fileDownload = new FileAction();
     fileDownload.downFile(response, fileName);
     return null;
   } catch (Exception e) {
     e.printStackTrace();
     return mapping.findForward("searchError");
   }
 }
  public boolean handleGetMessage(HttpServletRequest request, HttpServletResponse response) {
    copyToSession(request, this.getMsgParams);
    HttpSession session = request.getSession();

    boolean getMsg = session.getAttribute("getMessage") != null;

    if (!getMsg) return false;

    try {
      OAuthToken token = getSessionToken(request, response);
      if (token == null) {
        return true;
      }

      String msgId = (String) session.getAttribute("messageId");

      IMMNService srvc = new IMMNService(appConfig.getApiFQDN(), token);

      Message msg = srvc.getMessage(msgId);

      request.setAttribute("getMsg", msg);
      clearSession(request, this.getMsgParams);
    } catch (Exception e) {
      clearSession(request, this.getMsgParams);
      request.setAttribute("getMsgError", e.getMessage());
    } finally {
      request.setAttribute("toggleDiv", "getMsg");
    }

    return false;
  }
Example #23
0
  private void process(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    try {
      HttpSession session = request.getSession();
      String idUser = (String) session.getAttribute("name");
      Date date = new java.sql.Date(System.currentTimeMillis());

      JPAUtil jpa = new JPAUtil();

      ArrayList<String> ar = (ArrayList<String>) (session.getAttribute("commande"));
      if (ar != null) {
        ServiceCommande service = new ServiceCommande();
        for (String code : ar) {
          Commande c = new Commande();
          c.setCodeArticle(code);
          c.setIdUser(idUser);
          c.setDate(date);
          service.EnregistrerCommande(c);
          jpa.executeSQLCommand(
              "UPDATE bddprog3.article SET Stock=Stock-1 WHERE `code`='" + code + "'");
        }
      }

      getServletContext().getRequestDispatcher("/AnnulerCommande").forward(request, response);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public boolean handleGetDelta(HttpServletRequest request, HttpServletResponse response) {

    copyToSession(request, this.getDeltaParams);
    HttpSession session = request.getSession();

    boolean getDelta = session.getAttribute("getDelta") != null;

    if (!getDelta) return false;

    try {
      OAuthToken token = getSessionToken(request, response);
      if (token == null) {
        return true;
      }

      String state = (String) session.getAttribute("state");
      IMMNService srvc = new IMMNService(appConfig.getApiFQDN(), token);
      DeltaResponse deltaR = srvc.getDelta(state);
      request.setAttribute("deltas", deltaR);
      clearSession(request, this.getDeltaParams);
    } catch (Exception e) {
      clearSession(request, this.getDeltaParams);
      request.setAttribute("getDeltaError", e.getMessage());
    } finally {
      request.setAttribute("toggleDiv", "getMsg");
    }

    return false;
  }
Example #25
0
  @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);
  }
  public boolean handleNotificationConnectionDetails(
      HttpServletRequest request, HttpServletResponse response) {
    copyToSession(request, this.notifyDetailsParams);
    HttpSession session = request.getSession();

    boolean notify = session.getAttribute("getNotifyDetails") != null;

    if (!notify) return false;

    try {
      OAuthToken token = getSessionToken(request, response);
      if (token == null) {
        return true;
      }

      IMMNService srvc = new IMMNService(appConfig.getApiFQDN(), token);

      String queue = (String) session.getAttribute("queues");

      NotificationConnectionDetails details = srvc.getNotificationConnectionDetails(queue);

      request.setAttribute("notificationDetails", details);
      clearSession(request, this.notifyDetailsParams);
    } catch (Exception e) {
      clearSession(request, this.notifyDetailsParams);
      e.printStackTrace();
      request.setAttribute("notificationDetailsError", e.getMessage());
    } finally {
      request.setAttribute("toggleDiv", "getMsgNot");
    }

    return false;
  }
  @RequestMapping(value = "/wfstepDelete", method = RequestMethod.GET)
  @RequestScoped
  public ModelAndView wfStepDelete(HttpServletRequest request, HttpServletResponse response) {
    response.setCharacterEncoding("UTF-8");
    String wfstepid = null;

    try {
      wfstepid = request.getParameter("wfstepidDelete");
      String msg = wfstepService.wfstepDelete(wfstepid);

      if (msg.equals("S")) {
        sess = request.getSession(false);
        Date date = new Date();
        String modifiedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        auditLogService.setAuditLogSave(
            sess.getAttribute("userId").toString(),
            "D",
            "Process Step",
            "ROW",
            String.valueOf(wfstepid),
            "1",
            modifiedDate,
            sess.getAttribute("userName").toString());
        request.setAttribute("wfstepDeleteSuccess", "Work Flow Step has been deleted");
      } else {
        request.setAttribute("wfstepDeleteError", "Work Flow Step has not been deleted");
      }
    } catch (Exception e) {
      request.setAttribute("wfstepDeleteError", "Work Flow Step has not been deleted");
      e.printStackTrace();
    }
    return new ModelAndView("wfstepHome", "wfstepAdd", new WFStep());
  }
 @RequestMapping("/cardInfomation")
 public String cardInfomation(Model model, HttpSession session) {
   String forwardPath = "index";
   if ((Member) session.getAttribute("sMember") == null) {
     return "redirect:login";
   }
   Member member = (Member) session.getAttribute("sMember");
   //
   ArrayList<HashMap<String, String>> moneyMap =
       textFormatUtil.head_Nav_CardUseList(member.getM_email());
   model.addAttribute("head_nav_moneyList_size", moneyMap.size());
   model.addAttribute("head_nav_moneyList", moneyMap);
   //
   /** ************** 상단 nav schedule 알람 ************************ */
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   String strDate = sdf.format(new Date());
   HashMap<String, String> sMap = new HashMap<String, String>();
   sMap.put("s_m_email", member.getM_email());
   sMap.put("s_end", strDate);
   List<Scheduler> scList = schedulerService.selectforHeadNav(sMap);
   model.addAttribute("scList", scList);
   /** ************************************************************** */
   ArrayList<Card> cardList = cardService.getCardListByEmail(member.getM_email());
   model.addAttribute("cardList", cardList);
   model.addAttribute("path", "cardInfomation.jsp");
   return forwardPath;
 }
  /**
   * 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);
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String creditCard = request.getParameter("cardno");
    if (creditCard.length() != 16) {
      request
          .getSession()
          .setAttribute("creditcarderror", "Invalid Credit Card.It should be 16 Digits");
      response.sendRedirect("checkout.jsp");
    } else {
      HttpSession session = request.getSession();
      HashMap<String, ArrayList<String>> cartMap = new HashMap<String, ArrayList<String>>();
      cartMap = (HashMap<String, ArrayList<String>>) session.getAttribute("cartlist");

      for (String key : cartMap.keySet()) {
        ArrayList<String> list = cartMap.get(key);

        MarketServiceProxy proxy = new MarketServiceProxy();
        proxy.setEndpoint("http://localhost:8080/SimpleMarketPlace/services/MarketService?wsdl");
        proxy.updateProductQuantity(Integer.parseInt(list.get(2)), Integer.parseInt(key));
        proxy.updatePurchase(
            Integer.parseInt(key),
            Integer.parseInt(list.get(2)),
            session.getAttribute("email").toString());
      }

      cartMap.clear();
      response.sendRedirect("ship.jsp");

      // TODO add separate tables for sold and purchased items

    }
  }