Java Code Examples for javax.servlet.http.HttpSession#getServletContext()

The following examples show how to use javax.servlet.http.HttpSession#getServletContext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserServlet.java    From mytwitter with Apache License 2.0 6 votes vote down vote up
private void toExit(HttpServletRequest request, HttpServletResponse response) throws IOException {
	HttpSession session = request.getSession();
	if (session.getAttribute("admin") == null) {
		session.invalidate();
		response.sendRedirect("index.jsp");
		return;
	}
	Users user = (Users) session.getAttribute("user");
	ServletContext application = session.getServletContext();
	application.removeAttribute(((Users) session.getAttribute("user")).getUname());
	Integer onlineNum = (Integer) application.getAttribute("onlineNum");
	if (onlineNum > 0) {
		application.setAttribute("onlineNum", onlineNum - 1);
	}
	Object signinid = session.getAttribute("signinid");
	int uid = user.getUid();
	Timestamp sdtime = Times.getSystemTime();
	usersDao.updateOnline(0, uid);
	signinDao.updateSignin((Integer) signinid, sdtime);
	response.sendRedirect("index.jsp");
}
 
Example 2
Source File: AbstractCarbonUIAuthenticator.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param request
 * @return
 */
private String getBackendUrl(HttpServletRequest request) {

    HttpSession session = request.getSession();
    ServletContext servletContext = session.getServletContext();

    String backendServerURL = request.getParameter("backendURL");

    if (backendServerURL == null) {
        backendServerURL = CarbonUIUtil.getServerURL(servletContext, request.getSession());
    }

    if (backendServerURL != null) {
        session.setAttribute(CarbonConstants.SERVER_URL, backendServerURL);
    }

    return backendServerURL;
}
 
Example 3
Source File: AbstractCarbonUIAuthenticator.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param backendServerURL
 * @param session
 * @return
 * @throws AxisFault
 */
private LoggedUserInfoAdminStub getLoggedUserInfoAdminStub(String backendServerURL,
        HttpSession session) throws AxisFault {

    ServletContext servletContext = session.getServletContext();
    ConfigurationContext configContext = (ConfigurationContext) servletContext
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);

    if (configContext == null) {
        String msg = "Configuration context is null.";
        log.error(msg);
        throw new AxisFault(msg);
    }

    return new LoggedUserInfoAdminStub(configContext, backendServerURL + "LoggedUserInfoAdmin");
}
 
Example 4
Source File: DefaultCarbonAuthenticator.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param request
 * @return
 * @throws AxisFault
 */
private AuthenticationAdminClient getAuthenticationAdminCient(HttpServletRequest request)
        throws AxisFault {
    HttpSession session = request.getSession();
    ServletContext servletContext = session.getServletContext();
    String backendServerURL = request.getParameter("backendURL");
    if (backendServerURL == null) {
        backendServerURL = CarbonUIUtil.getServerURL(servletContext, request.getSession());
    }
    session.setAttribute(CarbonConstants.SERVER_URL, backendServerURL);

    ConfigurationContext configContext = (ConfigurationContext) servletContext
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);

    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_AUTH_TOKEN);

    return new AuthenticationAdminClient(configContext, backendServerURL, cookie, session, true);
}
 
Example 5
Source File: IWAUIAuthenticator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param request
 * @return
 * @throws AxisFault
 */
private IWAAuthenticatorStub getIWAClient(HttpServletRequest request)
        throws AxisFault, IdentityException {

    HttpSession session = request.getSession();
    ServletContext servletContext = session.getServletContext();
    String backendServerURL = request.getParameter("backendURL");
    if (backendServerURL == null) {
        backendServerURL = CarbonUIUtil.getServerURL(servletContext, request.getSession());
    }

    ConfigurationContext configContext = (ConfigurationContext) servletContext
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);

    String serviceEPR = backendServerURL + "IWAAuthenticator";
    IWAAuthenticatorStub stub = new IWAAuthenticatorStub(configContext, serviceEPR);
    ServiceClient client = stub._getServiceClient();
    client.engageModule("rampart");
    Policy rampartConfig = IdentityBaseUtil.getDefaultRampartConfig();
    Policy signOnly = IdentityBaseUtil.getSignOnlyPolicy();
    Policy mergedPolicy = signOnly.merge(rampartConfig);
    Options options = client.getOptions();
    options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, mergedPolicy);
    options.setManageSession(true);
    return stub;
}
 
