Example usage for javax.servlet.http HttpSession getId

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

Introduction

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

Prototype

public String getId();

Source Link

Document

Returns a string containing the unique identifier assigned to this session.

Usage

From source file:gov.nih.nci.rembrandt.web.taglib.KaplanMeierPlotTag.java

public int doStartTag() {

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();
    String dataName;//from   ww w .  ja  va 2 s .c o  m
    try {
        dataName = BeanUtils.getSimpleProperty(o, datasetName);
        KaplanMeierStoredData cacheData = (KaplanMeierStoredData) presentationTierCache
                .getSessionGraphingData(session.getId(), dataName);
        JFreeChart chart = CaIntegratorChartFactory
                .getKaplanMeierGraph(cacheData.getPlotPointSeriesCollection());

        RembrandtImageFileHandler imageHandler = new RembrandtImageFileHandler(session.getId(), "png", 700,
                500);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        /**
         * Create the actual chart, writing it to the session temp folder
         */
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 700, 500);
        /*
         *   This is here to put the thread into a loop while it waits for the
         *   image to be available.  It has an unsophisticated timer but at 
         *   least it is something to avoid an endless loop.
         *  
         */
        boolean imageReady = false;
        int timeout = 1000;
        FileInputStream inputStream = null;
        while (!imageReady) {
            timeout--;
            try {
                inputStream = new FileInputStream(finalPath);
                inputStream.available();
                imageReady = true;
                inputStream.close();
            } catch (IOException ioe) {
                imageReady = false;
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (timeout <= 1) {

                break;
            }
        }
        out.print(imageHandler.getImageTag());
        out.print(createLegend(cacheData));
    } catch (IllegalAccessException e1) {
        logger.error(e1);
    } catch (InvocationTargetException e1) {
        logger.error(e1);
    } catch (NoSuchMethodException e1) {
        logger.error(e1);
    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:nl.strohalm.cyclos.struts.CyclosRequestProcessor.java

private void traceLog(final HttpServletRequest request, final Throwable error, final boolean hasWrite) {
    final HttpServletRequest multipartRequest = (HttpServletRequest) request.getAttribute("multipartRequest");
    final HttpServletRequest req = multipartRequest == null ? request : multipartRequest;
    final TraceLogDTO params = new TraceLogDTO();
    params.setUser(LoggedUser.user());//from ww  w .j  a v  a2s.  c  o  m
    params.setRemoteAddress(req.getRemoteAddr());
    params.setRequestMethod(req.getMethod());
    params.setPath(req.getRequestURI());
    params.setParameters(ActionHelper.getParameterMap(req));
    final HttpSession session = req.getSession(false);
    params.setSessionId(session == null ? null : session.getId());
    params.setError(error);
    params.setHasDatabaseWrites(hasWrite);
    loggingHandler.trace(params);
}

From source file:airport.web.controller.ServicesController.java

@RequestMapping(value = "/service/dispatcher/getflights", produces = "application/json")
public List<NodeDisctributor> serviceDispatcherGetFlights(HttpServletRequest request,
        HttpServletResponse response) {//from w w  w.  j a v  a 2s.  c om
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (serviceUsers.checkUserOnline(user)) {
        List<NodeDisctributor> list = serviceDistributor.getActualInformation(user);

        if (LOG.isInfoEnabled()) {
            LOG.info("user get flight. Session id : " + httpSession.getId() + ". User : " + user
                    + ". URL : /service/dispatcher/getflights");
        }

        return list;
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : /service/dispatcher/getflights");
        }
    }

    return new ArrayList<>();
}

From source file:airport.web.controller.ServicesController.java

@RequestMapping(value = "/service/chat/get", produces = "application/json")
public List<Message> serviceChatGet(HttpServletRequest request, HttpServletResponse response) {
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (serviceUsers.checkUserOnline(user)) {
        int numberMessage = Integer.parseInt(request.getParameter("numberMessage"));

        if (LOG.isInfoEnabled()) {
            LOG.info("user get messages. Session id : " + httpSession.getId() + ". User : " + user
                    + ". URL : /service/chat/get");
        }//w  ww  . ja v  a 2s.  c o m

        return serviceChat.getMessageMiss(numberMessage);
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : /service/chat/get");
        }
    }

    return new ArrayList<>();
}

