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:Counter.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession(true);
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    int count = 1;
    Integer i = (Integer) session.getAttribute(COUNTER_KEY);
    if (i != null) {
        count = i.intValue() + 1;// w  ww.ja  v  a  2  s . c  om
    }
    session.setAttribute(COUNTER_KEY, new Integer(count));
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Session Counter</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("Your session ID is <b>" + session.getId());
    out.println("</b> and you have hit this page <b>" + count + "</b> time(s) during this browser session");

    out.println("<form method=GET action=\"" + req.getRequestURI() + "\">");
    out.println("<input type=submit " + "value=\"Hit page again\">");
    out.println("</form>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
}

From source file:CounterRewrite.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession(true);
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    int count = 1;
    Integer i = (Integer) session.getAttribute(COUNTER_KEY);
    if (i != null) {
        count = i.intValue() + 1;/*from www. ja  va 2s . c o m*/
    }
    session.setAttribute(COUNTER_KEY, new Integer(count));
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Session Counter</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("Your session ID is <b>" + session.getId());
    out.println("</b> and you have hit this page <b>" + count + "</b> time(s) during this browser session");

    String url = req.getRequestURI();
    out.println("<form method=GET action=\"" + resp.encodeURL(url) + "\">");
    out.println("<input type=submit " + "value=\"Hit page again\">");
    out.println("</form>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
}

From source file:nz.co.fortytwo.signalk.processor.RestApiProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    // the Restlet request should be available if needed
    HttpServletRequest request = exchange.getIn(HttpMessage.class).getRequest();
    HttpSession session = request.getSession();
    if (logger.isDebugEnabled()) {

        logger.debug("Request = " + exchange.getIn().getHeader(Exchange.HTTP_SERVLET_REQUEST).getClass());
        logger.debug("Session = " + session.getId());
    }/*from   w w w .  jav  a2s .c  o  m*/

    if (session.getId() != null) {
        exchange.getIn().setHeader(REST_REQUEST, "true");
        String remoteAddress = request.getRemoteAddr();
        String localAddress = request.getLocalAddr();
        if (Util.sameNetwork(localAddress, remoteAddress)) {
            exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.INTERNAL_IP);
        } else {
            exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.EXTERNAL_IP);
        }
        exchange.getIn().setHeader(SignalKConstants.MSG_SRC_IP, remoteAddress);
        exchange.getIn().setHeader(SignalKConstants.MSG_SRC_IP_PORT, request.getRemotePort());
        exchange.getIn().setHeader(SignalKConstants.MSG_SRC_BUS, "rest." + remoteAddress.replace('.', '_'));
        exchange.getIn().setHeader(WebsocketConstants.CONNECTION_KEY, session.getId());

        String path = (String) exchange.getIn().getHeader(Exchange.HTTP_URI);
        if (logger.isDebugEnabled()) {
            logger.debug(exchange.getIn().getHeaders());
            logger.debug(path);
        }

        if (logger.isDebugEnabled())
            logger.debug("Processing the path = " + path);
        if (!isValidPath(path)) {
            exchange.getIn().setBody("Bad Request");
            exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/plain");
            exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, HttpServletResponse.SC_BAD_REQUEST);
            // response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("GET")) {
            processGet(exchange, path);
        }
        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("PUT")) {
            processPut(exchange, path);
        }
        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("POST")) {
            if (exchange.getIn().getBody() instanceof StreamCache) {
                StreamCache cache = exchange.getIn().getBody(StreamCache.class);
                ByteArrayOutputStream writer = new ByteArrayOutputStream();
                cache.writeTo(writer);
                if (logger.isDebugEnabled())
                    logger.debug("Reading the POST request:" + writer.toString());
                exchange.getIn().setBody(writer.toString());

                // POST here
                if (logger.isDebugEnabled())
                    logger.debug("Processing the POST request:" + exchange.getIn().getBody());
            } else {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Skipping processing the POST request:" + exchange.getIn().getBody().getClass());
            }
        }

    } else {
        // HttpServletResponse response =
        // exchange.getIn(HttpMessage.class).getResponse();
        exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, HttpServletResponse.SC_MOVED_TEMPORARILY);
        // constant("http://somewhere.com"))
        exchange.getIn().setHeader("Location", SignalKConstants.SIGNALK_AUTH);
        exchange.getIn().setBody("Authentication Required");
    }

}

