Java 类org.apache.catalina.session.StandardSession 实例源码

项目:geeCommerce-Java-Shop-Software-and-PIM    文件:JavaSerializer.java   
public static byte[] serializeFrom(HttpSession session) throws IOException, NoSuchFieldException, SecurityException,
    IllegalArgumentException, IllegalAccessException {
    if (session != null) {
        Field facadeSessionField = StandardSessionFacade.class.getDeclaredField("session");
        facadeSessionField.setAccessible(true);
        StandardSession standardSession = (StandardSession) facadeSessionField.get(session);

        if (standardSession != null) {
            // StandardSessionFacade standardSession =
            // (StandardSessionFacade) session;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos));
            oos.writeLong(standardSession.getCreationTime());
            standardSession.writeObjectData(oos);

            oos.close();

            return bos.toByteArray();
        }
    }

    return null;
}
项目:geeCommerce-Java-Shop-Software-and-PIM    文件:JavaSerializer.java   
public static HttpSession deserializeInto(byte[] data, HttpSession session, ClassLoader loader)
    throws IOException, ClassNotFoundException, NoSuchFieldException, SecurityException,
    IllegalArgumentException, IllegalAccessException {
    if (data != null && data.length > 0 && session != null) {
        Field facadeSessionField = StandardSessionFacade.class.getDeclaredField("session");
        facadeSessionField.setAccessible(true);
        StandardSession standardSession = (StandardSession) facadeSessionField.get(session);

        // StandardSessionFacade standardSession = (StandardSessionFacade)
        // session;

        BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(data));

        ObjectInputStream ois = new CustomObjectInputStream(bis, loader);
        standardSession.setCreationTime(ois.readLong());
        standardSession.readObjectData(ois);
    }

    return session;
}
项目:session-managers    文件:SessionSerializationUtils.java   
/**
 * Serialize a {@link Session}
 *
 * @param session the {@link Session} to serialize
 * @return a {@code byte[]} representing the serialized {@link Session}
 * @throws IOException
 */
