Java Code Examples for javax.servlet.http.HttpSession

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/session/.

Source file: CycleHttpSession.java

  34 
vote

public static void openSession(ActivitiRequest req){
  HttpSession httpSession=req.getHttpServletRequest().getSession(true);
  String cuid=req.getCurrentUserId();
  CycleComponentFactory.registerServletContext(httpSession.getServletContext());
  CycleSessionContext.setContext(new HttpSessionContext(httpSession));
  CycleSessionContext.set("cuid",cuid);
  CycleRequestContext.setContext(new CycleMapContext());
  for (  CycleRequestFilter requestFilter : requestFilters) {
    requestFilter.doFilter(req);
  }
}
 

Example 2

From project core_5, under directory /exo.core.component.security.core/src/main/java/org/exoplatform/services/security/web/.

Source file: ConversationStateListener.java

  33 
vote

/** 
 * Remove  {@link ConversationState}.  {@inheritDoc}
 */
public void sessionDestroyed(HttpSessionEvent event){
  HttpSession httpSession=event.getSession();
  StateKey stateKey=new HttpSessionStateKey(httpSession);
  ExoContainer container=getContainerIfPresent(httpSession.getServletContext());
  if (container != null) {
    ConversationRegistry conversationRegistry=(ConversationRegistry)container.getComponentInstanceOfType(ConversationRegistry.class);
    ConversationState conversationState=conversationRegistry.unregister(stateKey);
    if (conversationState != null)     if (LOG.isDebugEnabled())     LOG.debug("Remove conversation state " + httpSession.getId());
  }
}
 

Example 3

From project ajah, under directory /ajah-servlet/src/main/java/com/ajah/servlet/util/.

Source file: SessionUtils.java

  32 
vote

/** 
 * A more explicit heavy-duty version of  {@link HttpSession#invalidate()}. This method will remove all attributes and clear all cookies, in addition to calling  {@link HttpSession#invalidate()}.
 * @param request Request to get cookies and session from, required.
 * @param response Response to set updated cookies on. Not required, but cookies cannot be cleared if null.
 */
public static void eradicate(final HttpServletRequest request,final HttpServletResponse response){
  AjahUtils.requireParam(request,"request");
  AjahUtils.requireParam(response,"response");
  final HttpSession session=request.getSession(false);
  if (session != null) {
    clearSessionAttributes(session);
    session.invalidate();
  }
  CookieUtils.clearAllCookies(request,response);
}
 

Example 4

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/tutorial/.

Source file: TutorialPanel.java

  32 
vote

@Override public void attach(){
  WebApplicationContext webappcontext=(WebApplicationContext)getApplication().getContext();
  HttpSession session=webappcontext.getHttpSession();
  String contextPath=session.getServletContext().getContextPath();
  embedded.setType(Embedded.TYPE_BROWSER);
  embedded.setSource(new ExternalResource(contextPath + "/tutorial/index.html"));
  super.attach();
}
 

Example 5

From project annotare2, under directory /app/web/src/test/java/uk/ac/ebi/fg/annotare2/web/server/login/.

Source file: AuthenticationServiceImplTest.java

  32 
vote

private HttpServletRequest mockRequest(String name,String password){
  HttpSession session=createMock(HttpSession.class);
  session.setAttribute(isA(String.class),isA(Object.class));
  expectLastCall();
  HttpServletRequest request=createMock(HttpServletRequest.class);
  expect(request.getParameterValues(AuthServiceImpl.LoginParams.EMAIL_PARAM)).andReturn(name == null ? null : new String[]{name}).anyTimes();
  expect(request.getParameterValues(AuthServiceImpl.LoginParams.PASSWORD_PARAM)).andReturn(password == null ? null : new String[]{password}).anyTimes();
  expect(request.getSession()).andReturn(session).anyTimes();
  replay(request,session);
  return request;
}
 

Example 6

From project arquillian_deprecated, under directory /frameworks/jsfunit/src/main/java/org/jboss/arquillian/framework/jsfunit/.

Source file: JSFUnitCleanupTestTreadFilter.java

  32 
vote

private void cleanUp(HttpServletRequest httpServletRequest){
  if (!isCallTestService(httpServletRequest))   return;
  if (SeamUtil.isSeamInitialized()) {
    SeamUtil.invalidateSeamSession(httpServletRequest);
  }
  HttpSession session=httpServletRequest.getSession(false);
  if (session != null) {
    session.invalidate();
  }
}
 

Example 7

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/util/.

Source file: Locales.java

  32 
vote

/** 
 * Sets the specified locale into session of the specified request. <p> If no session of the specified request, do nothing. </p>
 * @param request the specified request
 * @param locale a new locale
 */
public static void setLocale(final HttpServletRequest request,final Locale locale){
  final HttpSession session=request.getSession(false);
  if (null == session) {
    LOGGER.warning("Ignores set locale caused by no session");
    return;
  }
  session.setAttribute(Keys.LOCALE,locale);
  LOGGER.log(Level.FINER,"Client[sessionId={0}] sets locale to [{1}]",new Object[]{session.getId(),locale.toString()});
}
 

Example 8

From project Carolina-Digital-Repository, under directory /access/src/main/java/edu/unc/lib/dl/ui/controller/.

