Example usage for javax.servlet.http HttpSession getAttribute

List of usage examples for javax.servlet.http HttpSession getAttribute

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the object bound with the specified name in this session, or null if no object is bound under the name.

Usage

From source file:edu.uoc.json.controller.ChatController.java

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody JSONResponse currentUserAcceptConnection(@RequestBody JSONRequest message,
        HttpSession session) {
    JSONResponse response = new JSONResponse();
    MeetingRoom meeting = (MeetingRoom) session.getAttribute(Constants.MEETING_SESSION);
    User user = (User) session.getAttribute(Constants.USER_SESSION);
    try {/*from   w  ww  . java2s .co m*/
        if (user != null && meeting != null) {
            Chat chat = new Chat();
            chat.setUser(user);
            logger.debug("Chat message from " + user.getFullname() + " to " + message.getRequest());
            chat.setChat_message(message.getRequest());
            chat.setMeeting_room(meeting);

            chatDao.save(chat);

            response.setOk(true);
        }
    } catch (Exception e) {
        logger.error("Error registering chat", e);
        response.setErrorMessage(e.getMessage());
    }
    return response;
}

From source file:mx.com.quadrum.contratos.controller.crud.UsuarioController.java

@ResponseBody
@RequestMapping(value = "editarUsuario", method = RequestMethod.POST)
public String editarUsuario(@Valid @ModelAttribute("usuario") Usuario usuario, BindingResult bindingResult,
        HttpSession session) {
    if (session.getAttribute("usuario") == null) {
        return SESION_CADUCA;
    }//from   ww  w  . ja va  2s  .  c  om
    if (bindingResult.hasErrors()) {
        return ERROR_DATOS;
    }
    if (usuarioService.existeCorreo(usuario.getMail())) {
        Usuario u = usuarioService.buscarPorCorreo(usuario.getMail());
        if (u.getId() != usuario.getId()) {
            return "Error...#El correo pertencece a otra persona.";
        }
    }
    return usuarioService.editar(usuario);
}

From source file:be.fedict.eid.applet.service.KmlServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");

    HttpSession httpSession = request.getSession();
    EIdData eIdData = (EIdData) httpSession.getAttribute("eid");

    byte[] document;
    try {//from w w w. ja va2s  .c  o  m
        document = this.kmlGenerator.generateKml(eIdData);
    } catch (IOException e) {
        throw new ServletException("KML generator error: " + e.getMessage(), e);
    }

    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    if (false == request.getScheme().equals("https")) {
        // else the download fails in IE
        response.setHeader("Pragma", "no-cache"); // http 1.0
    } else {
        response.setHeader("Pragma", "public");
    }
    response.setDateHeader("Expires", -1);
    response.setHeader("Content-disposition", "attachment");
    response.setContentLength(document.length);

    response.setContentType(KmlLight.MIME_TYPE);
    response.setContentLength(document.length);
    ServletOutputStream out = response.getOutputStream();
    out.write(document);
    out.flush();
}

From source file:com.mirth.connect.server.servlets.MirthServlet.java

public boolean isUserLoggedIn(HttpServletRequest request) {
    HttpSession session = request.getSession();
    return (session.getAttribute(UserServlet.SESSION_AUTHORIZED) != null)
            && (session.getAttribute(UserServlet.SESSION_AUTHORIZED).equals(true));
}

From source file:hu.ptemik.gallery.servlets.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    User user = (User) session.getAttribute("user");
    String uploadFolder = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    if (ServletFileUpload.isMultipartContent(request) && user != null) {
        try {/*from  w  w  w  .j  av a 2 s  .c  o  m*/
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            Picture pic = new Picture();
            File uploadedFile = null;

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    String relativePath = UPLOAD_DIRECTORY + "/" + fileName;

                    uploadedFile = new File(filePath);
                    item.write(uploadedFile);

                    pic.setUrl(relativePath);
                } else {
                    if (item.getFieldName().equals("title")) {
                        pic.setTitle(item.getString());
                    } else if (item.getFieldName().equals("description")) {
                        pic.setDescription(item.getString());
                    }
                }
            }

            if (Controller.newPicture(pic, user)) {
                request.setAttribute("successMessage", "A fjl feltltse sikerlt!");
            } else {
                FileUtils.deleteQuietly(uploadedFile);
                throw new Exception();
            }
        } catch (FileNotFoundException ex) {
            request.setAttribute("errorMessage", "Hinyzik a fjl!");
        } catch (Exception ex) {
            request.setAttribute("errorMessage", "Hiba a fjl feltltse sorn!");
        }
    } else {
        request.setAttribute("errorMessage", "Form hiba");
    }

    request.getRequestDispatcher("upload.jsp").forward(request, response);
}