public byte[] serialize(Session session) throws IOException {
    ByteArrayOutputStream bytes = null;
    ObjectOutputStream out = null;

    try {
        bytes = new ByteArrayOutputStream();
        out = new ObjectOutputStream(bytes);

        StandardSession standardSession = (StandardSession) session;
        standardSession.writeObjectData(out);

        out.flush();
        bytes.flush();

        return bytes.toByteArray();
    } finally {
        closeQuietly(out, bytes);
    }

}
项目:aws-dynamodb-session-tomcat    文件:DefaultDynamoSessionItemConverter.java   
@Override
public DynamoSessionItem toSessionItem(Session session) {
    ObjectOutputStream oos = null;
    try {
        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(fos);
        ((StandardSession) session).writeObjectData(oos);
        oos.close();
        DynamoSessionItem sessionItem = new DynamoSessionItem(session.getIdInternal());
        sessionItem.setSessionData(ByteBuffer.wrap(fos.toByteArray()));
        return sessionItem;
    } catch (Exception e) {
        IOUtils.closeQuietly(oos, null);
        throw new SessionConversionException("Unable to convert Tomcat Session into Dynamo storage representation",
                e);
    }
}
项目:aws-dynamodb-session-tomcat    文件:TestSessionFactory.java   
public final StandardSession createStandardSession() {
    TestStandardSession session = new TestStandardSession(null);
    session.setValid(true);
    session.setId(getSessionId(), false);
    session.setCreationTime(getCreationTime());
    session.setMaxInactiveInterval(maxInactiveInterval);
    session.setLastAccessedTime(lastAccessedTime);

    Map<String, Object> sessionData = getSessionAttributes();
    if (sessionData != null) {
        for (Entry<String, Object> attr : sessionData.entrySet()) {
            session.setAttribute(attr.getKey(), attr.getValue(), false);
        }
    }
    session.setManager(getManager());
    return session;
}
项目:tomcat7    文件:TesterRequest.java   
public TesterRequest(boolean withSession) {
    context = new TesterContext();
    servletContext = new TesterServletContext();
    context.setServletContext(servletContext);
    if (withSession) {
        Set<SessionTrackingMode> modes = new HashSet<SessionTrackingMode>();
        modes.add(SessionTrackingMode.URL);
        modes.add(SessionTrackingMode.COOKIE);
        servletContext.setSessionTrackingModes(modes);
        session = new StandardSession(null);
        session.setId("1234", false);
        session.setValid(true);
    }
}
项目:apache-tomcat-7.0.73-with-comment    文件:TesterRequest.java   
public TesterRequest(boolean withSession) {
    context = new TesterContext();
    servletContext = new TesterServletContext();
    context.setServletContext(servletContext);
    if (withSession) {
        Set<SessionTrackingMode> modes = new HashSet<SessionTrackingMode>();
        modes.add(SessionTrackingMode.URL);
        modes.add(SessionTrackingMode.COOKIE);
        servletContext.setSessionTrackingModes(modes);
        session = new StandardSession(null);
        session.setId("1234", false);
        session.setValid(true);
    }
}
项目:appng-tomcat-session    文件:RedisSessionMangagerIT.java   
@Test
public void test() throws Exception {
    StandardContext context = new StandardContext();
    context.setName("foo");
    WebappLoader loader = new WebappLoader() {
        @Override
        public ClassLoader getClassLoader() {
            return WebappLoader.class.getClassLoader();
        }
    };
    context.setLoader(loader);
    StandardHost host = new StandardHost();
    StandardEngine engine = new StandardEngine();
    engine.setService(new StandardService());
    host.setParent(engine);
    context.setParent(host);
    loader.setContext(context);

    RedisSessionManager manager = new RedisSessionManager();
    manager.setSessionIdGenerator(new StandardSessionIdGenerator());
    manager.setContext(context);
    manager.initializeSerializer();
    manager.initializeDatabaseConnection();
    manager.clear();

    StandardSession session = manager.createSession(null);
    session.setAttribute("foo", "test");

    manager.afterRequest();

    StandardSession loaded = manager.findSession(session.getId());
    Assert.assertEquals(session.getAttribute("foo"), loaded.getAttribute("foo"));

    Assert.assertEquals(1, manager.getSize());
    Assert.assertArrayEquals(new String[] { session.getId() }, manager.keys());

    manager.processExpires();

}
项目:appng-tomcat-session    文件:UtilsTest.java   
@Test
public void test() throws Exception {
    MockServletContext ctx = new MockServletContext();
    StandardManager manager = new StandardManager();
    manager.setContext(new StandardContext());
    StandardSession session = new StandardSession(manager);
    session.setId("4711");
    session.setValid(true);
    session.setAttribute("foo", "bar");
    session.setAttribute("property", new SimpleProperty("foo", "bar"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    session.writeObjectData(oos);
    oos.flush();
    oos.close();
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    ObjectInputStream ois = Utils.getObjectInputStream(contextClassLoader, ctx, baos.toByteArray());

    StandardSession newSession = new StandardSession(manager);
    newSession.readObjectData(ois);
    Assert.assertEquals(session.getId(), newSession.getId());
    Assert.assertEquals("4711", newSession.getId());
    Assert.assertEquals(session.getAttribute("foo"), newSession.getAttribute("foo"));
    Assert.assertEquals("bar", newSession.getAttribute("foo"));
    Assert.assertEquals(SimpleProperty.class, newSession.getAttribute("property").getClass());
    Assert.assertEquals("bar", ((Property) newSession.getAttribute("property")).getString());

}
项目:hazelcast-tomcat-sessionmanager    文件:HazelcastSession.java   
/**
 * "attributes" field type is changed to ConcurrentMap with Tomcat 8.0.35+ and this causes NoSuchFieldException
 * if accessed directly. "attributes" is accessed through reflection to support Tomcat 8.0.35+
 */
private static Field getAttributesField() {
    try {
        Field attributesField = StandardSession.class.getDeclaredField("attributes");
        attributesField.setAccessible(true);
        return attributesField;
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    }
}
项目:WicketRedisSession    文件:CatalinaRedisSessionStore.java   
@Override
public void save(Session session) throws IOException {
    try{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos));

        ((StandardSession) session).writeObjectData(oos);
        oos.close();
        oos = null;
        byte[] obs = bos.toByteArray();
        redisCache.storeCacheObject(KEY_PREFIX_SESSION + session.getIdInternal(), obs);
    }catch(Exception e){

    }
}
项目:elpi    文件:OfbizStore.java   
public void save(Session session) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos));

    ((StandardSession) session).writeObjectData(oos);
    oos.close();
    oos = null;

    byte[] obs = bos.toByteArray();
    int size = obs.length;

    GenericValue sessionValue = delegator.makeValue(entityName);
    sessionValue.setBytes("sessionInfo", obs);
    sessionValue.set("sessionId", session.getId());
    sessionValue.set("sessionSize", size);
    sessionValue.set("isValid", session.isValid() ? "Y" : "N");
    sessionValue.set("maxIdle", session.getMaxInactiveInterval());
    sessionValue.set("lastAccessed", session.getLastAccessedTime());

    try {
        delegator.createOrStore(sessionValue);
    } catch (GenericEntityException e) {
        throw new IOException(e.getMessage());
    }

    Debug.logInfo("Persisted session [" + session.getId() + "]", module);
}
项目:session-managers    文件:RedisStoreTest.java   
@Test
public void load() throws IOException {
    Session session = new StandardSession(this.manager);
    session.setId("test-id");
    byte[] response = this.sessionSerializationUtils.serialize(session);

    when(this.jedisClient.get("test-id")).thenReturn(response);

    Session result = this.store.load("test-id");

    assertEquals(session.getId(), result.getId());
}
项目:session-managers    文件:RedisStoreTest.java   
@Test
public void save() throws IOException {
    Session session = new StandardSession(this.manager);
    session.setId("test-id");

    this.store.save(session);

    verify(this.jedisClient).set(getRedisSessionId(session), SESSIONS_KEY, this.sessionSerializationUtils.serialize(session), session.getMaxInactiveInterval());
}
项目:session-managers    文件:RedisStoreTest.java   
@Test
public void saveJedisConnectionException() throws UnsupportedEncodingException {
    Session session = new StandardSession(this.manager);
    session.setId("test-id");

    doThrow(new JedisConnectionException("test-message"))
            .when(this.jedisClient)
            .set(anyString(), anyString(), any((byte[].class)), eq(session.getMaxInactiveInterval()));

    this.store.save(session);
}
项目:session-managers    文件:SessionSerializationUtils.java   
/**
 * Deserialize a {@link Session}
 *
 * @param session a {@code byte[]} representing the serialized {@link Session}
 * @return the deserialized {@link Session} or {@code null} if the session data is {@code null}
 * @throws ClassNotFoundException
 * @throws IOException
 */