Source file: CDRBaseController.java

  32 
vote

protected AccessGroupSet getUserAccessGroups(HttpServletRequest request){
  HttpSession session=request.getSession();
  UserSecurityProfile user=(UserSecurityProfile)session.getAttribute("user");
  if (user == null) {
    return new AccessGroupSet(AccessGroupConstants.PUBLIC_GROUP);
  }
  return user.getAccessGroups();
}
 

Example 9

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/web/flow/.

Source file: TerminateWebSessionListener.java

  32 
vote

@Override public void sessionEnded(final RequestContext context,final FlowSession session,final String outcome,final AttributeMap output){
  final HttpServletRequest request=WebUtils.getHttpServletRequest(context);
  final HttpSession webSession=request.getSession(false);
  if (webSession != null && webSession.getAttribute(DO_NOT_TERMINATE) == null) {
    logger.debug("Terminate web session {} in {} seconds",webSession.getId(),this.timeToDieInSeconds);
    webSession.setMaxInactiveInterval(this.timeToDieInSeconds);
  }
}
 

Example 10

From project caseconductor-platform, under directory /utest-services-impl/src/main/java/com/utest/service/security/.

Source file: HttpSessionDestroyedListener.java

  32 
vote

@Override public void onApplicationEvent(final HttpSessionDestroyedEvent event){
  try {
    final Authentication auth=SecurityContextHolder.getContext().getAuthentication();
    final HttpSession session=(event).getSession();
    if ((auth != null) && (auth.getPrincipal() instanceof AuthenticatedUserInfo)) {
      userService.logout((AuthenticatedUserInfo)auth.getPrincipal(),session.getId());
    }
  }
 catch (  final Exception e) {
    logger.fatal("Failed to log user logout: " + e.toString());
  }
}
 

Example 11

From project cipango, under directory /cipango-console/src/main/java/org/cipango/console/.

Source file: VelocityConsoleServlet.java

  32 
vote

@Override protected void fillContext(Context context,HttpServletRequest request){
  super.fillContext(context,request);
  JmxConnection connection=getConnection(request);
  HttpSession session=request.getSession();
  session.setAttribute(StatisticGraph.class.getName(),_statisticGraphs.get(connection.getId()));
  if (connection.getContextMap() == null)   connection.setContextMap(newJmxMap(connection));
  for (  Map.Entry<String,Object> entry : connection.getContextMap().entrySet())   context.put(entry.getKey(),entry.getValue());
}
 

Example 12

From project cometd, under directory /cometd-java/cometd-java-server/src/main/java/org/cometd/server/transport/.

Source file: HttpTransport.java

  32 
vote

private ServletContext getServletContext(){
  HttpSession s=_request.getSession(false);
  if (s != null) {
    return s.getServletContext();
  }
 else {
    s=_request.getSession(true);
    ServletContext servletContext=s.getServletContext();
    s.invalidate();
    return servletContext;
  }
}
 

Example 13

From project cotopaxi-core, under directory /src/main/java/br/octahedron/cotopaxi/controller/.

Source file: Controller.java

  32 
vote

/** 
 * Stores an object in the session. If already exists an object stored with the given key, it will be overwritten, if the value is <code>null</code>, the object will be removed.
 * @param key the object's key
 * @param value the object
 */
protected final void session(String key,Object value){
  if (value != null) {
    this.request().getSession(true).setAttribute(key,value);
  }
 else {
    HttpSession session=this.request().getSession(false);
    if (session != null) {
      session.removeAttribute(key);
    }
  }
}
 

Example 14

From project echo2, under directory /src/webrender/java/nextapp/echo2/webrender/.

Source file: Connection.java

  32 
vote

/** 
 * Disposes of the <code>UserInstance</code> associated with this  <code>Connection</code>.
 */
void disposeUserInstance(){
  HttpSession session=request.getSession(false);
  if (session != null) {
    getUserInstance().setServletUri(null);
    session.removeAttribute(getSessionKey());
  }
}
 

Example 15

From project echo3, under directory /src/server-java/webcontainer/nextapp/echo/webcontainer/.

Source file: Connection.java

  32 
vote

/** 
 * Initializes the state of the new <code>UserInstanceContainer</code> and associates it with this <code>Connection</code> and the underlying <code>HttpSession</code>
 * @param userInstanceContainer the <code>UserInstanceContaienr</code>
 */
void initUserInstanceContainer(UserInstanceContainer userInstanceContainer){
  this.userInstanceContainer=userInstanceContainer;
  userInstanceContainer.setServletUri(request.getRequestURI());
  HttpSession session=request.getSession(true);
  session.setAttribute(getUserInstanceContainerSessionKey(),userInstanceContainer);
}
 

Example 16

From project elw, under directory /web/src/main/java/elw/miniweb/.

Source file: Message.java

  32 
vote

private static List<Message> getOrCreateMessages(HttpServletRequest req){
  final HttpSession session=req.getSession(true);
  @SuppressWarnings("unchecked") List<Message> messages=(List<Message>)session.getAttribute("elw_messages");
  if (messages == null) {
    messages=new ArrayList<Message>();
    session.setAttribute("elw_messages",messages);
  }
  return messages;
}
 

Example 17