Example 6
Source File: ChannelController.java    From PedestrianDetectionSystem with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "set_channel", method = RequestMethod.GET)
public @ResponseBody
ModelAndView setChannel(@RequestParam("use_channel")Integer channel, HttpSession session){
    ServletContext context = session.getServletContext();
    Map<String, Object> result = new HashMap();
    result.put("msg", "success");
    result.put("rst", 0);
    result.put("data", channel);
    context.setAttribute("use_channel", channel);
    return new ModelAndView(new MappingJackson2JsonView(), result);
}
 
Example 7
Source File: SessionListener.java    From PedestrianDetectionSystem with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionCreated(HttpSessionEvent se) {
    HttpSession session = se.getSession();
    ServletContext context = session.getServletContext();
    if (context.getAttribute("onlineCount") == null){
        context.setAttribute("onlineCount", 1);
    }else {
        context.setAttribute("onlineCount", (Integer)context.getAttribute("onlineCount") + 1);
    }

}
 
Example 8
Source File: SessionListener.java    From PedestrianDetectionSystem with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionDestroyed(HttpSessionEvent se) {
    HttpSession session = se.getSession();
    ServletContext context = session.getServletContext();
    Integer subFlag = (Integer)session.getAttribute("sub_flag");
    if(subFlag == null){
        context.setAttribute("onlineCount", (Integer)context.getAttribute("onlineCount") - 1);
    }
}
 
Example 9
Source File: WebChew.java    From ontopia with Apache License 2.0 5 votes vote down vote up
/**
 * INTERNAL: Returns the plug-in class instance used by the ontopoly
 * plugin. Used by classify/plugin.jsp.
 */
public static ClassifyPluginIF getPlugin(HttpServletRequest request) {
  // create plugin by dynamically intantiating plugin class
  HttpSession session = request.getSession(true);
  ServletContext scontext = session.getServletContext();
  String pclass = scontext.getInitParameter("classify_plugin");
  if (pclass == null)
    pclass = "net.ontopia.topicmaps.classify.DefaultPlugin";
  ClassifyPluginIF cp = (ClassifyPluginIF)ObjectUtils.newInstance(pclass);
  if (cp instanceof HttpServletRequestAwareIF)
    ((HttpServletRequestAwareIF)cp).setRequest(request);
  return cp;
}
 
Example 10
Source File: MultiSessionAttributeAdapter.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected MultiSessionAttributeAdapter(HttpSession preferredSession, HttpSession localSession, HttpServletRequest request) {
    this.preferredSession = preferredSession;
    this.localSession = localSession;

    ServletContext servletContext = request!=null ? request.getServletContext() :
            localSession!=null ? localSession.getServletContext() :
                    preferredSession!=null ? preferredSession.getServletContext() :
                            null;

    this.mgmt = servletContext != null ? new ManagementContextProvider(servletContext).getManagementContext() : null;
    resetExpiration();
}
 
Example 11
Source File: MultiSessionAttributeAdapter.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private HttpSession findPreferredSession(HttpSession localSession, HttpServletRequest optionalRequest) {
    HttpSession preferredSession = findValidPreferredSession(localSession, optionalRequest);

    //TODO just check this the first time preferred session is accessed on a given request (when it is looked up)

    ManagementContext mgmt = null;
    ServletContext servletContext = optionalRequest!=null ? optionalRequest.getServletContext() : localSession!=null ? localSession.getServletContext() : preferredSession!=null ? preferredSession.getServletContext() : null;
    if(servletContext != null){
        mgmt = new ManagementContextProvider(servletContext).getManagementContext();
    }

    boolean isValid = ((Session)preferredSession).isValid();
    if (!isValid) {
        throw new SessionExpiredException("Session invalidated", SessionErrors.SESSION_INVALIDATED, optionalRequest);
    }

    if(mgmt !=null){
        Long maxSessionAge = mgmt.getConfig().getConfig(MAX_SESSION_AGE);
        if (maxSessionAge!=null) {
            if (isAgeExceeded(preferredSession, maxSessionAge)) {
                invalidateAllSession(preferredSession, localSession);
                throw new SessionExpiredException("Max session age exceeded", SessionErrors.SESSION_AGE_EXCEEDED, optionalRequest);
            }
        }
    }

    return preferredSession;
}
 