public Session deserialize(byte[] session) throws ClassNotFoundException, IOException {
    if (session == null) {
        return null;
    }

    ByteArrayInputStream bytes = null;
    ObjectInputStream in = null;
    Context context = this.manager.getContext();
    ClassLoader oldThreadContextCL = context.bind(Globals.IS_SECURITY_ENABLED, null);

    try {
        bytes = new ByteArrayInputStream(session);
        in = new ObjectInputStream(bytes) {
            @Override
            protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                try {
                    return Class.forName(desc.getName(), false, Thread.currentThread().getContextClassLoader());
                } catch (ClassNotFoundException cnfe) {
                    return super.resolveClass(desc);
                }
            }
        };

        StandardSession standardSession = (StandardSession) this.manager.createEmptySession();
        standardSession.readObjectData(in);

        return standardSession;
    } finally {
        closeQuietly(in, bytes);
        context.unbind(Globals.IS_SECURITY_ENABLED, oldThreadContextCL);
    }
}
项目:o3erp    文件:OfbizStore.java   
public void save(Session session) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos));

    ((StandardSession) session).writeObjectData(oos);
    oos.close();
    oos = null;

    byte[] obs = bos.toByteArray();
    int size = obs.length;

    GenericValue sessionValue = delegator.makeValue(entityName);
    sessionValue.setBytes("sessionInfo", obs);
    sessionValue.set("sessionId", session.getId());
    sessionValue.set("sessionSize", size);
    sessionValue.set("isValid", session.isValid() ? "Y" : "N");
    sessionValue.set("maxIdle", session.getMaxInactiveInterval());
    sessionValue.set("lastAccessed", session.getLastAccessedTime());

    try {
        delegator.createOrStore(sessionValue);
    } catch (GenericEntityException e) {
        throw new IOException(e.getMessage());
    }

    Debug.logInfo("Persisted session [" + session.getId() + "]", module);
}
项目:mongo-session-manager    文件:MongoStoreTest.java   
/**
 * @throws java.lang.Exception
 */