From source file:net.lightbody.bmp.proxy.jetty.servlet.SessionDump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    Page page = new Page();

    HttpSession session = request.getSession(getURI(request).indexOf("new") > 0);

    page.title("Session Dump Servlet: ");

    TableForm tf = new TableForm(response.encodeURL(getURI(request)));
    tf.method("POST");

    if (session == null) {
        page.add("<H1>No Session</H1>");
        tf.addButton("Action", "New Session");
    } else {//from  ww w.j  a  v  a2s .c  o m
        try {
            tf.addText("ID", session.getId());
            tf.addText("State", session.isNew() ? "NEW" : "Valid");
            tf.addText("Creation", new Date(session.getCreationTime()).toString());
            tf.addText("Last Access", new Date(session.getLastAccessedTime()).toString());
            tf.addText("Max Inactive", "" + session.getMaxInactiveInterval());

            tf.addText("Context", "" + session.getServletContext());

            Enumeration keys = session.getAttributeNames();
            while (keys.hasMoreElements()) {
                String name = (String) keys.nextElement();
                String value = session.getAttribute(name).toString();
                tf.addText(name, value);
            }

            tf.addTextField("Name", "Property Name", 20, "name");
            tf.addTextField("Value", "Property Value", 20, "value");
            tf.addTextField("MaxAge", "MaxAge(s)", 5, "");
            tf.addButtonArea();
            tf.addButton("Action", "Set");
            tf.addButton("Action", "Remove");
            tf.addButton("Action", "Invalidate");

            page.add(tf);
            tf = null;
            if (request.isRequestedSessionIdFromCookie())
                page.add("<P>Turn off cookies in your browser to try url encoding<BR>");

            if (request.isRequestedSessionIdFromURL())
                page.add("<P>Turn on cookies in your browser to try cookie encoding<BR>");

        } catch (IllegalStateException e) {
            log.debug(LogSupport.EXCEPTION, e);
            page.add("<H1>INVALID Session</H1>");
            tf = new TableForm(getURI(request));
            tf.addButton("Action", "New Session");
        }
    }

    if (tf != null)
        page.add(tf);

    Writer writer = response.getWriter();
    page.write(writer);
    writer.flush();
}

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

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

    when(servletRequest.getHeader(anyString())).thenReturn("3df25213cac246f8bccad5c70cb3582e")
            .thenReturn("00000000000000000000000000000194");
    when(servletRequest.getPathInfo()).thenReturn("/");
    when(servletRequest.getRequestURI()).thenReturn("/vdc/00000000000000000000000000000194/");
    when(servletRequest.getSession()).thenReturn(httpSession);
    when(httpSession.getId()).thenReturn("1234");

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

From source file:at.gv.egiz.pdfas.web.helper.PdfAsHelper.java

private static String generateURL(HttpServletRequest request, HttpServletResponse response, String Servlet) {
    HttpSession session = request.getSession();
    String publicURL = WebConfiguration.getPublicURL();
    String dataURL = null;//  w w  w . j  av a  2  s . c  o  m
    if (publicURL != null) {
        dataURL = publicURL + Servlet + ";jsessionid=" + session.getId();
    } else {
        if ((request.getScheme().equals("http") && request.getServerPort() == 80)
                || (request.getScheme().equals("https") && request.getServerPort() == 443)) {
            dataURL = request.getScheme() + "://" + request.getServerName() + request.getContextPath() + Servlet
                    + ";jsessionid=" + session.getId();
        } else {
            dataURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + request.getContextPath() + Servlet + ";jsessionid=" + session.getId();
        }
    }
    logger.debug("Generated URL: " + dataURL);
    return dataURL;
}