From project entando-core-engine, under directory /src/main/java/com/agiletec/apsadmin/system/.

Source file: InterceptorMadMax.java

  32 
vote

protected String invoke(ActionInvocation invocation) throws Exception {
  Logger log=ApsSystemUtils.getLogger();
  if (log.isLoggable(Level.INFO)) {
    HttpSession session=ServletActionContext.getRequest().getSession();
    UserDetails currentUser=(UserDetails)session.getAttribute(SystemConstants.SESSIONPARAM_CURRENT_USER);
    String message="Action invoked '" + invocation.getProxy().getActionName() + "' on namespace '"+ invocation.getProxy().getNamespace()+ "' from user '"+ currentUser.getUsername()+ "'";
    log.info(message);
  }
  return super.invoke(invocation);
}
 

Example 18

From project Extlet6, under directory /liferay-6.0.5-patch/portal-impl/src/com/liferay/portal/servlet/.

Source file: MainServlet.java

  32 
vote

protected void checkPortletSessionTracker(HttpServletRequest request){
  HttpSession session=request.getSession();
  if (session.getAttribute(WebKeys.PORTLET_SESSION_TRACKER) != null) {
    return;
  }
  session.setAttribute(WebKeys.PORTLET_SESSION_TRACKER,PortletSessionTracker.getInstance());
}
 

Example 19

From project faces, under directory /Proyectos/upcdew-deportivoapp/src/java/com/upc/deportivo/controller/.

Source file: MantenimientoJugadorPartidoBean.java

  32 
vote

public MantenimientoJugadorPartidoBean(){
  jugadoresPartido=new ArrayList<JugadorPartidoBean>();
  HttpSession session=FacesUtils.getHttpSession(false);
  partidoBean=(PartidoBean)session.getAttribute("partido");
  session.removeAttribute("partido");
  if (partidoBean != null) {
    mostrarInformacionPartido(partidoBean);
  }
}
 

Example 20

From project flip, under directory /servlet/src/main/java/com/tacitknowledge/flip/servlet/.

Source file: FlipOverrideFilter.java

  32 
vote

/** 
 * The method which uses the request parameters and apply them into the session attribute  {@link #SESSION_FEATURES_KEY}. This session attribute holds the map  {@link FeatureDescriptorsMap}. The method do not creates the session. So if the session do not exists then the request parameters will be ignored. If in the session under key  {@link #SESSION_FEATURES_KEY} persists the object other than of type  {@link FeatureDescriptorsMap} or there isno object in the session then the new object will be created and stored there. 
 * @param request the request to process 
 */
private void applyFeaturesFromRequestParameters(final ServletRequest request){
  final HttpServletRequest httpRequest=(HttpServletRequest)request;
  final HttpSession session=httpRequest.getSession(false);
  FeatureDescriptorsMap featureDescriptors;
  if (session != null) {
    featureDescriptors=getSafeSessionFeatures(session);
    session.setAttribute(SESSION_FEATURES_KEY,featureDescriptors);
  }
 else {
    featureDescriptors=new FeatureDescriptorsMap();
  }
  applyRequestFeaturesToFeatureDescriptorsMap(request,featureDescriptors);
  FlipWebContext.setFeatureDescriptors(featureDescriptors);
}
 

Example 21

From project FormDesigner, under directory /OpenRosa/src/org/openrosa/server/.

Source file: FileSaveServlet.java

  32 
vote

@Override protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  HttpSession session=request.getSession();
  response.setHeader("Content-Disposition","attachment; filename=\"" + session.getAttribute(KEY_FILE_NAME));
  response.setContentType("text/xml; charset=utf-8");
  response.setHeader("Cache-Control","no-cache");
  response.setHeader("Pragma","no-cache");
  response.setDateHeader("Expires",-1);
  response.setHeader("Cache-Control","no-store");
  response.getOutputStream().print((String)session.getAttribute(KEY_FILE_CONTENTS));
}
 

Example 22

From project gatein-sso, under directory /agent/src/main/java/org/gatein/sso/agent/login/.

Source file: SPNEGORolesModule.java

  32 
vote

private String findSessionId() throws PolicyContextException {
  HttpServletRequest request=(HttpServletRequest)PolicyContext.getContext("javax.servlet.http.HttpServletRequest");
  if (request == null) {
    return null;
  }
  HttpSession session=request.getSession(false);
  String sessionId=session.getId();
  return sessionId;
}
 

Example 23

From project gatein-wci_1, under directory /glassfish/glassfish3/src/main/java/org/gatein/wci/glassfish/.

Source file: GF3ServletContainerContext.java

  32 
vote

public void logout(HttpServletRequest request,HttpServletResponse response) throws ServletException {
  HttpSession sess=request.getSession(false);
  if (sess == null)   return;
  sess.invalidate();
  if (!crossContextLogout)   return;
  final String sessId=sess.getId();
  DefaultServletContainerFactory.getInstance().getServletContainer().visit(new ServletContainerVisitor(){
    public void accept(    WebApp webApp){
      webApp.invalidateSession(sessId);
    }
  }
);
}
 

Example 24

From project hazelcast-cluster-monitor, under directory /src/main/java/com/hazelcast/monitor/server/.

Source file: HazelcastServiceImpl.java

  32 