From source file:com.alcshare.gothere.servlets.SearchServlet.java

private LDSearch getSearch(final HttpServletRequest req) {
    HttpSession session = req.getSession();
    Object data = session.getAttribute(KEY_DATA);
    if (data == null) {
        try {//  w w  w  . jav a 2s  . c om
            final SystemAccessSearchCache cache = new SystemAccessSearchCache();
            data = new LDSearch(cache);
            session.setAttribute(KEY_DATA, data);

            SystemConnection connection = DirectAccess.getDirectAccess().getUserSystemConnection(req);
            //Date start = new Date();
            connection.runReadAction(new ReadAction() {
                @Override
                public void execute(@NotNull SystemAccess access) throws Exception {
                    cache.buildCache(access);
                }
            });
            //Date end = new Date();
            //System.out.println("JumpTo Add-On created search cache of " + cache.getCache().size() + " items in " +
            //      (end.getTime() - start.getTime()) + " mSec");
        } catch (ActionExecutionException | InvalidConnectionRequestException | SystemException e) {
            LOGGER.println(e);
        }
    }

    return (LDSearch) data;
}

From source file:com.att.api.immn.controller.LoadController.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final HttpSession session = request.getSession();
    OAuthToken token = (OAuthToken) session.getAttribute("token");
    final Boolean authenticated = (token != null && !token.isAccessTokenExpired());

    final String FQDN = appConfig.getOauthFQDN();
    final String clientId = appConfig.getClientId();
    final String scope = appConfig.getProperty("scope");
    final String redirectUri = appConfig.getProperty("redirectUri");
    final String redirect_url = FQDN + "/oauth/v4/authorize?client_id=" + clientId + "&scope=" + scope
            + "&redirect_uri=" + redirectUri;
    final boolean subscriptionActive = session.getAttribute("subscriptionId") != null;

    JSONObject jchannel = new JSONObject().put("channelId", appConfig.getProperty("channelId"))
            .put("channelType", appConfig.getProperty("channelType"))
            .put("maxEvents", appConfig.getProperty("maxEvents"))
            .put("contentType", appConfig.getProperty("contentType"));

    JSONObject jresponse = new JSONObject().put("authenticated", authenticated)
            .put("redirect_url", redirect_url).put("server_time", DateUtil.getTime())
            .put("download", this.appConfig.getProperty("linkDownload"))
            .put("github", this.appConfig.getProperty("linkGithub")).put("notificationChannel", jchannel)
            .put("subscriptionActive", subscriptionActive);

    final String savedData = (String) session.getAttribute("savedData");
    if (savedData != null) {
        final JSONObject jsavedData = new JSONObject(savedData);
        jresponse.put("savedData", jsavedData);
    }//from   w w w .  j a v a  2  s  . c  o  m

    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.print(jresponse);
    writer.flush();
}

From source file:com.supinfo.supfriends.web.filter.ProtectorFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean validCredentials = false;

    String path = ((HttpServletRequest) request).getRequestURI();
    if (isFullyAuthorizedUrl(path)) {
        chain.doFilter(request, response);
        return;/*w  ww  . j av a2s .c  o m*/
    }

    HttpSession session = ((HttpServletRequest) request).getSession();
    if (session.getAttribute("id") != null && session.getAttribute("username") != null
            && session.getAttribute("password") != null) {
        UserEntity user = userFacade.find((Long) session.getAttribute("id"));
        if (user != null) {
            if (user.getPassword().equals(session.getAttribute("password"))) {
                validCredentials = true;
            }
        }
    }

    if (validCredentials) {
        chain.doFilter(request, response);
    } else {
        ((HttpServletResponse) response).sendRedirect(ServerConfig.CONTEXT_URL + "/faces/login.xhtml");
    }
}

From source file:cs472.w1d5.servlet.Welcome.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w  w .ja  v  a  2 s.c  o m*/
 *
 * @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 session = request.getSession();
    String user = (String) session.getAttribute("user");
    if (user == null) {
        response.sendRedirect("login.html");
        return;
    }

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet Welcome</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Welcome " + escapeHtml(user) + "</h1>");
        out.println("<p><a href='Logout'>logout</p>");
        out.println("</body>");
        out.println("</html>");
    }
}

From source file:bc8.movies.controllers.LoginController.java

@RequestMapping(value = "/changePassword")
public ModelAndView changePassword(String newPassword, HttpSession session) {
    ModelAndView mv = new ModelAndView("userDetails");
    User currUser;//from  www . j  a  va2s  .co m
    if (session.getAttribute("user") == null) {
        mv.setViewName("redirect:/home");
    } else if ((currUser = (User) session.getAttribute("user")) != null) {
        currUser.setPassword(newPassword);
        userService.updateUser(currUser);
    }
    return mv;
}