Example 12
Source File: cfSessionData.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Invoke onSessionEnd() for any cfSessionData instance within the
 * HttpSession.
 */
public static void onSessionEnd(HttpSession httpSession) {
	ServletContext servletContext = httpSession.getServletContext();
	boolean containsSessionId = false;
	boolean containsUrlToken = false;

	Enumeration<String> attrNames = httpSession.getAttributeNames();
	while (attrNames.hasMoreElements()) {
		String key = attrNames.nextElement();
		if (key.equals("sessionid")) {
			containsSessionId = true;
		} else if (key.equals("urltoken")) {
			containsUrlToken = true;
		} else {
			Object sessionAttr = httpSession.getAttribute(key);
			if (sessionAttr instanceof cfSessionData) {
				Object appAttr = servletContext.getAttribute(key);
				if (appAttr instanceof cfApplicationData) {
					((cfSessionData) sessionAttr).onSessionEnd((cfApplicationData) appAttr);
				}
			}
		}
	}

	// check for unnamed cfJ2EESessionData
	if (containsSessionId && containsUrlToken) {
		cfSessionData session = new cfJ2EESessionData(httpSession);
		session.onSessionEnd(new cfJ2EEApplicationData(servletContext));
	}
}
 
Example 13
Source File: HttpFlexSession.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
/**
 * Map of HttpSession Ids to FlexSessions. We need this when registered as a listener
 * in web.xml in order to trigger the destruction of a FlexSession when its associated HttpSession
 * is invalidated/destroyed. The Servlet spec prior to version 2.4 defined the session destruction event
 * to be dispatched after attributes are unbound from the session so when we receive notification that
 * an HttpSession is destroyed there's no way to get to the associated FlexSession attribute because it
 * has already been unbound... Additionally, we need it to handle attribute removal events that happen
 * during HttpSession destruction because the FlexSession can be unbound from the session before the
 * other attributes we receive notification for.
 *
 * Because of this, it's simplest to just maintain this lookup table and use it for all HttpSession
 * related event handling.
 *
 * The table is maintained on the servlet context instead of statically in order to prevent collisions
 * across web-apps.
 */
private Map getHttpSessionToFlexSessionMap(HttpSession session)
{
    try
    {
        ServletContext context = session.getServletContext();
        Map map = (Map)context.getAttribute(SESSION_MAP);

        if(map==null){
            // map should never be null here as it is created during MessageBrokerServlet start-up
            if (Log.isError())
                Log.getLogger(FLEX_SESSION_LOG_CATEGORY).error("HttpSession to FlexSession map not created in message broker for "
                        + session.getId());
            MessageException me = new MessageException();
            me.setMessage(10032, new Object[] {session.getId()});
            throw me;
        }
        return map;
    }
    catch(Exception e)
    {
        if (Log.isDebug())
            Log.getLogger(FLEX_SESSION_LOG_CATEGORY).debug("Unable to get HttpSession to FlexSession map for "
                    + session.getId() + " " + e.toString());
        return new ConcurrentHashMap();
    }
}
 