vote

protected SessionObject getSessionObject(){
  HttpServletRequest request=this.getThreadLocalRequest();
  HttpSession session=request.getSession();
  SessionObject sessionObject=getSessionObject(session);
  return sessionObject;
}
 

Example 25

From project hdiv, under directory /hdiv-core/src/main/java/org/hdiv/session/.

Source file: SessionHDIV.java

  32 
vote

/** 
 * Obtains from the user session the page identifier where the current request or form is
 * @return Returns the pageId.
 */
public String getPageId(){
  HttpSession session=this.getHttpSession();
  String id=null;
  PageIdGenerator pageIdGenerator=(PageIdGenerator)session.getAttribute(this.pageIdGeneratorName);
  if (pageIdGenerator == null) {
    throw new HDIVException("session.nopageidgenerator");
  }
  id=pageIdGenerator.getNextPageId();
  session.setAttribute(this.pageIdGeneratorName,pageIdGenerator);
  return id;
}
 

Example 26

From project IOCipherServer, under directory /src/Acme/Serve/.

Source file: Serve.java

  32 
vote

HttpSession createSession(){
  Integer ms=(Integer)this.arguments.get(ARG_MAX_ACTIVE_SESSIONS);
  if (ms != null && ms.intValue() < sessions.size())   return null;
  HttpSession result=new AcmeSession(generateSessionId(),Math.abs(expiredIn) * 60,this,sessions);
synchronized (sessions) {
    sessions.put(result.getId(),result);
  }
  return result;
}
 

Example 27

From project iserve, under directory /iserve-parent/iserve-sal-gwt/src/main/java/uk/ac/open/kmi/iserve/sal/gwt/server/.

Source file: ServiceBrowseServiceImpl.java

  32 
vote

public boolean logout(String userId){
  HttpSession httpSession=getThreadLocalRequest().getSession(false);
  if (null != httpSession) {
    httpSession.removeAttribute("logged-in");
  }
  return true;
}
 

Example 28

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/servlets/.

Source file: ReportDownloader.java

  31 
vote

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException {
  HttpSession session=request.getSession();
  SessionDataInfo sessionData=(SessionDataInfo)session.getAttribute("com.gtwm.pb.servlets.sessionData");
  if (sessionData == null) {
    throw new ServletException("No session found");
  }
  BaseReportInfo report=sessionData.getReport();
  String templateName=request.getParameter("template");
  if (templateName != null) {
    this.serveTemplate(request,response,report,templateName);
  }
 else {
    this.serveSpreadsheet(request,response,sessionData,report);
  }
}
 

Example 29

From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/main/java/alpha/portal/webapp/filter/.

Source file: LocaleFilter.java

  31 
vote

/** 
 * This method looks for a "locale" request parameter. If it finds one, it sets it as the preferred locale and also configures it to work with JSTL.
 * @param request the current request
 * @param response the current response
 * @param chain the chain
 * @throws IOException when something goes wrong
 * @throws ServletException when a communication failure happens
 */
@Override @SuppressWarnings("unchecked") public void doFilterInternal(HttpServletRequest request,final HttpServletResponse response,final FilterChain chain) throws IOException, ServletException {
  final String locale=request.getParameter("locale");
  Locale preferredLocale=null;
  if (locale != null) {
    final int indexOfUnderscore=locale.indexOf('_');
    if (indexOfUnderscore != -1) {
      final String language=locale.substring(0,indexOfUnderscore);
      final String country=locale.substring(indexOfUnderscore + 1);
      preferredLocale=new Locale(language,country);
    }
 else {
      preferredLocale=new Locale(locale);
    }
  }
  final HttpSession session=request.getSession(false);
  if (session != null) {
    if (preferredLocale == null) {
      preferredLocale=(Locale)session.getAttribute(Constants.PREFERRED_LOCALE_KEY);
    }
 else {
      session.setAttribute(Constants.PREFERRED_LOCALE_KEY,preferredLocale);
      Config.set(session,Config.FMT_LOCALE,preferredLocale);
    }
    if ((preferredLocale != null) && !(request instanceof LocaleRequestWrapper)) {
      request=new LocaleRequestWrapper(request,preferredLocale);
      LocaleContextHolder.setLocale(preferredLocale);
    }
  }
  final String theme=request.getParameter("theme");
  if ((theme != null) && request.isUserInRole(Constants.ADMIN_ROLE)) {
    final Map<String,Object> config=(Map)this.getServletContext().getAttribute(Constants.CONFIG);
    config.put(Constants.CSS_THEME,theme);
  }
  chain.doFilter(request,response);
  LocaleContextHolder.setLocaleContext(null);
}
 

Example 30

From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/processor/.

Source file: ArticleProcessor.java

  31 
vote

/** 
 * Processes the article view password form submits.
 * @param context the specified context
 * @param request the specified HTTP servlet request
 * @param response the specified HTTP servlet response
 * @throws Exception exception 
 */