From source file:com.imagelake.android.signin.Servlet_signin.java

protected void doPost(HttpServletRequest request, HttpServletResponse respose)
        throws IOException, ServletException {
    PrintWriter out = respose.getWriter();
    try {/*w  ww.j  av  a2s  .c  o  m*/
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(d);
        SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm:ss");
        String loginTime = sdf2.format(d);

        HttpSession ses = request.getSession();

        un = request.getParameter("un");
        pw = request.getParameter("pw");

        if (un != null && pw != null) {

            User u = udi.searchSignIn(un, pw);
            if (u != null) {

                if (u.getState() == 1) {

                    Userlogin userlogin = new Userlogin();
                    userlogin.setBrowser("Android");
                    userlogin.setIp_address(request.getRemoteHost());
                    userlogin.setSession_id(ses.getId());
                    userlogin.setStart_date(sdf.format(d));
                    userlogin.setStart_time(loginTime);
                    userlogin.setCountry("Sri Lanka");
                    userlogin.setCode("LK");

                    userlogin.setUser_user_id(u.getUser_id());
                    userlogin.setState(1);

                    int ok = uldi.insertLogin(userlogin);
                    System.out.println("okkk " + ok);
                    if (ok > 0) {

                        JSONObject jo = new JSONObject();
                        jo.put("id", u.getUser_id());
                        jo.put("un", u.getUser_name());
                        jo.put("pw", u.getPassword());
                        jo.put("fn", u.getFirst_name());
                        jo.put("ln", u.getLast_name());
                        jo.put("em", u.getEmail());
                        jo.put("user_type", u.getUser_type());
                        jo.put("state", u.getState());

                        out.write("json=" + jo.toJSONString());
                        System.out.println("json" + jo.toJSONString());

                    } else {
                        out.write("msg=Internal server error,Please try again later.");
                    }

                } else {
                    out.write("msg=Blocked by the admin");
                }

            } else {
                out.write("msg=Incorrect user name or password");
            }

        } else {

            out.write("msg=Please enter user details");

        }

    } catch (Exception e) {
        e.printStackTrace();
        out.write("msg=Internal server error,Please try again later.");
    }

}

From source file:airport.web.controller.ServicesController.java

@RequestMapping(value = "/service/chat/add", produces = "application/json")
public void serviceChatAdd(HttpServletRequest request, HttpServletResponse response) {
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (serviceUsers.checkUserOnline(user)) {
        String text = request.getParameter("charText");

        serviceChat.addMessage(user, text);

        if (LOG.isInfoEnabled()) {
            LOG.info("user add message. Session id : " + httpSession.getId() + ". User : " + user
                    + ". URL : /service/chat/add");
        }/*from w w  w  .ja  va  2 s.  co m*/
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : /service/chat/add");
        }
    }
}

From source file:nl.armatiek.xslweb.serializer.RequestSerializer.java

@SuppressWarnings("rawtypes")
private void serializeSession() throws Exception {
    HttpSession session = req.getSession();
    if (session == null) {
        return;/*  w  w  w .j  a  va2s .  c o  m*/
    }
    xsw.writeStartElement(URI, "session");
    dataElement(xsw, URI, "creation-time", getXsDateTimeString(new Date(session.getCreationTime())));
    dataElement(xsw, URI, "id", session.getId());
    dataElement(xsw, URI, "last-accessed-time", getXsDateTimeString(new Date(session.getLastAccessedTime())));
    dataElement(xsw, URI, "max-inactive-interval", Integer.toString(session.getMaxInactiveInterval()));
    dataElement(xsw, URI, "is-new", Boolean.toString(session.isNew()));
    Enumeration attrNames = session.getAttributeNames();
    if (attrNames.hasMoreElements()) {
        xsw.writeStartElement(URI, "attributes");
        while (attrNames.hasMoreElements()) {
            String attrName = (String) attrNames.nextElement();
            xsw.writeStartElement(URI, "attribute");
            xsw.writeAttribute("name", attrName);
            Object attr = session.getAttribute(attrName);
            if (attr instanceof Collection) {
                @SuppressWarnings("unchecked")
                Collection<Attribute> attrs = (Collection<Attribute>) attr;
                for (Attribute a : attrs) {
                    xsw.writeStartElement(URI, "item");
                    if (a.isSerialized()) {
                        xsw.writeAttribute("type", a.getType());
                        getFilteredXMLReader().parse(new InputSource(new StringReader(a.getSerializedValue())));
                    } else {
                        xsw.writeAttribute("type", a.getType());
                        xsw.writeCharacters(a.getValue().toString());
                    }
                    xsw.writeEndElement();
                }
            } else {
                xsw.writeCharacters(attr.toString());
            }
            xsw.writeEndElement();
        }
        xsw.writeEndElement();
    }
    xsw.writeEndElement();
}