Example 14
Source File: OIDCUIAuthenticator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public void unauthenticate(Object o) throws Exception {

    HttpServletRequest request = (HttpServletRequest) o;
    HttpSession session = request.getSession();
    String username = (String) session.getAttribute(CarbonConstants.LOGGED_USER);
    ServletContext servletContext = session.getServletContext();
    ConfigurationContext configContext = (ConfigurationContext) servletContext
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);

    String backendServerURL = CarbonUIUtil.getServerURL(servletContext, session);
    try {
        String cookie = (String) session.getAttribute(ServerConstants.
                ADMIN_SERVICE_AUTH_TOKEN);

        OIDCAuthenticationClient authClient = new
                OIDCAuthenticationClient(configContext, backendServerURL, cookie, session);

        authClient.logout(session);
        log.info(username + "@" + PrivilegedCarbonContext.getThreadLocalCarbonContext().
                getTenantDomain() +" successfully logged out");

    } catch (Exception ignored) {
        String msg = "OIDC logout failed";
        log.error(msg, ignored);
        throw new Exception(msg, ignored);
    }

    String logoutUrl = Util.getIdentityProviderURI() + "logout";

    request.setAttribute(OIDCConstants.HTTP_ATTR_IS_LOGOUT_REQ, true);
    request.setAttribute(OIDCConstants.EXTERNAL_LOGOUT_PAGE, logoutUrl);
}
 
Example 15
Source File: AttachmentSessionListener.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {

	HttpSession httpSession = httpSessionEvent.getSession();
	ServletContext servletContext = httpSession.getServletContext();
	File tempDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR);

	File attachmentDir = new File(tempDir, httpSession.getId());

	if (attachmentDir.exists()) {

		File[] files = attachmentDir.listFiles();

		for (File file : files) {

			file.delete();

			logger.debug("Deleted file: " + file.getAbsolutePath());
		}
	}
}
 
Example 16
Source File: LoginServiceImpl.java    From admin-plus with Apache License 2.0 4 votes vote down vote up
@Override
public Result login(LoginDTO dto, HttpSession session) throws Exception {
    String psw =dto.getPassword();
    String userName = dto.getUsername();
    if(Tools.isEmpty(userName) || Tools.isEmpty(psw)){
        throw new ApiException(ApiResultEnum.PARAMETER_NULL);
    }
    psw = SHA.encryptSHA(psw);
    QueryWrapper<User> queryWrapper = new QueryWrapper();
    queryWrapper.lambda().eq(User::getUsername,dto.getUsername()).eq(User::getPassword,psw);
    User user = userService.getOne(queryWrapper);
    if(user == null){
        throw  new ApiException(ApiResultEnum.ACCOUNT_NOT_FOUND);
    }
    if("lock".equalsIgnoreCase(user.getStatus())){
        throw new ApiException(ApiResultEnum.ACCOUNT_LOCK);
    }
    //获取用户权限
    Long userId = user.getUserId();
    List<Role> roles =userRoleService.getUserRoles(userId);
    long maxMenuId = menuService.getMaxId();
    Role uRole = new Role(new BigInteger("0"),new BigInteger("0"),new BigInteger("0"),new BigInteger("0"),new BigInteger("0"));
    checkUserRole(roles, uRole, maxMenuId);
    System.out.println("==ROLE=="+JSON.toJSONString(uRole));
    user.setRole(uRole);
    //父级菜单
    List<Menu> parentMenuList = menuService.getAllMenuList();
    checkMenuRole(parentMenuList, uRole.getRights(),user.getUsername());
    ServletContext servletContext = session.getServletContext();
    Map<String,User> globalUser = (Map<String, User>) servletContext.getAttribute(Const.GLOBAL_SESSION);
    if(globalUser == null){
        globalUser = new HashMap<String, User>();
    }else{
        if(globalUser.containsKey(userName)){
            globalUser.remove(userName);
        }
    }
    user.setSessionId(session.getId());
    user.setPassword("*****");
    globalUser.put(userName, user);
    session.setMaxInactiveInterval(0);
    session.setAttribute(Const.SESSION_ALL_MENU, parentMenuList);
    session.setAttribute(Const.SESSION_USER, user);
    servletContext.setAttribute(Const.GLOBAL_SESSION, globalUser);
    User updateUser = new User();
    updateUser.setSessionId(session.getId());
    updateUser.setUserId(userId);
    userService.updateById(updateUser);
    //保存登录日志
    Login loginLog = new Login();
    loginLog.setLastLoginTime(LocalDateTime.now());
    loginLog.setUserId(userId);
    this.save(loginLog);
    return Result.ok();
}
 