@RequestProcessing(value="/console/article-pwd",method=HTTPRequestMethod.POST) public void onArticlePwdForm(final HTTPRequestContext context,final HttpServletRequest request,final HttpServletResponse response) throws Exception {
  try {
    final String articleId=request.getParameter("articleId");
    final String pwdTyped=request.getParameter("pwdTyped");
    final JSONObject article=articleQueryService.getArticleById(articleId);
    if (article.getString(Article.ARTICLE_VIEW_PWD).equals(pwdTyped)) {
      final HttpSession session=request.getSession(false);
      if (null != session) {
        @SuppressWarnings("unchecked") Map<String,String> viewPwds=(Map<String,String>)session.getAttribute(Common.ARTICLES_VIEW_PWD);
        if (null == viewPwds) {
          viewPwds=new HashMap<String,String>();
        }
        viewPwds.put(articleId,pwdTyped);
        session.setAttribute(Common.ARTICLES_VIEW_PWD,viewPwds);
      }
      response.sendRedirect(Latkes.getServePath() + article.getString(Article.ARTICLE_PERMALINK));
      return;
    }
    response.sendRedirect(Latkes.getServePath() + "/console/article-pwd" + articleUtils.buildArticleViewPwdFormParameters(article)+ '&'+ Keys.MSG+ '='+ URLEncoder.encode(langPropsService.get("passwordNotMatchLabel"),"UTF-8"));
  }
 catch (  final Exception e) {
    LOGGER.log(Level.SEVERE,"Processes article view password form submits failed",e);
    try {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
 catch (    final IOException ex) {
      LOGGER.severe(ex.getMessage());
    }
  }
}
 

Example 31

From project Blitz, under directory /src/com/laxser/blitz/web/portal/impl/.

Source file: WindowRequest.java

  31 
vote

@Override public HttpSession getSession(boolean create){
  HttpSession session=super.getSession(false);
  if (session != null) {
    return session;
  }
  if (create) {
    if (window.getContainer().getInvocation().getResponse().isCommitted()) {
      session=new SessionAfterCommitted(new IllegalStateException("Cannot create a session after the response has been committed"));
    }
 else {
      try {
        session=super.getSession(true);
      }
 catch (      IllegalStateException e) {
        session=new SessionAfterCommitted(e);
      }
    }
  }
  return session;
}
 

Example 32

From project CalendarPortlet, under directory /contrib/blackboard-vista/.

Source file: BlackboardVistaICalAdapter.java

  31 
vote

public Set<CalendarEvent> getEvents(CalendarConfiguration calendar,Period period,HttpServletRequest request) throws CalendarException {
  HttpSession session=request.getSession(false);
  if (session == null) {
    log.error("BlackboardVistaICalAdapter requested with a null session");
    throw new CalendarException();
  }
  String username=(String)session.getAttribute("subscribeId");
  if (username == null) {
    log.error("BlackboardVistaICalAdapter cannot find the subscribeId");
    throw new CalendarException();
  }
  String password=(String)session.getAttribute("password");
  if (password == null) {
    log.error("BlackboardVistaICalAdapter cannot find the users password, try configuring the CachedCredentialsInitializationService");
    throw new CalendarException();
  }
  return getEvents(calendar,period,username,password);
}
 

Example 33

From project citrus-sample, under directory /petstore/web/src/main/java/com/alibaba/sample/petstore/web/common/.

Source file: PetstoreUserAuth.java

  31 
vote

public Status onStart(TurbineRunData rundata){
  HttpSession session=rundata.getRequest().getSession();
  PetstoreUser user=null;
  try {
    user=(PetstoreUser)session.getAttribute(sessionKey);
  }
 catch (  Exception e) {
    log.warn("Failed to read PetstoreUser from session: " + sessionKey,e);
  }
  if (user == null) {
    user=new PetstoreUser();
    session.setAttribute(sessionKey,user);
  }
  PetstoreUser.setCurrentUser(user);
  return new Status(rundata,user);
}
 

Example 34

From project drools-planner, under directory /drools-planner-webexamples/src/main/java/org/drools/planner/webexamples/vehiclerouting/.

Source file: VrpShowScheduleServlet.java

  31 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException {
  HttpSession session=req.getSession();
  VrpSchedule shownSolution=(VrpSchedule)session.getAttribute(VrpSessionAttributeName.SHOWN_SOLUTION);
  Dimension size=new Dimension(800,600);
  BufferedImage image;
  if (shownSolution == null) {
    schedulePainter.createCanvas(size.width,size.height);
  }
 else {
    schedulePainter.reset(shownSolution,size,null);
  }
  image=schedulePainter.getCanvas();
  resp.setContentType("image/png");
  ImageIO.write(image,"png",resp.getOutputStream());
}
 

Example 35

From project empire-db, under directory /empire-db-struts2/src/main/java/org/apache/empire/struts2/web/.

Source file: EmpireStrutsDispatcher.java

  31 
vote

protected void createSessionObject(HttpServletRequest request,Object applObj){
  try {
    HttpSession httpSession=request.getSession(false);
    if (httpSession == null || httpSession.getAttribute(WebSession.SESSION_NAME) == null) {
      Object session=createObject(sessionClassName);
      httpSession=request.getSession(true);
      if (session instanceof WebSession) {
        ((WebSession)session).init(new ServletSessionWrapper(httpSession),applObj);
      }
 else       log.warn("Session object does not implement IWebSession!");
      httpSession.setAttribute(WebSession.SESSION_NAME,session);
    }
  }
 catch (  Exception e) {
    log.error("Failed to create session [" + sessionClassName + "] msg= "+ e.getMessage());
  }
}
 

Example 36

From project gitblit, under directory /src/com/gitblit/.

Source file: AuthenticationFilter.java

  31 
vote

/** 
 * Taken from Jetty's LoginAuthenticator.renewSessionOnAuthentication()
 */
@SuppressWarnings("unchecked") protected void newSession(HttpServletRequest request,HttpServletResponse response){
  HttpSession oldSession=request.getSession(false);
  if (oldSession != null && oldSession.getAttribute(SESSION_SECURED) == null) {
synchronized (this) {
      Map<String,Object> attributes=new HashMap<String,Object>();
      Enumeration<String> e=oldSession.getAttributeNames();
      while (e.hasMoreElements()) {
        String name=e.nextElement();
        attributes.put(name,oldSession.getAttribute(name));
        oldSession.removeAttribute(name);
      }
      oldSession.invalidate();
      HttpSession newSession=request.getSession(true);
      newSession.setAttribute(SESSION_SECURED,Boolean.TRUE);
      for (      Map.Entry<String,Object> entry : attributes.entrySet()) {
        newSession.setAttribute(entry.getKey(),entry.getValue());
      }
    }
  }
}
 

Example 37

From project guice-jit-providers, under directory /extensions/servlet/test/com/google/inject/servlet/.

Source file: ServletTest.java

  31 
vote

public void testHttpSessionIsSerializable() throws IOException, ClassNotFoundException, ServletException {
  final Injector injector=createInjector();
  final HttpServletRequest request=newFakeHttpServletRequest();
  final HttpSession session=request.getSession();
  GuiceFilter filter=new GuiceFilter();
  final boolean[] invoked=new boolean[1];
  FilterChain filterChain=new FilterChain(){
    public void doFilter(    ServletRequest servletRequest,    ServletResponse servletResponse){
      invoked[0]=true;
      assertNotNull(injector.getInstance(InSession.class));
      assertNull(injector.getInstance(IN_SESSION_NULL_KEY));
    }
  }
;
  filter.doFilter(request,null,filterChain);
  assertTrue(invoked[0]);
  HttpSession deserializedSession=reserialize(session);
  String inSessionKey=IN_SESSION_KEY.toString();
  String inSessionNullKey=IN_SESSION_NULL_KEY.toString();
  assertTrue(deserializedSession.getAttribute(inSessionKey) instanceof InSession);
  assertEquals(NullObject.INSTANCE,deserializedSession.getAttribute(inSessionNullKey));
}
 

Example 38

From project guj.com.br, under directory /src/net/jforum/.

Source file: ForumSessionListener.java

  31 
vote

/** 
 * @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
 */
public void sessionDestroyed(HttpSessionEvent event){
  HttpSession session=event.getSession();
  if (session == null) {
    return;
  }
  String sessionId=session.getId();
  try {
    SessionFacade.storeSessionData(sessionId);
  }
 catch (  Exception e) {
    logger.warn(e);
  }
  logger.info("Destroying the session for: " + sessionId);
  SessionFacade.remove(sessionId);
}
 

Example 39

From project Hackathon_Chutaum, under directory /src/br/com/chutaum/servlet/.

Source file: LoginFacebook.java

  31 
vote

public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {
  if (req.getParameter("access_token") != null) {
    URL u=new URL("https://graph.facebook.com/me?access_token=" + req.getParameter("access_token").toString());
    JSONTokener reader=new JSONTokener(new InputStreamReader(u.openStream()));
    JSONObject jsonObject;
    try {
      jsonObject=new JSONObject(reader);
      if (jsonObject.getString("email") != null) {
        HttpSession session=req.getSession();
        UserController.login(jsonObject.getString("email"));
        session.setAttribute("authenticatedUserName",jsonObject.getString("email"));
        Key ancestorKey=KeyFactory.createKey("User",jsonObject.getString("email"));
        Iterable<Entity> actions=Util.listChildren("UserAction",ancestorKey,2,0);
        int count=0;
        for (        Entity tmp : actions) {
          count++;
        }
        if (count == 0) {
          res.sendRedirect("/");
        }
 else {
          res.sendRedirect("/cidadao");
        }
      }
 else {
        res.sendRedirect("/");
      }
    }
 catch (    JSONException e) {
      res.sendRedirect("/");
    }
  }
}
 

Example 40

From project hadoop_framework, under directory /webapp/src/main/java/org/sleuthkit/web/sampleapp/server/.

Source file: SecurityFilter.java

  31 
vote

@Override public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException, ServletException {
  boolean authorized=false;
  HttpSession session=((HttpServletRequest)req).getSession();
  String authVal=(String)session.getAttribute("SAMPLE_GWT_AUTH");
  if (authVal != null)   authorized=authVal.equals("y");
  if (authorized) {
    chain.doFilter(req,res);
  }
 else {
    String username=req.getParameter("username");
    String password=req.getParameter("password");
    if (username != null && password != null) {
      if (checkCredentials(username,password)) {
        session.setAttribute("SAMPLE_GWT_AUTH","y");
        session.setMaxInactiveInterval(SESSION_TIMEOUT * 60);
        ((HttpServletResponse)res).sendRedirect("/sampleapp/SampleApp.jsp");
      }
 else {
        String loginUrl="/sampleapp/login.jsp?failed=true";
        ((HttpServletResponse)res).sendRedirect(loginUrl);
      }
    }
 else {
      String loginUrl="/sampleapp/login.jsp";
      ((HttpServletResponse)res).sendRedirect(loginUrl);
    }
  }
}
 

Example 41

From project harmony, under directory /harmony.ui.webgui/src/server/common/.

Source file: CommonServiceImpl.java

  31 
vote

public Boolean logIn(final String username,final String password) throws GuiException {
  final HttpSession session=this.getRequest().getSession();
  String upwd="";
  try {
    upwd=Config.getString("management",username + ".pwd").trim();
  }
 catch (  final RuntimeException e) {
    return new Boolean(false);
  }
  String hash="";
  try {
    final MessageDigest digest=MessageDigest.getInstance("SHA");
    final byte[] passedIn=digest.digest(password.getBytes());
    for (int i=0; i < passedIn.length; i++) {
      final String hex=Integer.toHexString(passedIn[i] & 0xff);
      hash+=(hex.length() > 1) ? hex : "0" + hex;
    }
  }
 catch (  final NoSuchAlgorithmException e) {
    throw new GuiException("SHA not supported on your system");
  }
  if (upwd.equals(hash)) {
    final SessionInformation info=new SessionInformation((new Date()).getTime(),0,username);
    this.loggedInUsers.put(session.getId(),info);
    return new Boolean(true);
  }
  return new Boolean(false);
}
 

Example 42

From project interoperability-framework, under directory /interfaces/taverna/T2-Client/workflow-lib/src/main/java/eu/impact_project/iif/t2/client/.

Source file: GroupSelector.java

  31 
vote

/** 
 * Sets the currently selected myExperiment groups
 */
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  HttpSession session=request.getSession(true);
  int i=0;
  while (request.getParameter("MyExpGroup" + i) != null || request.getAttribute("MyExpGroup" + i) != null) {
    String groupName="";
    String groupParam=request.getParameter("MyExpGroup" + i);
    String groupAttrib=(String)request.getAttribute("MyExpGroup" + i);
    if (groupParam != null) {
      groupName=groupParam;
    }
 else     if (groupAttrib != null) {
      groupName=groupAttrib;
    }
    session.setAttribute("selectedGroupName" + i,groupName);
    String workflowUrl="";
    String workflowParam=request.getParameter("MyExpWorkflow" + i);
    String workflowAttrib=(String)request.getAttribute("MyExpWorkflow" + i);
    if (workflowParam != null) {
      workflowUrl=workflowParam;
    }
 else     if (workflowAttrib != null) {
      workflowUrl=workflowAttrib;
    }
    session.setAttribute("currentWfId" + i,workflowUrl);
    i++;
  }
  RequestDispatcher rd=getServletContext().getRequestDispatcher("/");
  rd.forward(request,response);
}
 

