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:Controller.UserController.java

@RequestMapping(value = "/Payment", method = RequestMethod.POST)
public String payment(HttpServletRequest request) {
    try {//from   w ww .ja  v a  2s  . c  o m
        boolean validate = false;
        boolean makePayment = false;
        AccountSession account = (AccountSession) request.getSession().getAttribute("account");
        String selectedDate = request.getParameter("selectedDate");
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        int numberOfAdults, numberOfChilds, packageID;
        int cvv = 0;
        String paymentType = request.getParameter("paymentMethod");
        PackageDTO packgeDTO = null;
        List<Double> prices = new ArrayList<Double>();
        Double total = (Double) 0.0;
        try {
            numberOfAdults = Integer.parseInt(request.getParameter("numberOfAdults"));
        } catch (NumberFormatException e) {
            numberOfAdults = 0;
        }
        try {
            numberOfChilds = Integer.parseInt(request.getParameter("numberOfChilds"));
        } catch (NumberFormatException e) {
            numberOfChilds = 0;
        }
        try {
            packageID = Integer.parseInt(request.getParameter("packageID"));
        } catch (NumberFormatException e) {
            packageID = 0;
        }

        if (packageID > 0 && numberOfAdults > 0) {
            packgeDTO = tripperService.getPackageForPayment(packageID);
            prices = tripperService.getPriceOfSelectedDate(selectedDate, packgeDTO);
            if (prices.get(0) > 0) {
                if (prices.get(1) <= 0 || (prices.get(1) > 0 && numberOfChilds > 0)) {
                    if (!packgeDTO.isIsPrivateTour()) {
                        total = ((prices.get(0) * numberOfAdults + numberOfChilds * prices.get(1))
                                * (100 - packgeDTO.getYoutripperPercentage()) / 100);
                    } else {
                        int noOfPackages = (int) Math.round(Math
                                .ceil((float) (numberOfAdults + numberOfChilds) / packgeDTO.getMinTripper()));
                        total = (noOfPackages * prices.get(0) * (100 - packgeDTO.getYoutripperPercentage())
                                / 100);
                    }

                    validate = true;
                }
            }
        }
        //Make credit Card payment
        if (validate) {
            if (paymentType.equals("creditCard")) {
                String cardType = request.getParameter("cardType");
                String cardNumber = request.getParameter("cardNumber");
                int expireMonth = Integer.parseInt(request.getParameter("expireMonth"));
                int expireYear = Integer.parseInt(request.getParameter("expireYear"));
                try {
                    cvv = Integer.parseInt(request.getParameter("cvv"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                makePayment = tripperService.paywithCreditCard(cardType, cardNumber, expireMonth, expireYear,
                        cvv, firstName, lastName, "USD", String.format(Locale.US, "%.2f", total),
                        "Booking Trip:" + packageID);
            } else if (paymentType.equals("paypal")) {
                request.setAttribute("packageID", packageID);
                request.setAttribute("selectedDate", selectedDate);
                request.setAttribute("numberOfChilds", numberOfChilds);
                request.setAttribute("numberOfAdults", numberOfAdults);
                request.setAttribute("prices", prices);
                request.setAttribute("totalPrice", String.format(Locale.US, "%.2f", total));
                return "forward:/Tripper/PaywithPaypal";
            }
            if (makePayment) {
                String code = tripperService.getBookingCode();
                tripperService.insertBooking(code, packageID, selectedDate, numberOfChilds, numberOfAdults,
                        account.getId());
                int providerID = packgeDTO.getProviderID();
                int tripperID = account.getId();
                boolean notifyForProvider = providerService
                        .insertNewProviderSystemNotification("{\"URL\":\"Noti/ProviderViewBooking/" + code
                                + "\",\"Message\":\"You have a new booking\"}", false, providerID);
                boolean notifyForTripper = tripperService
                        .insertNewTripperSystemNotification("{\"URL\":\"Noti/TripperViewBooking/" + code
                                + "\",\"Message\":\"You had booked a trip!\"}", false, tripperID);
                String providerNoti = providerService.getProviderNewNotification(providerID);
                template.convertAndSend("/topic/Notifications/Provider/" + providerID, providerNoti);
                String tripperNoti = tripperService.getTripperNewNotification(tripperID);
                template.convertAndSend("/topic/Notifications/Tripper/" + tripperID, tripperNoti);
                return "/tripper/paymentSuccess";
            } else {
                request.setAttribute("message", "Your credit card is declined");
                request.setAttribute("selectedDate", selectedDate);
                request.setAttribute("numberOfAdults", numberOfAdults);
                request.setAttribute("numberOfChilds", numberOfChilds);
                request.setAttribute("packageID", packageID);
                return "forward:/Tripper/Book";
            }
        }
        if (request.getParameter("language") != null) {
            return "redirect:/Common" + "?language=" + request.getParameter("language");
        } else {
            return "redirect:/Common";
        }

    } catch (Exception e) {
        HttpSession session = request.getSession(true);
        String content = "Function: UserController - payment\n" + "***Input***\n" + "selectedDate: "
                + request.getParameter("selectedDate") + "\n" + "firstName: "
                + request.getParameter("firstName") + "\n" + "lastName: " + request.getParameter("lastName")
                + "\n" + "paymentMethod: " + request.getParameter("paymentMethod") + "\n" + "numberOfAdults: "
                + request.getParameter("numberOfAdults") + "\n" + "numberOfChilds: "
                + request.getParameter("numberOfChilds") + "\n" + "packageID: "
                + request.getParameter("packageID") + "\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:controller.Upload.java

/**
 * Servlet implementation class UploadServlet
 *///from   w  ww.  j av a 2s . c  o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);
    String fileName = "", newname = "";
    try {
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                //                    fileName = (String)session.getId() + new File(item.getName()).getName();
                //                    String filePath = uploadFolder + File.separator + fileName;
                fileName = new File(item.getName()).getName();
                newname = (String) session.getId() + fileName.substring(fileName.lastIndexOf("."));
                String filePath = uploadFolder + File.separator + newname;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                item.write(uploadedFile);
            }
        }
        userDao ud = new userDao();
        ud.changeuserpic((int) session.getAttribute("userID"), newname);
        // displays done.jsp page after upload finished
        getServletContext().getRequestDispatcher("/done.jsp").forward(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:com.w20e.socrates.servlet.WebsurveyServlet.java

/**
 * Do the thing... If there is no runner (context) in the session, create a
 * new session based on the given id parameter. If there is also no id
 * parameter, it's an error. If the id parameter is given, create a new
 * runner context anyway. If a parameter called regkey is given, this
 * parameter is used for storage and possibly retrieval of the instance.
 * This way, a user may provide it's own key.
 * /*w w  w  .  j  a  v  a2s . c  o m*/
 * @param req
 *            The request
 * @param res
 *            The response
 * @throws IOException
 *             when some io error occurs
 * @throws ServletException
 *             when the servlet fails
 */
public final void doPost(final HttpServletRequest req, final HttpServletResponse res)
        throws IOException, ServletException {

    // Always use UTF!
    res.setContentType("text/html;charset=UTF-8");
    req.setCharacterEncoding("UTF-8");

    // Thou shalst not cache...
    res.addHeader("Cache-Control", "no-cache");
    res.addHeader("Pragma", "No-Cache");

    HttpSession session = this.sessionMgr.getSession(req);

    // If we don't have a session now, we might as well call it a day...
    if (session == null) {

        if (ServletHelper.getCookie(req, "JSESSIONID") != null) {
            LOGGER.warning("Session timeout");
            res.sendRedirect("session-timeout.html");
            res.getOutputStream().flush();
            return;
        } else {
            LOGGER.severe("No session created");
            res.sendRedirect("session-creation-error.html");
            res.getOutputStream().flush();
            return;
        }
    }

    // Hold all enable/disable options
    //
    Map<String, String> options = ServletHelper.determineOptions(req);

    // If no runner yet for this session, create one. We should have
    // startup param's for the runner, like the questionnaire to run, and
    // the locale. If these are not available, check for regkey. Else, all fails.
    //
    if (session.getAttribute("runnerCtx") == null) {

        LOGGER.finer("Session instantiated with id " + session.getId());
        LOGGER.fine("No runner context available in session; creating one");

        if (req.getParameter("id") == null && req.getParameter("regkey") == null) {
            LOGGER.warning("No id nor regkey parameter in request");
            try {
                res.sendRedirect("session-creation-error.html");
                this.sessionMgr.invalidateSession(req);
                res.getOutputStream().flush();
            } catch (IOException e) {
                LOGGER.severe("Couldn't even send error message..." + e.getMessage());
            }
            return;
        }

        if (!initializeRunner(req, res, session, options)) {
            LOGGER.severe("Could not create runner context. Bye for now.");
            return;
        }
    }

    // Okido, by now we should have a session, and a valid runner context
    // stored in the session.
    //
    try {
        WebsurveyContext wwCtx = (WebsurveyContext) session.getAttribute("runnerCtx");

        // Now let's see whether this session was deserialized.
        //
        if (wwCtx.isInvalid()) {
            LOGGER.info("Serialized session found!");
            // Re-create the context, and attach to WoliWeb context.
            LOGGER.finer("Model id: " + wwCtx.getModelId());
            LOGGER.finer("State id: " + wwCtx.getStateId());
            LOGGER.finer("Locale: " + wwCtx.getLocale());

            URI qUri = QuestionnaireURIFactory.getInstance().determineURI(this.rootDir, wwCtx.getModelId());

            RunnerContextImpl ctx = this.runnerFactory.createContext(qUri, null);
            ctx.setLocale(wwCtx.getLocale());
            ctx.setQuestionnaireId(qUri);
            ctx.getStateManager().setStateById(wwCtx.getStateId());
            ctx.setInstance(wwCtx.getInstance());
            wwCtx.setRunnerContext(ctx);
        }

        RunnerContextImpl ctx = (RunnerContextImpl) wwCtx.getRunnerContext();

        LOGGER.finer("Session id " + session.getId());
        LOGGER.finer("Context id " + ctx.getInstance().getMetaData().get("key"));

        // set locale if requested later on, when the survey is well under way...
        if (req.getParameter("locale") != null && req.getParameter("id") == null) {
            ctx.setLocale(LocaleUtility.getLocale(req.getParameter("locale"), false));
            LOGGER.fine("Locale change requested; set to "
                    + LocaleUtility.getLocale(req.getParameter("locale"), false));
        }

        // even check on locale in instance data...
        try {
            Locale instanceLocale = LocaleUtility
                    .getLocale(ctx.getInstance().getNode("locale").getValue().toString(), false);

            if (instanceLocale != null && instanceLocale != ctx.getLocale()) {
                LOGGER.fine("Locale is set in instance data: " + instanceLocale);
                ctx.setLocale(instanceLocale);
            }
        } catch (Exception ex) {
            // not a problem...
        }

        // Add specific options
        // @todo This should move to the runner creation options.
        if (ctx.getProperty("renderOptions") == null) {
            ctx.setProperty("renderOptions", options);
        } else {
            ((Map<String, String>) ctx.getProperty("renderOptions")).putAll(options);
        }

        Map<String, Object> params = ParameterParser.parseParams(req);

        ctx.setData(params);

        // Do we have initial data already?
        if ("true".equals(options.get("enable_preload_params"))) {
            Node node;
            for (String key : params.keySet()) {
                node = ctx.getInstance().getNode(key);
                if (node != null) {
                    LOGGER.fine("Preloading node value " + params.get(key) + " for node " + node.getName());
                    node.setValue(params.get(key));
                }
            }
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        ctx.setOutputStream(output);

        // @todo: I really don't see why we should re-create the runner for
        // every post. Actually, the factory holds a reference to existing
        // runners, so it is not really bad, but I reckon the context should
        // hold the runner?
        //
        URI qUri = QuestionnaireURIFactory.getInstance().determineURI(this.rootDir, wwCtx.getModelId());

        Runner runner = this.runnerFactory.createRunner(qUri);

        if (req.getParameter("previous") == null) {
            Map<String, Object> meta = ctx.getInstance().getMetaData();
            meta.put("time_" + req.getParameter("stateId"), new Date());
        }

        // Always store stateId in instance, for retrieval of state after
        // serialization.
        //
        if (req.getParameter("stateId") != null) {
            LOGGER.fine("Setting state id to " + req.getParameter("stateId"));
            ctx.getInstance().getMetaData().put("stateId", req.getParameter("stateId"));
            if (!ctx.getStateManager().setStateById(req.getParameter("stateId"))) {
                LOGGER.warning("Couldn't set stateId to " + req.getParameter("stateId"));
            }
        }

        // Go two states back if 'previous' request, and simply execute
        // 'next'.
        if (req.getParameter("previous") != null) {
            ctx.getStateManager().previous();
            RenderState state = ctx.getStateManager().previous();

            LOGGER.finest("Fill data from instance");

            ctx.setProperty("previous", "true");

            if (state != null) {

                // Make sure to fill in existing data, otherwise we'll get
                // an error
                //
                for (Iterator<Renderable> i = state.getItems().iterator(); i.hasNext();) {
                    Renderable r = i.next();
                    if (r instanceof Control) {
                        String name = ((Control) r).getBind();
                        params.put(name, ctx.getInstance().getNode(name).getValue());
                        LOGGER.finest("Set node " + name + " to " + params.get(name));
                    }
                }
            }
        } else {
            ctx.setProperty("previous", "false");
        }

        next(ctx, runner);

        LOGGER.fine("Are we stored yet? " + ctx.getInstance().getMetaData().get("storage-type"));

        // If we submitted, destroy long session
        if ("submit".equals(ctx.getInstance().getMetaData().get("storage-type"))) {
            LOGGER.fine("Invalidating long session");

            String surveyId = ctx.getInstance().getMetaData().get("qId").toString();

            this.sessionMgr.invalidateLongSession(surveyId, req, res);
        }

        // If this was the last action, destroy session.
        if (!runner.hasNext(ctx)) {
            this.sessionMgr.invalidateSession(req);
        }

        res.getOutputStream().write(output.toByteArray());
        res.getOutputStream().flush();

        // free resources...
        ctx.setOutputStream(null);

    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "No runner created", e);
        throw new ServletException("Runner could not be created: " + e.getMessage());
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.createJobs.CreateJobsMainHandler.java

/**
 * Set useful parameters onto the jsp/*  w  w  w.  j  av  a  2s.c  o  m*/
 * 
 * @param request
 * @param bundle
 * @param user
 * @param session
 * @param currentCompanyId
 */
private void setPageParameter(HttpServletRequest request, ResourceBundle bundle, User user, HttpSession session,
        String currentCompanyId) {
    this.setLable(request, bundle);
    request.setAttribute("rand", session.getAttribute("UID_" + session.getId()));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
    String tmpFolderName = sdf.format(new Date()) + "-" + getRandomNumber();
    if (user != null) {
        request.setAttribute("lastSelectedFolder",
                convertFilePath(getLastSelectedFolder(user.getUserId(), SELECTED_FOLDER)).replace("\\",
                        "\\\\"));
    } else {
        request.setAttribute("lastSelectedFolder", "");
    }

    request.setAttribute("baseTmpFolder",
            convertFilePath(AmbFileStoragePathUtils.getCxeDocDir() + File.separator + TMP_FOLDER_NAME)
                    .replace("\\", "\\\\"));
    request.setAttribute("baseStorageFolder", tmpFolderName + "," + currentCompanyId);

    if (request.getParameter("currentFolderName") != null) {
        request.setAttribute("tmpFolderName", convertFilePath(request.getParameter("currentFolderName")));
    } else {
        request.setAttribute("tmpFolderName", tmpFolderName);
        extensionToFileProfileMap = new HashMap<String, List<FileProfileImpl>>();
    }
    SystemConfiguration sysConfig = SystemConfiguration.getInstance();
    boolean useSSL = sysConfig.getBooleanParameter(SystemConfigParamNames.USE_SSL);
    if (useSSL) {
        request.setAttribute("httpProtocolToUse", WebAppConstants.PROTOCOL_HTTPS);
    } else {
        request.setAttribute("httpProtocolToUse", WebAppConstants.PROTOCOL_HTTP);
    }
}

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

@Override
public WebdavExtendedResource getWebdavExtendedResource(String path, UsernamePasswordCredentials credentials,
        boolean localResource) throws HttpException, IOException, RemoteException, RemoteException {

    HttpURL url = getWebdavServerURL(credentials, getPath(path), getWebdavServerURI(), localResource);
    if (url == null) {
        throw new IOException("[IWSlideService] WebdavServerURL could not be retrieved for " + path
                + ", using credentials: " + credentials);
    }/* w  ww .j  a  v a 2s . co m*/

    WebdavExtendedResource resource = null;

    if (localResource && isLocalResourceEnabled()) {
        if (!Domain.isInitialized()) {
            DomainConfig domainConfig = ELUtil.getInstance().getBean(DomainConfig.SPRING_BEAN_IDENTIFIER);
            domainConfig.initialize();
        }

        HttpSession currentSession = getCurrentSession();
        if (currentSession != null) {
            url.setQuery(CoreConstants.PARAMETER_SESSION_ID.toLowerCase(), currentSession.getId());
        }

        try {
            resource = new WebdavLocalResource(getHttpClient(url, credentials));
            resource.setHttpURL(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (resource == null) {
        resource = new WebdavExtendedResource(url);
    }

    return resource;
}

From source file:com.adito.security.DefaultLogonController.java

public synchronized void removeSessionTimeoutBlock(HttpSession session, int sessionTimeoutBlockId) {
    try {/* www  . ja v a  2  s  .  c o m*/
        Map sessionTimeoutBlocks = (Map) session.getAttribute(Constants.SESSION_TIMEOUT_BLOCKS);
        if (sessionTimeoutBlocks != null) {
            String reason = (String) sessionTimeoutBlocks.get(String.valueOf(sessionTimeoutBlockId));
            if (reason == null) {
                log.warn("No session timeout block with id of " + sessionTimeoutBlockId);
            } else {
                sessionTimeoutBlocks.remove(String.valueOf(sessionTimeoutBlockId));
                if (log.isDebugEnabled())
                    log.debug("Removing session timeout block " + sessionTimeoutBlockId + " for session "
                            + session.getId() + " ('" + reason + "'). There are now "
                            + sessionTimeoutBlocks.size() + " reasons not to timeout the session.");
            }
            if (sessionTimeoutBlocks.size() == 0) {
                session.removeAttribute(Constants.SESSION_TIMEOUT_BLOCKS);
                User user = (User) session.getAttribute(Constants.USER);
                int minutes = CoreUtil.getUsersProfilePropertyIntOrDefault(session,
                        "webServer.sessionInactivityTimeout", user);
                if (log.isDebugEnabled())
                    log.debug("Initialising timeout for session " + session.getId() + " to " + minutes
                            + " minutes");
                session.setMaxInactiveInterval(minutes == 0 ? -1 : minutes * 60);
            }
        }
    } catch (IllegalStateException ise) {
        log.warn("Couldnt remove session timeout block.", ise);
    }
}

From source file:com.aurel.track.prop.LoginBL.java

private static StringBuilder assembleJSONPart2(StringBuilder sb, Locale locale, boolean firstTimeEver,
        TPersonBean personBean, HttpSession httpSession, String redirectURL, Integer mobileApplicationVersionNo,
        TMotdBean motd) {/* w w w .j  a v  a2s. co  m*/
    String licURL = "";
    if (ApplicationBean.getInstance().getLicenseManager() != null) {
        licURL = ApplicationBean.getInstance().getLicenseManager().getLicenseUrl(locale);
    }

    JSONUtility.appendStringValue(sb, "licURL", licURL, false);
    JSONUtility.appendBooleanValue(sb, "ftever", firstTimeEver, false);

    boolean isld = true;

    JSONUtility.appendBooleanValue(sb, "isLicenseDerfined", isld, false);

    JSONUtility.appendStringValue(sb, "jsonURL", redirectURL, false);
    if (httpSession.getAttribute(ISMOBILEAPP) != null) {
        if ((Boolean) httpSession.getAttribute(ISMOBILEAPP)) {
            // This property is added for mobile client,
            if (personBean != null && personBean.getLocale() != null) {
                JSONUtility.appendStringValue(sb, "locale", personBean.getLocale().toString());
                JSONUtility.appendStringValue(sb, "datePattern", getLocaleDatePattern(personBean.getLocale()));
                JSONUtility.appendIntegerValue(sb, "userLevel", personBean.getUserLevel());
                JSONUtility.appendIntegerValue(sb, "sessionTimeoutMinutes",
                        httpSession.getMaxInactiveInterval() / 60);
                JSONUtility.appendJSONValue(sb, "userSettingsProperties", getUserProperties(personBean));
                JSONUtility.appendIntegerValue(sb, "userObjectID", personBean.getObjectID());
                JSONUtility.appendStringValue(sb, "serverVersion", ApplicationBean.getInstance().getVersion());
                JSONUtility.appendIntegerValue(sb, "serverVersionNo",
                        ApplicationBean.getInstance().getVersionNo());
                JSONUtility.appendIntegerValue(sb, "clientCompatibility",
                        MobileBL.checkClientCompatibility(mobileApplicationVersionNo, true));
                JSONUtility.appendStringValue(sb, "sessionId", httpSession.getId());

                Integer iconKey = Integer.valueOf(-1);
                try {
                    byte[] oneAvatar = AvatarBL.getAvatarInByteArray(personBean.getObjectID(), iconKey);
                    MessageDigest md = MessageDigest.getInstance("MD5");
                    byte[] thedigest = md.digest(oneAvatar);
                    String checksum = DatatypeConverter.printBase64Binary(thedigest);
                    JSONUtility.appendStringValue(sb, "checkSum", checksum);
                } catch (Exception ex) {
                }
            }
        }
    }
    String motdMsg = motd.getTheMessage();
    if (motdMsg == null) {
        motdMsg = "&nbsp;";
    }
    try {
        JSONUtility.appendStringValue(sb, "teaserText",
                Html2Text.getNewInstance().convert(motd.getTeaserText()));
    } catch (Exception ex) {
    }
    JSONUtility.appendStringValue(sb, "motd", motdMsg, true);

    sb.append("}");
    sb.append("}");
    return sb;
}

From source file:org.kmnet.com.fw.web.token.transaction.HttpSessionTransactionTokenStore.java

/**
 * Creates a new Token key and reserve it in the HttpSession<br>
 * removes oldeset token if token size is greater than or equals {@link #transactionTokensPerTokenName} in the same
 * namespace./*w w w . j a  va 2s. c o m*/
 * @see org.kmnet.com.fw.web.token.transaction.TransactionTokenStore#createAndReserveTokenKey(java.lang.String)
 */
@Override
public String createAndReserveTokenKey(String tokenName) {
    String tokenNamePrefix = TOKEN_HOLDER_SESSION_ATTRIBUTE_PREFIX + tokenName;
    Set<String> sessionAttributeNames = new HashSet<String>();
    HttpSession session = getSession();
    Object mutex = getMutex(session);
    String tokenKey = null;
    synchronized (mutex) {
        Enumeration<String> tokenNameEnumeration = session.getAttributeNames();
        while (tokenNameEnumeration.hasMoreElements()) {
            String name = tokenNameEnumeration.nextElement();
            // fetch the sessionKeyPrefix (session key with only Token prefix and namespace name) and compare
            if (tokenNamePrefix.equals(name.split(TransactionToken.TOKEN_STRING_SEPARATOR)[0])) {
                sessionAttributeNames.add(name);
            }
        }

        for (int i = 0, max = sessionAttributeNames.size(); i < max; i++) {
            // do not use while loop to avoid infinite loop
            if (sessionAttributeNames.size() >= transactionTokensPerTokenName) {
                String oldestTokenName = null;
                TokenHolder oldestTokenHolder = new TokenHolder(null, Long.MAX_VALUE);
                for (String name : sessionAttributeNames) {
                    TokenHolder tokenHolder = (TokenHolder) session.getAttribute(name);
                    if (tokenHolder.getTimestamp() < oldestTokenHolder.getTimestamp()) {
                        oldestTokenName = name;
                        oldestTokenHolder = tokenHolder;
                    }
                }
                session.removeAttribute(oldestTokenName);
                sessionAttributeNames.remove(oldestTokenName);
            } else {
                break;
            }
        }

        for (int i = 0; i < retryCreateTokenName; i++) {
            String str = generator.generate(session.getId());
            String name = tokenNamePrefix + TransactionToken.TOKEN_STRING_SEPARATOR + str;
            if (!sessionAttributeNames.contains(name)) {
                tokenKey = str;
                break;
            }
        }
    }
    if (tokenKey == null) {
        throw new IllegalStateException(
                "token key generation failed within retry count " + retryCreateTokenName);
    }

    return tokenKey;
}

From source file:edu.harvard.i2b2.fhirserver.ws.OAuth2AuthzEndpoint.java

@Path("processScope")
@POST/*from  w w w  .j  av  a2s .c  o m*/
public Response processResourceOwnerScopeChoice(@FormParam("project") String i2b2Project,
        @Context HttpServletRequest request) {
    try {
        logger.trace("processing scope:" + i2b2Project + " sessionid:" + request.getSession().getId());
        // save scope to session and
        // redirect to client uri
        HttpSession session = request.getSession();
        session.setAttribute("permittedScopes", "user/*.*");

        String finalUri = (String) session.getAttribute("finalUri");

        String msg = "";
        Enumeration x = session.getAttributeNames();
        while (x.hasMoreElements()) {
            String p = (String) x.nextElement();
            msg = msg + p + "=" + session.getAttribute(p).toString() + "\n";
        }
        logger.trace("sessionAttributes:" + msg);
        // create AuthToken in Database;

        String pmResponseXml = (String) session.getAttribute("pmResponseXml");
        if (pmResponseXml == null)
            throw new RuntimeException("PMRESPONSE NOT FOUND");

        String resourceUserId = (String) session.getAttribute("resourceUserId");
        String i2b2Token = (String) I2b2Util.getToken(pmResponseXml);
        String authorizationCode = (String) session.getAttribute("authorizationCode");
        String clientRedirectUri = (String) session.getAttribute("redirectUri");
        String clientId = (String) session.getAttribute("clientId");
        String state = (String) session.getAttribute("state");
        String scope = "user/*.*";// HashSet<String>
        // session.getAttribute("scope");
        AuthToken authToken = authTokenBean.find(authorizationCode);
        if (authToken == null)
            authToken = authTokenBean.createAuthToken(authorizationCode, resourceUserId, i2b2Token,
                    clientRedirectUri, clientId, state, scope, i2b2Project);

        session.setAttribute("msg", "");
        return Response.status(Status.MOVED_PERMANENTLY).location(new URI(finalUri))
                .header("session_id", session.getId()).build();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        e.printStackTrace();
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.filterConfiguration.FilterConfigurationImportHandler.java

/**
 * Invokes this PageHandler//from  w w w  . ja v a 2  s  . c  om
 * 
 * @param pageDescriptor
 *            the page desciptor
 * @param request
 *            the original request sent from the browser
 * @param response
 *            the original response object
 * @param context
 *            context the Servlet context
 * @throws IOException
 * @throws ServletException
 * @throws EnvoyServletException
 */
public void invokePageHandler(WebPageDescriptor p_pageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws EnvoyServletException, ServletException, IOException {
    HttpSession session = p_request.getSession(false);
    String sessionId = session.getId();
    SessionManager sessionMgr = (SessionManager) session.getAttribute(WebAppConstants.SESSION_MANAGER);
    m_userId = (String) session.getAttribute(WebAppConstants.USER_NAME);
    String companyId = CompanyThreadLocal.getInstance().getValue();
    sessionMgr.setAttribute("companyId", companyId);
    String action = p_request.getParameter("action");
    if (action != null) {
        if ("startUpload".equals(action)) {
            File uploadedFile = this.uploadFile(p_request);
            session.setAttribute("uploading_filter", uploadedFile);
        } else if ("doImport".equals(action)) {
            int count = 0;
            if (sessionMgr.getAttribute("count") != null) {
                count = (Integer) sessionMgr.getAttribute("count");
                if (count == 1) {
                    count++;
                    sessionMgr.setAttribute("count", count);
                }
            } else {
                count++;
                sessionMgr.setAttribute("count", count);
            }
            if (session.getAttribute("uploading_filter") != null) {
                filter_percentage_map.clear();// .remove(sessionId);
                filter_error_map.clear();// .remove(sessionId);
                File uploadedFile = (File) session.getAttribute("uploading_filter");
                session.removeAttribute("uploading_filter");

                DoImport imp = new DoImport(sessionId, uploadedFile, companyId);
                imp.start();
            } else {
                logger.error("No uploaded user info file.");
            }
        } else if ("refreshProgress".equals(action)) {
            this.refreshProgress(p_request, p_response, sessionId);
            return;
        }
    }

    ResourceBundle bundle = PageHandler.getBundle(session);
    setLable(p_request, bundle);
    super.invokePageHandler(p_pageDescriptor, p_request, p_response, p_context);
}