@Before
public void setUp() throws Exception {
    /* set up the manager */
    this.manager.setContainer(new StandardContext());
    this.manager.getContainer().setName("test");
    this.manager.getContainer().setParent(new StandardEngine());
    this.manager.getContainer().getParent().setName("parent");


    /* create the store */
    this.mongoStore = new MongoStore();
    this.mongoStore.setHosts("127.0.0.1:27017");
    this.mongoStore.setDbName("unitest");
    this.mongoStore.setManager(manager);

    this.manager.setStore(mongoStore);

    /* initialize the store */
    this.manager.start();

    /* create the test session */
    this.testSession = (StandardSession)this.manager.createSession(this.sessionId);

    /* add some data */
    this.testSession.setAttribute("test", "test", false);       
}
项目:mongo-session-manager    文件:MongoStoreTest.java   
/**
 * Test method for {@link org.hbr.session.store.MongoStore#save(org.apache.catalina.Session)}.
 * and {@link org.hbr.session.store.MongoStore#load(java.lang.String)}
 */
@Test
public void testLoadAndSave() throws Exception {
    /* save our session */
    this.mongoStore.save(this.testSession);

    /* load the session */
    Session session = this.mongoStore.load(this.sessionId);
    assertNotNull(session);
    assertNotNull(((StandardSession)session).getAttribute("test"));
}
项目:jRender    文件:ViewSession.java   
ViewSession(int id, HttpSession session, ViewSessionContext context) {
    this.session = (StandardSession) GenericReflection.NoThrow.getValue(f, session);
    this.id = id;
    this.context = context;
    context.addView(id, this);

    setMaxInactiveInterval(maxInactiveInterval);

    // System.out.println("View session("+id+") created");
}
项目:smonitor    文件:TomcatUtil.java   
/**
 * Deletes the session for host, application and session id.
 *
 * @param host the host.
 * @param webApp the application.
 * @param sessionId the session id.
 * @return the deleted session to the host, application and session id.
 */
public static Session deleteSession(Service service, String host, String application, String sessionId) {
    String id = createTomcatApplicationId(application);
    Session result = null;
    StandardSession tmp = getSession(service, host, id, sessionId);
    if (tmp != null) {
        tmp.invalidate();

        result = createSession(host, application, tmp);
        LOGGER.log(Level.INFO, "The session id {0}, application {1} and host {2} was deleted", new Object[]{sessionId, application, host});
    } else {
        LOGGER.log(Level.FINEST, "No session found for id {0}, application {0} and host {1}", new Object[]{sessionId, application, host});
    }
    return result;        
}
项目:appng-tomcat-session    文件:MongoStoreIT.java   
@Test
public void test() throws Exception {
    StandardContext context = new StandardContext();
    context.setName("foo");
    WebappLoader loader = new WebappLoader() {
        @Override
        public ClassLoader getClassLoader() {
            return WebappLoader.class.getClassLoader();
        }
    };
    context.setLoader(loader);
    StandardHost host = new StandardHost();
    StandardEngine engine = new StandardEngine();
    engine.setService(new StandardService());
    host.setParent(engine);
    context.setParent(host);
    loader.setContext(context);

    MongoPersistentManager manager = new MongoPersistentManager();
    manager.setContext(context);

    MongoStore store = new MongoStore();
    store.setManager(manager);
    store.setHosts("localhost:27017");
    store.setDbName("mongo_session_test");
    store.setCollectionName("mongo_session_test");
    manager.setStore(store);
    store.start();

    StandardSession session = new StandardSession(manager);
    session.setId("4711");
    session.setNew(true);
    session.setValid(true);
    session.setCreationTime(System.currentTimeMillis());

    session.setAttribute("foo", "test");

    store.save(session);

    StandardSession loaded = store.load(session.getId());
    Assert.assertEquals(session.getAttribute("foo"), loaded.getAttribute("foo"));

    Assert.assertEquals(1, store.getSize());
    Assert.assertArrayEquals(new String[] { "4711" }, store.keys());
}
项目:distributed-session-manager    文件:RocketMqManager.java   
@Override
protected StandardSession getNewSession() {
    return new RocketMqSession(this);
}
项目:distributed-session-manager    文件:RedisManager.java   
/**
 * 间接被createSession()调用.
 */