Example 43

From project ipdburt, under directory /iddb-web/src/main/java/iddb/web/security/service/.

Source file: CommonUserService.java

  31 
vote

protected void createUserSession(HttpServletRequest request,HttpServletResponse response,Subject subject,boolean persistent){
  HttpSession session=request.getSession(true);
  session.setAttribute(UserService.SUBJECT,subject);
  saveLocal(subject);
  String sessionKey=HashUtils.generate(subject.getLoginId());
  session.setAttribute(UserService.SESSION_KEY,sessionKey);
  Cookie cookieKey=new Cookie("iddb-k",sessionKey);
  Cookie cookieUser=new Cookie("iddb-u",subject.getKey().toString());
  cookieKey.setPath(request.getContextPath() + "/");
  cookieUser.setPath(request.getContextPath() + "/");
  if (persistent) {
    cookieKey.setMaxAge(COOKIE_EXPIRE_REMEMBER);
    cookieUser.setMaxAge(COOKIE_EXPIRE_REMEMBER);
  }
 else {
    cookieKey.setMaxAge(-1);
    cookieUser.setMaxAge(-1);
  }
  response.addCookie(cookieKey);
  response.addCookie(cookieUser);
  log.trace("Create new session {}, {}, {}",new String[]{sessionKey,subject.getKey().toString(),request.getRemoteAddr()});
  createSession(sessionKey,subject.getKey(),request.getRemoteAddr());
}
 

