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:pivotal.au.se.gemfirexdweb.controller.LoginController.java

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, HttpSession session) throws Exception {
    logger.debug("Received request to show login page");

    String vcapServices = null;/*www  . ja va2  s  . c o  m*/
    vcapServices = System.getenv().get("VCAP_SERVICES");

    if (vcapServices != null) {
        if (vcapServices.length() > 0) {
            try {
                // we have a bound application to HAWQ possibly get connect details.
                logger.debug("PCFHawqWeb bound to PHD service...");

                JSONObject GemFireXDURI = (JSONObject) getPCFObject(vcapServices.trim());

                String username = "", password = "";
                String pcfurl = (String) GemFireXDURI.get("uri");

                String[] splitStr = pcfurl.split(";");

                for (String s : splitStr) {
                    String tmp = "";
                    int length = 0, startpos = 0;

                    if (s.startsWith("user")) {
                        length = s.length();
                        startpos = s.indexOf("=");

                        username = s.substring(startpos + 1, length);
                    } else if (s.startsWith("password")) {
                        length = s.length();
                        startpos = s.indexOf("=");

                        password = s.substring(startpos + 1, length);
                    }

                }

                logger.debug("\n---- Ready to roll ----");
                logger.debug("url = " + pcfurl);
                logger.debug("username = " + username);
                logger.debug("password = " + password);

                logger.debug("----");

                ConnectionManager cm = ConnectionManager.getInstance();
                Connection conn;

                conn = AdminUtil.getNewConnection(pcfurl);

                SQLFireJDBCConnection newConn = new SQLFireJDBCConnection(conn, pcfurl,
                        new java.util.Date().toString(), username);

                cm.addConnection(newConn, session.getId());

                session.setAttribute("user_key", session.getId());
                session.setAttribute("user", username);
                session.setAttribute("schema", username);
                session.setAttribute("url", pcfurl);
                session.setAttribute("prefs", new UserPref());
                session.setAttribute("history", new LinkedList());
                session.setAttribute("connectedAt", new java.util.Date().toString());

                Map<String, String> schemaMap = AdminUtil.getSchemaMap();

                // get schema count now
                schemaMap = QueryUtil.populateSchemaMap(conn, schemaMap, username);

                session.setAttribute("schemaMap", schemaMap);

                // This will resolve to /WEB-INF/jsp/main.jsp
                return "main";
            } catch (Exception ex) {
                model.addAttribute("error", ex.getMessage());
                model.addAttribute("loginAttribute", new Login());
                // This will resolve to /WEB-INF/jsp/loginpage.jsp
                return "loginpage";
            }

        }
    }

    // Create new QueryWindow and add to model
    // This is the formBackingObject
    Login login = new Login();
    login.setUrl("jdbc:gemfirexd://localhost:1527/");

    model.addAttribute("loginAttribute", login);
    // This will resolve to /WEB-INF/jsp/loginpage.jsp
    return "loginpage";
}

From source file:pivotal.au.se.gemfirexdweb.controller.QueryController.java