From source file:ATDataGrid.servlets.DataObjectProfileManager.java

private void registerAuthentication(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    String access_token = request.getParameter("Access_Token");
    int issued_at = Integer.parseInt(request.getParameter("Issued_At"));
    int expires_at = Integer.parseInt(request.getParameter("Expires_At"));
    boolean isValidAccessToken = false;
    try {/*from  www  . j  ava 2s . c o  m*/
        isValidAccessToken = doAccessTokenValidation(session, access_token, issued_at, expires_at);
    } catch (Exception e) {
        //
    }
    if (isValidAccessToken) {
        System.out.println("Session ID is: " + session.getId());
        System.out.println("Access Token Validated");
        response.setContentType("application/json;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.println("{\"ReturnCode\": 0}");
        } catch (IOException ex) {
            Logger.getLogger(DataObjectProfileManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        System.out.println("Access Token Is Not Valid");
        response.setStatus(407);
        try (PrintWriter out = response.getWriter()) {
            out.println("{\"ReturnCode\": 407}");
        } catch (IOException ex) {
            Logger.getLogger(DataObjectProfileManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTest.java

@Test
public void buildRequestSessionWithExistingSession() throws Exception {
    String sessionId = "session-id";
    webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
    MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

    HttpSession session = actualRequest.getSession();
    assertThat(session.getId()).isEqualTo(sessionId);
    assertSingleSessionCookie("JSESSIONID=" + session.getId() + "; Path=/test; Domain=example.com");

    requestBuilder = new HtmlUnitRequestBuilder(sessions, cookieManager, webRequest);
    actualRequest = requestBuilder.buildRequest(servletContext);
    assertThat(actualRequest.getSession()).isEqualTo(session);

    webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId + "NEW");
    actualRequest = requestBuilder.buildRequest(servletContext);
    assertThat(actualRequest.getSession()).isNotEqualTo(session);
    assertSingleSessionCookie(/*from   w w  w  .j a va  2 s  . co m*/
            "JSESSIONID=" + actualRequest.getSession().getId() + "; Path=/test; Domain=example.com");
}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationFilterTest.java

@Test
public void doFilterOtherTennantAccessNoVDCinReq() throws IOException, ServletException {
    HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    HttpServletResponse servletResponse = mock(HttpServletResponse.class);
    FilterChain filterChain = mock(FilterChain.class);
    HttpSession httpSession = mock(HttpSession.class);
    Authentication authResult = mock(Authentication.class);
    PaasManagerUser paasUser = mock(PaasManagerUser.class);

    when(servletRequest.getHeader(anyString())).thenReturn("3df25213cac246f8bccad5c70cb3582e")
            .thenReturn("00000000000000000000000000000194").thenReturn("1234");
    when(servletRequest.getRequestURI()).thenReturn("/catalog/application/");
    when(servletRequest.getPathInfo()).thenReturn("/path");
    when(servletRequest.getSession()).thenReturn(httpSession);
    when(httpSession.getId()).thenReturn("1234");
    when(authenticationManager.authenticate(any(Authentication.class))).thenReturn(authResult);

    when(authResult.getPrincipal()).thenReturn(paasUser);

    openStackAuthenticationFilter.doFilter(servletRequest, servletResponse, filterChain);
}