Example 44

From project accesointeligente, under directory /src/org/accesointeligente/server/.

Source file: SessionUtil.java

  29 
vote

public static SessionData getSessionData(HttpSession session) throws SessionServiceException {
  if (session == null) {
    throw new SessionServiceException();
  }
  String sessionId=(String)session.getAttribute("sessionId");
  User user=(User)session.getAttribute("user");
  if (sessionId == null || user == null) {
    throw new SessionServiceException();
  }
 else {
    SessionData sessionData=new SessionData();
    sessionData.getData().put("sessionId",sessionId);
    sessionData.getData().put("user",user);
    return sessionData;
  }
}
 

Example 45

From project components-ness-tracking, under directory /src/test/java/com/nesscomputing/tracking/.

Source file: MockedHttpServletRequest.java

  29 
vote

@Override public HttpSession getSession(boolean create){
  if (create) {
    throw new UnsupportedOperationException();
  }
 else {
    return null;
  }
}
 

Example 46

From project dev-examples, under directory /misc-demo/src/main/java/org/richfaces/demo/.

Source file: TestIdentityFilter.java

  29 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletRequestWrapper wrapper=new HttpServletRequestWrapper((HttpServletRequest)request){
    private UserBean getUserBean(){
      HttpSession session=getSession(false);
      if (session != null) {
        return (UserBean)session.getAttribute("userBean");
      }
      return null;
    }
    @Override public boolean isUserInRole(    String role){
      UserBean userBean=getUserBean();
      if (userBean != null) {
        return userBean.isUserInRole(role);
      }
      return false;
    }
    @Override public Principal getUserPrincipal(){
      UserBean userBean=getUserBean();
      if (userBean != null) {
        return userBean.getPrincipal();
      }
      return null;
    }
    @Override public String getRemoteUser(){
      UserBean userBean=getUserBean();
      if (userBean != null) {
        return userBean.getRolename();
      }
      return null;
    }
  }