@RequestMapping(value = "/query", method = RequestMethod.POST)
public String worksheetAction(@ModelAttribute("queryAttribute") QueryWindow queryAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {/* w ww  .j  av a  2s.  c o  m*/
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action SQL from query worksheet");
    logger.info(queryAttribute);

    UserPref userPrefs = (UserPref) session.getAttribute("prefs");

    ConnectionManager cm = ConnectionManager.getInstance();

    if (queryAttribute.getQuery() != null) {

        if (queryAttribute.getSaveWorksheet().equals("Y")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment; filename=" + FILENAME);

            ServletOutputStream out = response.getOutputStream();
            out.println(queryAttribute.getQuery());
            out.close();
            return null;
        }

        // retrieve connection
        Connection conn = cm.getConnection(session.getId());
        String query = queryAttribute.getQuery().trim();
        logger.debug("Query = " + query);

        String[] splitQueryStr = spiltQuery(query);

        CommandResult result = new CommandResult();

        if (query.length() > 0) {
            if (splitQueryStr.length == 1) {
                String s = checkForComments(query);
                s = s.trim();

                if (determineQueryType(s).equals("SELECT")) {
                    try {
                        final String explain = queryAttribute.getExplainPlan();
                        if (!explain.equals("N")) {
                            logger.debug("Need to run explain plan.");

                            String explainString = "";

                            if (explain.equals("Y")) {
                                explainString = "explain as xml %s";
                            } else if (explain.equals("T")) {
                                explainString = "explain %s";
                            }

                            String xPlan = QueryUtil.runExplainPlan(conn, String.format(explainString, query));
                            logger.debug("received xPath : " + xPlan);

                            if (explain.equals("Y")) {
                                model.addAttribute("explainresult", xPlan);
                            } else if (explain.equals("T")) {
                                model.addAttribute("explaintxtresult", xPlan);
                            }
                        } else {

                            if (queryAttribute.getShowMember().equals("Y")) {
                                String replace = "select dsid() as \"Member\",";

                                s = query.toLowerCase().replaceFirst("select", replace);
                            }

                            long start = System.currentTimeMillis();
                            Result res = QueryUtil.runQuery(conn, s, userPrefs.getMaxRecordsinSQLQueryWindow());
                            long end = System.currentTimeMillis();

                            double timeTaken = new Double(end - start).doubleValue();
                            DecimalFormat df = new DecimalFormat("#.##");

                            model.addAttribute("queryResults", res);
                            model.addAttribute("query", s);
                            model.addAttribute("querysql", s);
                            if (queryAttribute.getQueryCount().equals("Y")) {
                                model.addAttribute("queryResultCount", res.getRowCount());
                            }

                            if (queryAttribute.getElapsedTime().equals("Y")) {
                                model.addAttribute("elapsedTime", df.format(timeTaken / 1000));
                            }

                            addCommandToHistory(session, userPrefs, s);

                        }
                    } catch (Exception ex) {
                        result.setCommand(s);
                        result.setMessage(ex.getMessage() == null ? "Unable to run query" : ex.getMessage());
                        result.setRows(-1);
                        model.addAttribute("result", result);
                        model.addAttribute("query", s);
                    }
                } else {
                    if (s.length() > 0) {
                        if (determineQueryType(s).equals("COMMIT")) {
                            result = QueryUtil.runCommitOrRollback(conn, true, queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        } else if (determineQueryType(s).equals("ROLLBACK")) {
                            result = QueryUtil.runCommitOrRollback(conn, false,
                                    queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        } else if (determineQueryType(s).equals("CALL")) {

                            String procName = getProcName(s);

                            if (procName != null) {
                                String schema = null;

                                int x = procName.indexOf(".");
                                if (x != -1) {
                                    String newProcName = procName.substring((procName.indexOf(".") + 1));
                                    schema = procName.substring(0, (procName.indexOf(".")));
                                    procName = newProcName;
                                } else {
                                    schema = (String) session.getAttribute("schema");
                                }

                                logger.debug("schema for stored procedure = " + schema);
                                logger.debug("call statement called for proc with name " + procName);

                                // need to get schema name to check proc details
                                int numberOfDynamicResultSets = QueryUtil.checkForDynamicResultSetProc(conn,
                                        schema, procName);

                                if (numberOfDynamicResultSets > 0) {
                                    logger.debug("call statement with " + numberOfDynamicResultSets
                                            + " dynamic resultset(s)");
                                    try {
                                        List<Result> procResults = QueryUtil.runStoredprocWithResultSet(conn, s,
                                                userPrefs.getMaxRecordsinSQLQueryWindow(),
                                                numberOfDynamicResultSets);
                                        model.addAttribute("procresults", procResults);
                                        model.addAttribute("callstatement", procName);
                                        model.addAttribute("dynamicresults", numberOfDynamicResultSets);
                                        addCommandToHistory(session, userPrefs, s);
                                    } catch (Exception ex) {
                                        result.setCommand(s);
                                        result.setMessage(ex.getMessage() == null ? "Unable to run query"
                                                : ex.getMessage());
                                        result.setRows(-1);
                                        model.addAttribute("result", result);
                                        model.addAttribute("query", s);
                                    }
                                } else {
                                    result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                                    model.addAttribute("result", result);
                                    if (result.getMessage().startsWith("SUCCESS")) {
                                        addCommandToHistory(session, userPrefs, s);
                                    }
                                }
                            } else {
                                result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                                model.addAttribute("result", result);
                                if (result.getMessage().startsWith("SUCCESS")) {
                                    addCommandToHistory(session, userPrefs, s);
                                }
                            }
                        } else {
                            result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        }

                    }
                }

            } else {
                logger.debug("multiple SQL statements need to be executed");
                SortedMap<String, Object> queryResults = handleMultipleStatements(splitQueryStr, conn,
                        userPrefs, queryAttribute, session);
                logger.debug("keys : " + queryResults.keySet());
                model.addAttribute("sqlResultMap", queryResults);
                model.addAttribute("statementsExecuted", queryResults.size());

            }
        }
    } else {
        if (ServletFileUpload.isMultipartContent(request)) {
            logger.debug("is multipartcontent request");
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> fileItemsList = upload.parseRequest(request);

            logger.debug("fileItemList size = " + fileItemsList.size());
            Iterator<?> it = fileItemsList.iterator();
            while (it.hasNext()) {
                FileItem fileItemTemp = (FileItem) it.next();
                if (fileItemTemp.getFieldName().equals("sqlfilename")) {
                    QueryWindow qw = new QueryWindow();
                    qw.setQuery(fileItemTemp.getString());
                    model.addAttribute("queryAttribute", qw);
                    model.addAttribute("sqlfile", fileItemTemp.getName());
                }
            }
        }
    }

    return "query";
}

From source file:com.idega.slide.business.IWSlideServiceBean.java

@SuppressWarnings("deprecation")
private HttpClient getHttpClient(HttpURL url, UsernamePasswordCredentials credentials) throws Exception {
    HttpSession currentSession = getCurrentSession();

    HttpState state = new WebdavState();
    AuthScope authScope = new AuthScope(url.getHost(), url.getPort());
    state.setCredentials(authScope, credentials);
    if (currentSession != null) {
        IWTimestamp iwExpires = new IWTimestamp(System.currentTimeMillis());
        iwExpires.setMinute(iwExpires.getMinute() + 30);
        Date expires = new Date(iwExpires.getTimestamp().getTime());

        boolean secure = url instanceof HttpsURL;

        Cookie cookie = new Cookie(url.getHost(), CoreConstants.PARAMETER_SESSION_ID, currentSession.getId(),
                CoreConstants.SLASH, expires, secure);
        state.addCookie(cookie);/*from w  ww.j  a va  2s .  co  m*/
    }

    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    client.setState(state);

    HostConfiguration hostConfig = client.getHostConfiguration();
    hostConfig.setHost(url);

    Credentials hostCredentials = null;

    if (credentials == null) {
        String userName = url.getUser();
        if (userName != null && userName.length() > 0) {
            hostCredentials = new UsernamePasswordCredentials(userName, url.getPassword());
        }
    }

    if (hostCredentials != null) {
        HttpState clientState = client.getState();
        clientState.setCredentials(null, url.getHost(), hostCredentials);
        clientState.setAuthenticationPreemptive(true);
    }

    return client;
}

From source file:gov.nih.nci.security.upt.actions.CommonDoubleAssociationAction.java

public String loadProtectionElementPrivilegesAssociation(BaseDoubleAssociationForm baseDoubleAssociationForm)
        throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession();

    if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) {
        if (logDoubleAssociation.isDebugEnabled())
            logDoubleAssociation.debug("||" + baseDoubleAssociationForm.getFormName()
                    + "|loadProtectionElementPrivilegesAssociation|Failure|No Session or User Object Forwarding to the Login Page||");
        return ForwardConstants.LOGIN_PAGE;
    }//from w  w w. j  a va 2 s.  co  m
    session.setAttribute(DisplayConstants.CREATE_WORKFLOW, "0");
    try {
        UserProvisioningManager userProvisioningManager = (UserProvisioningManager) (request.getSession())
                .getAttribute(DisplayConstants.USER_PROVISIONING_MANAGER);
        baseDoubleAssociationForm.setRequest(request);
        Collection temp = baseDoubleAssociationForm
                .buildProtectionElementPrivilegesObject(userProvisioningManager);

        List associatedProtectionElementPrivilegesContexts = new ArrayList();
        Iterator iterator = temp.iterator();
        while (iterator.hasNext()) {
            associatedProtectionElementPrivilegesContexts.add(iterator.next());
        }
        Collections.sort(associatedProtectionElementPrivilegesContexts,
                new ProtectionElementPrivilegesContextComparator());

        if (associatedProtectionElementPrivilegesContexts != null
                && associatedProtectionElementPrivilegesContexts.size() != 0)
            session.setAttribute(DisplayConstants.AVAILABLE_PROTECTIONELEMENTPRIVILEGESCONTEXT_SET,
                    associatedProtectionElementPrivilegesContexts);
        else {
            addActionError("No Associated Protection Element or Privileges found");
            if (logDoubleAssociation.isDebugEnabled())
                logDoubleAssociation.debug(session.getId() + "|"
                        + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                        + baseDoubleAssociationForm.getFormName()
                        + "|loadProtectionElementPrivilegesAssociation|Failure|No Protection Element Privileges Association for the "
                        + baseDoubleAssociationForm.getFormName() + " object|"
                        + baseDoubleAssociationForm.toString() + "|");
            return ForwardConstants.LOAD_PROTECTIONELEMENTPRIVILEGESASSOCIATION_FAILURE;
        }
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (logDoubleAssociation.isDebugEnabled())
            logDoubleAssociation.debug(session.getId() + "|"
                    + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                    + baseDoubleAssociationForm.getFormName()
                    + "|loadProtectionElementPrivilegesAssociation|Failure|Error Loading Protection Element Privileges Association for the "
                    + baseDoubleAssociationForm.getFormName() + " object|"
                    + baseDoubleAssociationForm.toString() + "|" + cse.getMessage());
    }
    if (logDoubleAssociation.isDebugEnabled())
        logDoubleAssociation.debug(session.getId() + "|"
                + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                + baseDoubleAssociationForm.getFormName()
                + "|loadProtectionElementPrivilegesAssociation|Success|Success in Loading Protection Element Privileges Association for "
                + baseDoubleAssociationForm.getFormName() + " object|" + baseDoubleAssociationForm.toString()
                + "|");
    return ForwardConstants.LOAD_PROTECTIONELEMENTPRIVILEGESASSOCIATION_SUCCESS;
}

From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

private void updateSessionAndHeader(HttpServletRequest request, HttpSession session, Principal principal) {

    if (principal != null) {
        final String[] principalParts = principal.getName().split("@");
        session.setAttribute(USERNAME_SESSION_KEY, principalParts[0]);
        session.setAttribute(REALM_SESSION_KEY, principalParts[1]);
        debug("Setting extra session users info name={0} realm={1}", principalParts[0], principalParts[1]);

        // TODO Implement userHeader on a generic way
        /*//from w  ww  . j  av  a  2s.c  o m
         * if(this.userHeader!=null && !"".equals(userHeader.trim())){
         * request.adHeader(...) ? }
         */
    }

    if (this.sessionAttributes != null) {
        for (final Map.Entry<String, String> entry : this.sessionAttributes.entrySet()) {
            session.setAttribute(entry.getKey(), entry.getValue());
        }
        debug("Setting extra session pairs : {0}", this.sessionAttributes);
    }

    debug("Session was update sessionId {0} for user {1}", session.getId(), principal);
}

From source file:Controller.UserController.java

@RequestMapping(value = "/Booking")
public String booking(HttpServletRequest request, HttpSession session) {
    try {//  ww w.  j  a v a2  s. c  om
        String finalUrl = "redirect:/";
        if (request.getParameter("language") != null) {
            finalUrl = "redirect:/" + "?language=" + request.getParameter("language");
        }

        // no adults
        String noAdultsStr = request.getParameter("numberOfAdults");
        String[] noChildsStrs = request.getParameterValues("numberOfChilds");
        String packageIDStr = request.getParameter("packageID");
        String tripDate = request.getParameter("selectedDate");
        String tripTime = request.getParameter("selectedTime");
        if (tripperService.tripperBooking(noAdultsStr, noChildsStrs, packageIDStr, tripDate, tripTime)) {
            finalUrl = "redirect:/Package/" + packageIDStr;
        }
        return finalUrl;
    } catch (Exception e) {
        String content = "Function: UserController - book\n" + "***Input***\n" + "numberOfAdults: "
                + request.getParameter("numberOfAdults") + "\n" + "numberOfChilds: "
                + request.getParameterValues("numberOfChilds") + "\n" + "packageIDStr: "
                + request.getParameter("packageID") + "\n" + "tripDate: " + request.getParameter("selectedDate")
                + "\n" + "selectedTime: " + request.getParameter("selectedTime") + "\n" + "**********\n"
                + "****Error****\n" + e.getMessage() + "\n" + "**********";
        request.setAttribute("errorID", session.getId());
        request.setAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}

From source file:com.indicator_engine.controller.LoginController.java

@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView processLoginForm(@Valid @ModelAttribute("loginForm") LoginForm loginForm,
        BindingResult bindingResult, HttpSession session) {

    ModelAndView model;//ww  w .ja  v  a  2s.c o m
    if (bindingResult.hasErrors()) {
        return new ModelAndView("app/login");
    }
    boolean authid = false;
    String user_role = "INVALID";
    String admin_role = "NO";
    boolean activation_status = false;
    String sessionUserName = null;
    String loginMsg = null;
    UserCredentialsDao userDetailsBean = (UserCredentialsDao) appContext.getBean("userDetails");
    SecurityRoleEntityDao securityRoleEntityBean = (SecurityRoleEntityDao) appContext
            .getBean("userRoleDetails");
    String username = loginForm.getUserName();
    String password = loginForm.getPassword();
    List<UserCredentials> selectedUserList = userDetailsBean.searchByUserName(username);
    for (UserCredentials eachuser : selectedUserList) {
        log.info("---------------------------------------------------");
        log.info(eachuser.getUname());
        log.info(eachuser.getPassword());
        if (username.equals(eachuser.getUname())) {
            if (encoder.matches(password, eachuser.getPassword())) {
                authid = true;
                sessionUserName = username;
                if (eachuser.getActivation_status()) {
                    activation_status = true;
                    List<SecurityRoleEntity> roleEntity = securityRoleEntityBean
                            .searchRolesByID(eachuser.getUid());
                    for (SecurityRoleEntity roles : roleEntity) {
                        if (roles.getRole().equals("ROLE_ADMIN"))
                            admin_role = "YES";
                        if (roles.getRole().equals("ROLE_USER"))
                            user_role = "ROLE_USER";
                    }
                    break;
                }
            }
        }
    }
    log.info("---------------------------------------------------");
    log.info("Debug Login : \n");
    log.info("Debug Login : Auth ID : \t" + authid);
    log.info("Debug Login : Activation Status : \t" + activation_status);
    log.info("Debug Login : Session User Name : \t" + sessionUserName);
    log.info("Debug Login : Role : \t" + user_role);
    if (authid && activation_status) {
        String sid = session.getId();
        model = new ModelAndView("app/home");
        model.addObject("sid", sid);
        model.addObject("loggedIn", "true");
        model.addObject("userName", sessionUserName);
        model.addObject("activationStatus", "true");
        model.addObject("role", user_role);
        model.addObject("admin_access", admin_role);
    } else if (authid && !activation_status) {
        String sid = session.getId();
        model = new ModelAndView("app/activate");
        model.addObject("sid", sid);
        model.addObject("loggedIn", "true");
        model.addObject("userName", sessionUserName);
        model.addObject("activationStatus", "false");
        model.addObject("role", user_role);
        model.addObject("admin_access", admin_role);
    } else
        model = new ModelAndView("app/login");
    log.info("Debug Login : Selected Model : \t" + model);
    return model;
}

From source file:Controller.UserController.java

@RequestMapping(value = "/MakeReview", method = RequestMethod.POST)
public String makeReview(HttpServletRequest request, HttpSession session) {
    try {/*from  ww w . j  av a  2 s . com*/
        AccountSession account = (AccountSession) session.getAttribute("account");
        int packageID = Integer.valueOf(request.getParameter("packageID"));
        String bookingID = String.valueOf(request.getParameter("bookingID"));
        String reviewDetail = request.getParameter("reviewDetail");
        double score = Double.valueOf(request.getParameter("rateScore"));
        int Professionlism = Integer.valueOf(request.getParameter("Professionlism"));
        int StaffAttitude = Integer.valueOf(request.getParameter("StaffAttitude"));
        int Convenient = Integer.valueOf(request.getParameter("Convenient"));
        int Satisfaction = Integer.valueOf(request.getParameter("Satisfaction"));
        int AmenityQuality = Integer.valueOf(request.getParameter("AmenityQuality"));
        int Cleanliness = Integer.valueOf(request.getParameter("Cleanliness"));
        boolean result = tripperService.makeReview(account.getId(), bookingID, packageID, reviewDetail, score,
                Professionlism, StaffAttitude, Convenient, Satisfaction, AmenityQuality, Cleanliness);

        return "tripper/reviewSuccess";
    } catch (Exception e) {
        String content = "Function: UserController - makeReview\n" + "***Input***\n" + "packageID: "
                + request.getParameter("packageID") + "\n" + "reviewDetail: "
                + request.getParameter("reviewDetail") + "\n" + "score: " + request.getParameter("score") + "\n"
                + "**********\n" + "****Error****\n" + e.getMessage() + "\n" + "**********";
        request.setAttribute("errorID", session.getId());
        request.setAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}

From source file:org.apache.stratos.rest.endpoint.api.StratosApiV41.java

/**
 * This method gets called by the client who are interested in using session mechanism to authenticate
 * themselves in subsequent calls. This method call get authenticated by the basic authenticator.
 * Once the authenticated call received, the method creates a session and returns the session id.
 *
 * @return The session id related with the session
 *//* w w  w.jav  a 2 s  .  c om*/
@GET
@Path("/session")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/login")
public Response getSession() {
    HttpSession httpSession = httpServletRequest.getSession(true);//create session if not found
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    httpSession.setAttribute("userName", carbonContext.getUsername());
    httpSession.setAttribute("tenantDomain", carbonContext.getTenantDomain());
    httpSession.setAttribute("tenantId", carbonContext.getTenantId());

    String sessionId = httpSession.getId();
    return Response.ok().header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
            .entity(Utils.buildAuthenticationSuccessMessage(sessionId)).build();
}

From source file:Com.Dispatcher.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w  w  w  .  ja  v a2s  .c om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    File file;

    Boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        return;
    }

    // Create a session object if it is already not  created.
    HttpSession session = request.getSession(true);
    // Get session creation time.
    Date createTime = new Date(session.getCreationTime());
    // Get last access time of this web page.
    Date lastAccessTime = new Date(session.getLastAccessedTime());

    String visitCountKey = new String("visitCount");
    String userIDKey = new String("userID");
    String userID = new String("ABCD");
    Integer visitCount = (Integer) session.getAttribute(visitCountKey);

    // Check if this is new comer on your web page.
    if (visitCount == null) {

        session.setAttribute(userIDKey, userID);
    } else {

        visitCount++;
        userID = (String) session.getAttribute(userIDKey);
    }
    session.setAttribute(visitCountKey, visitCount);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(fileRepository));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file to server in "/uploads/{sessionID}/"   
                String clientDataPath = getServletContext().getInitParameter("clientFolder");
                // TODO clear the client folder here
                // FileUtils.deleteDirectory(new File("clientDataPath"));
                if (fileName.lastIndexOf("\\") >= 0) {

                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/")));
                } else {
                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/") + 1));
                }
                fi.write(file);
            }
        }
    } catch (Exception ex) {
        System.out.println("Failure: File Upload");
        System.out.println(ex);
        //TODO show error page for website
    }
    System.out.println("file uploaded");
    // TODO make the fileRepository Folder generic so it doesnt need to be changed
    // for each migration of the program to a different server
    File input = new File((String) session.getAttribute("inputFolder"));
    File output = new File((String) session.getAttribute("outputFolder"));
    File profile = new File(getServletContext().getInitParameter("profileFolder"));
    File hintsXML = new File(getServletContext().getInitParameter("hintsXML"));

    System.out.println("folders created");

    Controller controller = new Controller(input, output, profile, hintsXML);
    HashMap initialArtifacts = controller.initialArtifacts();
    session.setAttribute("Controller", controller);

    System.out.println("Initialisation of profiles for session (" + session.getId() + ") is complete\n"
            + "Awaiting user to update parameters to generate next generation of results.\n");

    String json = new Gson().toJson(initialArtifacts);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}