@Override
protected StandardSession getNewSession() {
    return new RedisSession(this);
}
项目:tomcat-runtime    文件:DatastoreManager.java   
@Override
protected StandardSession getNewSession() {
  return new DatastoreSession(this);
}
项目:hazelcast-archive    文件:HazelcastManager.java   
/**
 * Get new session class to be used in the doLoad() method.
 */
protected StandardSession getNewSession() {
    return new HazelcastSession(this);
}
项目:aws-dynamodb-session-tomcat    文件:DefaultSessionConverterTest.java   
@Test
public void roundTrip_NoSessionData_ReturnsSameSession() throws Exception {
    StandardSession session = new TestSessionFactory().withSessionAttributes(null).createStandardSession();
    Session roundTripSession = sessionConverter.toSession(sessionConverter.toSessionItem(session));
    assertSessionEquals(session, roundTripSession);
}
项目:smonitor    文件:TomcatUtil.java   
/**
 * Creates the session details.
 *
 * @param host the host.
 * @param application the application.
 * @param sessionId the session id.
 * @return the session details.
 */
public static SessionDetails createSessionDetails(Service service, String host, String application, String sessionId) {

    String id = TomcatUtil.createTomcatApplicationId(application);
    StandardSession session = getSession(service, host, id, sessionId);

    SessionDetails result = null;

    if (session != null) {
        result = new SessionDetails();

        // session info
        result.setInfo(session.getInfo());

        // create session basic information
        Session tmp = createSession(host, application, session);
        result.setSession(tmp);

        // load user roles
        GenericPrincipal principal = (GenericPrincipal) session.getPrincipal();
        if (principal != null) {
            String[] roles = principal.getRoles();
            if (roles != null) {
                result.setRoles(Arrays.asList(roles));
            }
        }

        if (session instanceof StandardSession) {

            StandardSession standardSession = (StandardSession) session;

            // is new session flag
            result.setNewSession(standardSession.isNew());

            double size = 0;
            double sizeSerializable = 0;

            List<Attribute> attributes = new ArrayList<Attribute>();

            Enumeration enumerator = standardSession.getAttributeNames();
            while (enumerator.hasMoreElements()) {
                String name = (String) enumerator.nextElement();
                Attribute attr = createAttribute(name, standardSession.getAttribute(name));
                attributes.add(attr);
                size = size + attr.getSize();
                sizeSerializable = sizeSerializable + attr.getSerializableSize();
            }

            result.setSize(size);
            result.setSizeSerializable(sizeSerializable);
            result.setAttributes(attributes);
        }

    }
    return result;
}
项目:smonitor    文件:TomcatUtil.java   
/**
 * Creates the session.
 *
 * @param session the session.
 * @return the session.
 */
public static Session createSession(Service service, String host, String application, String sessionId) {
    String id = createTomcatApplicationId(application);
    StandardSession session = getSession(service, host, id, sessionId);
    return createSession(host, application, session);
}