;
  chain.doFilter(wrapper,response);
}
 

Example 47

From project egov-data, under directory /easyCompany2/src/main/java/egovframework/rte/tex/cgr/web/.

Source file: EgovCategoryController.java

  29 
vote

/** 
 * ?????? ??? ?? ? ?????? ?????? ??????.
 * @param categoryVO ?????? ???
 * @param results validation???
 * @param session ??? ???
 * @param model
 * @return "redirect:/springrest/cgr.html"
 * @throws Exception
 */
@RequestMapping(value="/springrest/cgr",method=RequestMethod.POST,headers="Content-type=application/x-www-form-urlencoded") public String create(@Valid CategoryVO categoryVO,BindingResult results,HttpSession session,Model model) throws Exception {
  if (results.hasErrors()) {
    return "cgr/egovCategoryRegister";
  }
  categoryService.insertCategory(categoryVO);
  return "redirect:/springrest/cgr.html";
}
 

Example 48

From project excilys-bank, under directory /excilys-bank-web/src/main/java/com/excilys/ebi/bank/web/controller/.

Source file: LoginController.java

  29 
vote

@RequestMapping("/public/login.html") public String login(ModelMap model,HttpSession session){
  if (session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY) != null) {
    return "redirect:" + loginSuccessHandler.getHomeUrl();
  }
  return "public/login";
}
 

Example 49

From project framework, under directory /impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/.

Source file: SecurityObserver.java

  29 
vote

public void onLogoutSuccessful(@Observes final AfterLogoutSuccessful event){
  try {
    if (config.isRedirectEnabled()) {
      Redirector.redirect(config.getRedirectAfterLogout());
    }
  }
 catch (  PageNotFoundException cause) {
    throw new ConfigurationException("A tela \"" + cause.getViewId() + "\" que ? invocada ap?s o logout n?o foi encontrada. Caso o seu projeto possua outra, defina no arquivo de configura??o a chave \""+ "frameworkdemoiselle.security.redirect.after.logout"+ "\"",cause);
  }
 finally {
    try {
      Beans.getReference(HttpSession.class).invalidate();
    }
 catch (    IllegalStateException e) {
      logger.debug("Esta sess?o j? foi invalidada.");
    }
  }
}
 

Example 50

From project fuzzydb-samples, under directory /sample-webapp/src/main/java/org/fuzzydb/samples/security/.

Source file: SimpleSignInAdapter.java

  29 
vote

private void removeAutheticationAttributes(HttpSession session){
  if (session == null) {
    return;
  }
  session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
 

Example 51

From project greenhouse, under directory /src/main/java/com/springsource/greenhouse/connect/.

Source file: AccountSignInAdapter.java

  29 
vote

private void removeAutheticationAttributes(HttpSession session){
  if (session == null) {
    return;
  }
  session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
 

Example 52

From project gxa, under directory /atlas-web/src/main/java/ae3/service/.

Source file: AtlasDownloadService.java

  29 
vote

/** 
 * Starts a new download within the session, with query parameters.
 * @param session session in which the download is kept
 * @param query   download query
 * @return download id, always positive; -1 in case of error.
 */
public int requestDownload(HttpSession session,AtlasStructuredQuery query){
  Map<Integer,Download> downloadList;
  if (downloads.containsKey(session.getId())) {
    downloadList=downloads.get(session.getId());
  }
 else {
    downloadList=synchronizedMap(new LinkedHashMap<Integer,Download>());
  }
  try {
    final String q=query.toString();
    for (    Download d : downloadList.values()) {
      if (d.getQuery().equals(q)) {
        log.info("There's already a download {} going on - ignoring request.",q);
        return -1;
      }
    }
    final Download download=new Download(countDownloads.incrementAndGet(),atlasStructuredQueryService,atlasStatisticsQueryService,geneSolrDAO,query,atlasProperties.getDataRelease());
    downloadList.put(download.getId(),download);
    downloads.put(session.getId(),downloadList);
    downloadThreadPool.execute(download);
    return download.getId();
  }
 catch (  IOException e) {
    log.error("Problem creating new download for {}, error {}",query,e.getMessage());
  }
  return -1;
}