Example 17
Source File: AttachmentSessionListener.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {

	HttpSession httpSession = httpSessionEvent.getSession();
	ServletContext servletContext = httpSession.getServletContext();
	File tempDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR);

	File attachmentDir = new File(tempDir, httpSession.getId());

	if (attachmentDir.exists()) {

		File[] files = attachmentDir.listFiles();

		for (File file : files) {

			file.delete();

			logger.debug("Deleted file: " + file.getAbsolutePath());
		}
	}
}
 
Example 18
Source File: OrderEvents.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static String downloadDigitalProduct(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    ServletContext application = session.getServletContext();
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    String dataResourceId = request.getParameter("dataResourceId");

    try {
        // has the userLogin.partyId ordered a product with DIGITAL_DOWNLOAD content associated for the given dataResourceId?
        GenericValue orderRoleAndProductContentInfo = EntityQuery.use(delegator).from("OrderRoleAndProductContentInfo")
                .where("partyId", userLogin.get("partyId"),
                        "dataResourceId", dataResourceId,
                        "productContentTypeId", "DIGITAL_DOWNLOAD",
                        "statusId", "ITEM_COMPLETED")
                .queryFirst();

        if (orderRoleAndProductContentInfo == null) {
            request.setAttribute("_ERROR_MESSAGE_", "No record of purchase for digital download found (dataResourceId=[" + dataResourceId + "]).");
            return "error";
        }


        // TODO: check validity based on ProductContent fields: useCountLimit, useTime/useTimeUomId

        if (orderRoleAndProductContentInfo.getString("mimeTypeId") != null) {
            response.setContentType(orderRoleAndProductContentInfo.getString("mimeTypeId"));
        }
        OutputStream os = response.getOutputStream();
        GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne();
        Map<String, Object> resourceData = DataResourceWorker.getDataResourceStream(dataResource, "", application.getInitParameter("webSiteId"), UtilHttp.getLocale(request), application.getRealPath("/"), false);
        os.write(IOUtils.toByteArray((InputStream) resourceData.get("stream")));
        os.flush();
    } catch (GeneralException | IOException e) {
        String errMsg = "Error downloading digital product content: " + e.toString();
        Debug.logError(e, errMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }

    return "success";
}
 
Example 19
Source File: UserServlet.java    From mytwitter with Apache License 2.0 4 votes vote down vote up
private void signUp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	HttpSession session = request.getSession();

	String name = (String) session.getAttribute("name");
	String uname = (String) session.getAttribute("uname");
	String pwd = (String) session.getAttribute("pwd");
	String aite = request.getParameter("aite");
	Timestamp utime = Times.getSystemTime();

	int n = usersDao.addUser(uname, pwd, name, aite, utime);
	if (n > 0) {
		ServletContext application = session.getServletContext();
		Integer zhuceNum = (Integer) application.getAttribute("zhuceNum");
		if (zhuceNum == null) {
			zhuceNum = 1;
		} else {
			zhuceNum += 1;
		}
		application.setAttribute("newTweetNum", zhuceNum);
		Users user = usersDao.checkLogin(uname, pwd);

		int m = usersinfoDao.addUserinfo(user.getUid());
		if (m > 0) {
			Usersinfo info = usersinfoDao.getInfos(user.getUid());

			String folder = request.getSession().getServletContext().getRealPath("/img/" + user.getUname());
			String img = request.getSession().getServletContext().getRealPath("/img");
			File file = new File(folder);
			file.mkdir();

			InputStream is = new FileInputStream(img + "/" + info.getUlogo());
			OutputStream os = new FileOutputStream(folder + "/" + info.getUlogo(), true);
			byte[] b = new byte[1024];
			int a = is.read(b); // 实际读到的文件的长度

			while (a > 0) {
				os.write(b, 0, a);
				a = is.read(b);
			}

			os.close();
			is.close();

			session.setAttribute("info", info);
			session.setAttribute("user", user);
			response.sendRedirect("start.jsp");
		}
	}

}
 
Example 20
Source File: VaadinUtils.java    From jdal with Apache License 2.0 4 votes vote down vote up
public static ServletContext getServletContext() {
	HttpSession session = getSession();
	
	return session != null ? session.getServletContext() : null;
}