From source file:gov.nih.nci.ispy.web.taglib.CatCorrPlotTag.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();

    ISPYCategoricalCorrelationFinding corrFinding = (ISPYCategoricalCorrelationFinding) businessTierCache
            .getSessionFinding(session.getId(), taskId);

    try {/*from  w  w w  .j a v a  2s.c o  m*/
        List<DataPointVector> dataSet = corrFinding.getDataVectors();
        List<ReporterInfo> reporterInfoList = corrFinding.getCatCorrRequest().getReporters();

        //get better labels for X and Y axis.
        ContinuousType ct = corrFinding.getContType();
        String xLabel, yLabel;
        if (ct == ContinuousType.GENE) {
            yLabel = "Log base 2 expression value";
        } else {
            yLabel = ct.toString();
        }

        //if there are reporters involved then send them in so that they can be used to create
        //a series.

        ISPYCategoricalCorrelationPlot plot = new ISPYCategoricalCorrelationPlot(dataSet, reporterInfoList,
                "Category", yLabel, corrFinding.getContType(), ColorByType.CLINICALRESPONSE);

        chart = plot.getChart();
        ISPYImageFileHandler imageHandler = new ISPYImageFileHandler(session.getId(), "png", 650, 600);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        String finalURLpath = imageHandler.getFinalURLPath();
        /*
         * Create the actual charts, writing it to the session temp folder
        */
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        String mapName = imageHandler.createUniqueMapName();
        //PrintWriter writer = new PrintWriter(new FileWriter(mapName));
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info);
        //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true);
        //writer.close();

        /*   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(ImageMapUtil.getBoundingRectImageMapTag(mapName, true, info));
        finalURLpath = finalURLpath.replace("\\", "/");
        long randomness = System.currentTimeMillis(); //prevent image caching
        out.print("<img id=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?" + randomness
                + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

        //(imageHandler.getImageTag(mapFileName));

    } 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:edu.harvard.i2b2.fhir.oauth2.ws.OAuth2AuthzEndpoint.java

String successfulResponse(HttpServletRequest request)//, String scope, String patientId, String state)
        throws OAuthSystemException, URISyntaxException, OAuthProblemException {
    OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
    OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());

    String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);

    OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request,
            HttpServletResponse.SC_FOUND);

    String redirectURI = oauthRequest.getRedirectURI();

    if (responseType.equals(ResponseType.CODE.toString())) {
        String authorizationCode = oauthIssuerImpl.authorizationCode();

        logger.info("generated authorizationCode:" + authorizationCode);
        builder.setCode(authorizationCode);

        HttpSession session = request.getSession();
        session.setAttribute("authorizationCode", authorizationCode);
        logger.info("put generated authcode " + session.getAttribute("authorizationCode") + " in session "
                + session.getId());

    }//from  w w w.j  av  a  2s. c  o  m
    URI fhirBase = HttpHelper.getBasePath(request, serverConfigs);
    String uri = fhirBase.toString();
    uri = uri.substring(0, uri.length() - 1);//chopping of last /
    uri = uri.substring(0, uri.lastIndexOf('/')) + "/";
    OAuthResponse Oresponse = builder.location(redirectURI).setParam("aud", uri).buildQueryMessage();
    URI url = new URI(Oresponse.getLocationUri());

    return url.toString();
}

From source file:org.apache.struts.apps.mailreader.actions.BaseAction.java

/**
 * <p>//from  w  w  w  .  j  a  va 2s  . c  o  m
 * Store User object in client session.
 * If user object is null, any existing user object is removed.
 * </p>
 *
 * @param request The request we are processing
 * @param user    The user object returned from the database
 */
void doCacheUser(HttpServletRequest request, User user) {

    HttpSession session = request.getSession();
    session.setAttribute(Constants.USER_KEY, user);
    if (log.isDebugEnabled()) {
        log.debug("LogonAction: User '" + user.getUsername() + "' logged on in session " + session.getId());
    }
}

From source file:at.gv.egiz.pdfas.web.helper.PdfAsHelper.java

public static void injectCertificate(HttpServletRequest request, HttpServletResponse response,
        InfoboxReadResponseType infoboxReadResponseType, ServletContext context) throws Exception {

    HttpSession session = request.getSession();
    StatusRequest statusRequest = (StatusRequest) session.getAttribute(PDF_STATUS);

    if (statusRequest == null) {
        throw new PdfAsWebException("No Signature running in session:" + session.getId());
    }/*from   www.  j  a va 2s  .co  m*/

    statusRequest.setCertificate(getCertificate(infoboxReadResponseType));
    statusRequest = pdfAs.process(statusRequest);
    session.setAttribute(PDF_STATUS, statusRequest);

    PdfAsHelper.process(request, response, context);
}