repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/sso/coarse/CoarseSSOSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.sso.coarse; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; import org.wildfly.clustering.marshalling.protostream.ValueMarshaller; import org.wildfly.clustering.web.cache.SessionKeyMarshaller; /** * @author Paul Ferraro */ @MetaInfServices(SerializationContextInitializer.class) public class CoarseSSOSerializationContextInitializer extends AbstractSerializationContextInitializer { @Override public void registerMarshallers(SerializationContext context) { context.registerMarshaller(new SessionKeyMarshaller<>(CoarseSessionsKey.class, CoarseSessionsKey::new)); context.registerMarshaller(new ValueMarshaller<>(new SessionsFilter<>())); } }
1,946
43.25
112
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/logging/Logger.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.logging; import static org.jboss.logging.Logger.Level.*; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * @author Paul Ferraro */ @MessageLogger(projectCode = "WFLYCLWEBHR", length = 4) public interface Logger extends BasicLogger { String ROOT_LOGGER_CATEGORY = "org.wildfly.clustering.web.hotrod"; Logger ROOT_LOGGER = org.jboss.logging.Logger.getMessageLogger(Logger.class, ROOT_LOGGER_CATEGORY); @LogMessage(level = WARN) @Message(id = 1, value = "Failed to expire session %s") void failedToExpireSession(@Cause Throwable cause, String sessionId); // @Message(id = 3, value = "Session %s is not valid") // IllegalStateException invalidSession(String sessionId); @LogMessage(level = WARN) @Message(id = 7, value = "Failed to activate attributes of session %s") void failedToActivateSession(@Cause Throwable cause, String sessionId); @LogMessage(level = WARN) @Message(id = 8, value = "Failed to activate attribute %2$s of session %1$s") void failedToActivateSessionAttribute(@Cause Throwable cause, String sessionId, String attribute); @Message(id = 9, value = "Failed to read attribute %2$s of session %1$s") IllegalStateException failedToReadSessionAttribute(@Cause Throwable cause, String sessionId, String attribute); @LogMessage(level = WARN) @Message(id = 10, value = "Failed to activate authentication for single sign on %s") void failedToActivateAuthentication(@Cause Throwable cause, String ssoId); @LogMessage(level = WARN) @Message(id = 11, value = "Session %s is missing cache entry for attribute %s") void missingSessionAttributeCacheEntry(String sessionId, String attribute); }
2,941
42.264706
115
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/HotRodSessionManagerFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session; import java.time.Duration; import java.util.function.Consumer; import org.infinispan.client.hotrod.RemoteCache; import org.wildfly.clustering.Registrar; import org.wildfly.clustering.ee.cache.ConcurrentManager; import org.wildfly.clustering.ee.cache.tx.TransactionBatch; import org.wildfly.clustering.ee.hotrod.HotRodConfiguration; import org.wildfly.clustering.marshalling.spi.ByteBufferMarshaller; import org.wildfly.clustering.marshalling.spi.MarshalledValue; import org.wildfly.clustering.web.cache.session.CompositeSessionMetaDataEntry; import org.wildfly.clustering.web.cache.session.ConcurrentSessionManager; import org.wildfly.clustering.web.cache.session.DelegatingSessionManagerConfiguration; import org.wildfly.clustering.web.cache.session.MarshalledValueSessionAttributesFactoryConfiguration; import org.wildfly.clustering.web.cache.session.SessionAttributesFactory; import org.wildfly.clustering.web.cache.session.SessionFactory; import org.wildfly.clustering.web.cache.session.SessionMetaDataFactory; import org.wildfly.clustering.web.hotrod.session.coarse.CoarseSessionAttributesFactory; import org.wildfly.clustering.web.hotrod.session.fine.FineSessionAttributesFactory; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.SessionManager; import org.wildfly.clustering.web.session.SessionManagerConfiguration; import org.wildfly.clustering.web.session.SessionManagerFactory; /** * Factory for creating session managers. * @param <S> the HttpSession specification type * @param <SC> the ServletContext specification type * @param <AL> the HttpSessionAttributeListener specification type * @param <LC> the local context type * @author Paul Ferraro */ public class HotRodSessionManagerFactory<S, SC, AL, LC> implements SessionManagerFactory<SC, LC, TransactionBatch> { private final HotRodConfiguration configuration; private final Registrar<Consumer<ImmutableSession>> expirationListenerRegistrar; private final SessionFactory<SC, CompositeSessionMetaDataEntry<LC>, ?, LC> factory; public HotRodSessionManagerFactory(HotRodSessionManagerFactoryConfiguration<S, SC, AL, LC> configuration) { this.configuration = configuration; SessionMetaDataFactory<CompositeSessionMetaDataEntry<LC>> metaDataFactory = new HotRodSessionMetaDataFactory<>(configuration); HotRodSessionFactory<SC, ?, LC> sessionFactory = new HotRodSessionFactory<>(configuration, metaDataFactory, this.createSessionAttributesFactory(configuration), configuration.getLocalContextFactory()); this.factory = sessionFactory; this.expirationListenerRegistrar = sessionFactory; } @Override public SessionManager<LC, TransactionBatch> createSessionManager(SessionManagerConfiguration<SC> configuration) { Duration transactionTimeout = Duration.ofMillis(this.configuration.getCache().getRemoteCacheContainer().getConfiguration().transactionTimeout()); Registrar<Consumer<ImmutableSession>> expirationListenerRegistrar = this.expirationListenerRegistrar; HotRodSessionManagerConfiguration<SC> config = new AbstractHotRodSessionManagerConfiguration<>(configuration, this.configuration) { @Override public Registrar<Consumer<ImmutableSession>> getExpirationListenerRegistrar() { return expirationListenerRegistrar; } @Override public Duration getStopTimeout() { return transactionTimeout; } }; return new ConcurrentSessionManager<>(new HotRodSessionManager<>(this.factory, config), ConcurrentManager::new); } @Override public void close() { this.factory.close(); } private SessionAttributesFactory<SC, ?> createSessionAttributesFactory(HotRodSessionManagerFactoryConfiguration<S, SC, AL, LC> configuration) { switch (configuration.getAttributePersistenceStrategy()) { case FINE: { return new FineSessionAttributesFactory<>(new HotRodMarshalledValueSessionAttributesFactoryConfiguration<>(configuration)); } case COARSE: { return new CoarseSessionAttributesFactory<>(new HotRodMarshalledValueSessionAttributesFactoryConfiguration<>(configuration)); } default: { // Impossible throw new IllegalStateException(); } } } private abstract static class AbstractHotRodSessionManagerConfiguration<SC> extends DelegatingSessionManagerConfiguration<SC> implements HotRodSessionManagerConfiguration<SC> { private final HotRodConfiguration configuration; AbstractHotRodSessionManagerConfiguration(SessionManagerConfiguration<SC> managerConfiguration, HotRodConfiguration configuration) { super(managerConfiguration); this.configuration = configuration; } @Override public <CK, CV> RemoteCache<CK, CV> getCache() { return this.configuration.getCache(); } } private static class HotRodMarshalledValueSessionAttributesFactoryConfiguration<S, SC, AL, V, LC> extends MarshalledValueSessionAttributesFactoryConfiguration<S, SC, AL, V, LC> implements HotRodSessionAttributesFactoryConfiguration<S, SC, AL, V, MarshalledValue<V, ByteBufferMarshaller>> { private final HotRodSessionManagerFactoryConfiguration<S, SC, AL, LC> configuration; HotRodMarshalledValueSessionAttributesFactoryConfiguration(HotRodSessionManagerFactoryConfiguration<S, SC, AL, LC> configuration) { super(configuration); this.configuration = configuration; } @Override public <CK, CV> RemoteCache<CK, CV> getCache() { return this.configuration.getCache(); } } }
6,906
49.786765
293
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/HotRodSessionAttributesFactoryConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session; import org.wildfly.clustering.ee.cache.CacheProperties; import org.wildfly.clustering.ee.hotrod.HotRodConfiguration; import org.wildfly.clustering.web.cache.session.SessionAttributesFactoryConfiguration; /** * @author Paul Ferraro * @param <S> the HttpSession specification type * @param <C> the ServletContext specification type * @param <L> the HttpSessionActivationListener specification type * @param <V> attributes cache entry type * @param <SV> attributes serialized form type */ public interface HotRodSessionAttributesFactoryConfiguration<S, C, L, V, SV> extends SessionAttributesFactoryConfiguration<S, C, L, V, SV>, HotRodConfiguration { @Override default CacheProperties getCacheProperties() { return HotRodConfiguration.super.getCacheProperties(); } }
1,869
41.5
161
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/SessionManagerNearCacheFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.function.BiConsumer; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.configuration.NearCacheConfiguration; import org.infinispan.client.hotrod.near.NearCache; import org.infinispan.client.hotrod.near.NearCacheFactory; import org.wildfly.clustering.infinispan.client.near.CaffeineNearCache; import org.wildfly.clustering.infinispan.client.near.EvictionListener; import org.wildfly.clustering.infinispan.client.near.SimpleKeyWeigher; import org.wildfly.clustering.web.hotrod.session.coarse.SessionAttributesKey; import org.wildfly.clustering.web.hotrod.session.fine.SessionAttributeKey; import org.wildfly.clustering.web.hotrod.session.fine.SessionAttributeNamesKey; import org.wildfly.clustering.web.session.SessionAttributePersistenceStrategy; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; /** * A near-cache factory based on max-active-sessions. * @author Paul Ferraro */ public class SessionManagerNearCacheFactory implements NearCacheFactory { private final Integer maxActiveSessions; private final SessionAttributePersistenceStrategy strategy; public SessionManagerNearCacheFactory(Integer maxActiveSessions, SessionAttributePersistenceStrategy strategy) { this.maxActiveSessions = maxActiveSessions; this.strategy = strategy; } @Override public <K, V> NearCache<K, V> createNearCache(NearCacheConfiguration config, BiConsumer<K, MetadataValue<V>> removedConsumer) { EvictionListener<K, V> listener = (this.maxActiveSessions != null) ? new EvictionListener<>(removedConsumer, new InvalidationListener(this.strategy)) : null; Caffeine<Object, Object> builder = Caffeine.newBuilder(); if (listener != null) { builder.executor(Runnable::run) .maximumWeight(this.maxActiveSessions.longValue()) .weigher(new SimpleKeyWeigher(SessionCreationMetaDataKey.class::isInstance)) .removalListener(listener); } Cache<K, MetadataValue<V>> cache = builder.build(); if (listener != null) { listener.accept(cache); } return new CaffeineNearCache<>(cache); } private static class InvalidationListener implements BiConsumer<Cache<Object, MetadataValue<Object>>, Map.Entry<Object, Object>> { private final SessionAttributePersistenceStrategy strategy; InvalidationListener(SessionAttributePersistenceStrategy strategy) { this.strategy = strategy; } @Override public void accept(Cache<Object, MetadataValue<Object>> cache, Map.Entry<Object, Object> entry) { Object key = entry.getKey(); if (key instanceof SessionCreationMetaDataKey) { String id = ((SessionCreationMetaDataKey) key).getId(); List<Object> keys = new LinkedList<>(); keys.add(new SessionAccessMetaDataKey(id)); switch (this.strategy) { case COARSE: { keys.add(new SessionAttributesKey(id)); break; } case FINE: { SessionAttributeNamesKey namesKey = new SessionAttributeNamesKey(id); keys.add(namesKey); MetadataValue<Object> namesValue = cache.getIfPresent(namesKey); if (namesValue != null) { @SuppressWarnings("unchecked") Map<String, UUID> names = (Map<String, UUID>) namesValue.getValue(); for (UUID attributeId : names.values()) { keys.add(new SessionAttributeKey(id, attributeId)); } } break; } } cache.invalidateAll(keys); } } } }
5,189
44.130435
165
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/HotRodSessionFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session; import java.io.IOException; import java.nio.ByteBuffer; import java.time.Instant; import java.util.Collection; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.annotation.ClientCacheEntryExpired; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.ClientCacheEntryCustomEvent; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.Marshaller; import org.wildfly.clustering.Registrar; import org.wildfly.clustering.Registration; import org.wildfly.clustering.context.DefaultExecutorService; import org.wildfly.clustering.context.DefaultThreadFactory; import org.wildfly.clustering.ee.Remover; import org.wildfly.clustering.ee.hotrod.HotRodConfiguration; import org.wildfly.clustering.web.LocalContextFactory; import org.wildfly.clustering.web.cache.session.CompositeSessionFactory; import org.wildfly.clustering.web.cache.session.CompositeSessionMetaDataEntry; import org.wildfly.clustering.web.cache.session.ImmutableSessionAttributesFactory; import org.wildfly.clustering.web.cache.session.ImmutableSessionMetaDataFactory; import org.wildfly.clustering.web.cache.session.SessionAccessMetaData; import org.wildfly.clustering.web.cache.session.SessionAttributesFactory; import org.wildfly.clustering.web.cache.session.SessionCreationMetaDataEntry; import org.wildfly.clustering.web.cache.session.SessionMetaDataFactory; import org.wildfly.clustering.web.cache.session.SimpleSessionCreationMetaData; import org.wildfly.clustering.web.hotrod.logging.Logger; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.ImmutableSessionAttributes; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author Paul Ferraro */ @ClientListener(converterFactoryName = "___eager-key-value-version-converter", useRawData = true) // References org.infinispan.server.hotrod.KeyValueVersionConverterFactory public class HotRodSessionFactory<C, V, L> extends CompositeSessionFactory<C, V, L> implements Registrar<Consumer<ImmutableSession>> { private final RemoteCache<SessionCreationMetaDataKey, SessionCreationMetaDataEntry<L>> creationMetaDataCache; private final RemoteCache<SessionAccessMetaDataKey, SessionAccessMetaData> accessMetaDataCache; private final ImmutableSessionMetaDataFactory<CompositeSessionMetaDataEntry<L>> metaDataFactory; private final ImmutableSessionAttributesFactory<V> attributesFactory; private final Remover<String> attributesRemover; private final Collection<Consumer<ImmutableSession>> listeners = new CopyOnWriteArraySet<>(); private final ExecutorService executor = Executors.newCachedThreadPool(new DefaultThreadFactory(this.getClass())); private final boolean nearCacheEnabled; /** * Constructs a new session factory * @param config * @param metaDataFactory * @param attributesFactory * @param localContextFactory */ public HotRodSessionFactory(HotRodConfiguration config, SessionMetaDataFactory<CompositeSessionMetaDataEntry<L>> metaDataFactory, SessionAttributesFactory<C, V> attributesFactory, LocalContextFactory<L> localContextFactory) { super(metaDataFactory, attributesFactory, localContextFactory); this.metaDataFactory = metaDataFactory; this.attributesFactory = attributesFactory; this.attributesRemover = attributesFactory; this.creationMetaDataCache = config.getCache(); this.accessMetaDataCache= config.getCache(); this.creationMetaDataCache.addClientListener(this, null, new Object[] { Boolean.TRUE }); this.nearCacheEnabled = this.creationMetaDataCache.getRemoteCacheContainer().getConfiguration().remoteCaches().get(this.creationMetaDataCache.getName()).nearCacheMode().enabled(); } @Override public void close() { this.creationMetaDataCache.removeClientListener(this); WildFlySecurityManager.doUnchecked(this.executor, DefaultExecutorService.SHUTDOWN_ACTION); try { this.executor.awaitTermination(this.creationMetaDataCache.getRemoteCacheContainer().getConfiguration().transactionTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @ClientCacheEntryExpired public void expired(ClientCacheEntryCustomEvent<byte[]> event) { RemoteCache<SessionCreationMetaDataKey, SessionCreationMetaDataEntry<L>> creationMetaDataCache = this.creationMetaDataCache; RemoteCache<SessionAccessMetaDataKey, SessionAccessMetaData> accessMetaDataCache = this.accessMetaDataCache; ImmutableSessionMetaDataFactory<CompositeSessionMetaDataEntry<L>> metaDataFactory = this.metaDataFactory; ImmutableSessionAttributesFactory<V> attributesFactory = this.attributesFactory; Remover<String> attributesRemover = this.attributesRemover; Collection<Consumer<ImmutableSession>> listeners = this.listeners; boolean nearCacheEnabled = this.nearCacheEnabled; Runnable task = new Runnable() { @Override public void run() { ByteBuffer buffer = ByteBuffer.wrap(event.getEventData()); byte[] key = new byte[UnsignedNumeric.readUnsignedInt(buffer)]; buffer.get(key); byte[] value = buffer.remaining() > 0 ? new byte[UnsignedNumeric.readUnsignedInt(buffer)] : null; if (value != null) { buffer.get(value); } Marshaller marshaller = creationMetaDataCache.getRemoteCacheContainer().getConfiguration().marshaller(); String id = null; try { SessionCreationMetaDataKey creationKey = (SessionCreationMetaDataKey) marshaller.objectFromByteBuffer(key); id = creationKey.getId(); @SuppressWarnings("unchecked") SessionCreationMetaDataEntry<L> creationEntry = (value != null) ? (SessionCreationMetaDataEntry<L>) marshaller.objectFromByteBuffer(value) : new SessionCreationMetaDataEntry<>(new SimpleSessionCreationMetaData(Instant.EPOCH)); // Ensure entry is removed from near cache if (nearCacheEnabled) { creationMetaDataCache.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).remove(creationKey); } SessionAccessMetaData accessMetaData = accessMetaDataCache.withFlags(Flag.FORCE_RETURN_VALUE).remove(new SessionAccessMetaDataKey(id)); if (accessMetaData != null) { V attributesValue = attributesFactory.findValue(id); if (attributesValue != null) { ImmutableSessionMetaData metaData = metaDataFactory.createImmutableSessionMetaData(id, new CompositeSessionMetaDataEntry<>(creationEntry, accessMetaData)); ImmutableSessionAttributes attributes = attributesFactory.createImmutableSessionAttributes(id, attributesValue); ImmutableSession session = HotRodSessionFactory.this.createImmutableSession(id, metaData, attributes); Logger.ROOT_LOGGER.tracef("Session %s has expired.", id); for (Consumer<ImmutableSession> listener : listeners) { listener.accept(session); } attributesRemover.remove(id); } } } catch (IOException | ClassNotFoundException e) { Logger.ROOT_LOGGER.failedToExpireSession(e, id); } } }; this.executor.submit(task); } @Override public Registration register(Consumer<ImmutableSession> listener) { this.listeners.add(listener); return () -> this.listeners.remove(listener); } }
9,419
55.746988
246
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/HotRodSessionManagerConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session; import java.time.Duration; import java.util.function.Consumer; import org.wildfly.clustering.Registrar; import org.wildfly.clustering.ee.hotrod.HotRodConfiguration; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.SessionManagerConfiguration; /** * Configuration for an {@link HotRodSessionManager}. * @param <C> the ServletContext specification type * @author Paul Ferraro */ public interface HotRodSessionManagerConfiguration<C> extends SessionManagerConfiguration<C>, HotRodConfiguration { Registrar<Consumer<ImmutableSession>> getExpirationListenerRegistrar(); Duration getStopTimeout(); }
1,736
41.365854
115
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/HotRodSessionMetaDataFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session; import java.time.Duration; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Function; import org.infinispan.client.hotrod.RemoteCache; import org.wildfly.clustering.ee.Key; import org.wildfly.clustering.ee.Mutator; import org.wildfly.clustering.ee.MutatorFactory; import org.wildfly.clustering.ee.cache.CacheProperties; import org.wildfly.clustering.ee.hotrod.HotRodConfiguration; import org.wildfly.clustering.ee.hotrod.RemoteCacheMutatorFactory; import org.wildfly.clustering.web.cache.session.CompositeSessionMetaData; import org.wildfly.clustering.web.cache.session.CompositeSessionMetaDataEntry; import org.wildfly.clustering.web.cache.session.InvalidatableSessionMetaData; import org.wildfly.clustering.web.cache.session.MutableSessionAccessMetaData; import org.wildfly.clustering.web.cache.session.MutableSessionCreationMetaData; import org.wildfly.clustering.web.cache.session.SessionAccessMetaData; import org.wildfly.clustering.web.cache.session.SessionCreationMetaData; import org.wildfly.clustering.web.cache.session.SessionCreationMetaDataEntry; import org.wildfly.clustering.web.cache.session.SessionMetaDataFactory; import org.wildfly.clustering.web.cache.session.SimpleSessionAccessMetaData; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; /** * @author Paul Ferraro */ public class HotRodSessionMetaDataFactory<L> implements SessionMetaDataFactory<CompositeSessionMetaDataEntry<L>> { private final RemoteCache<Key<String>, Object> cache; private final RemoteCache<SessionCreationMetaDataKey, SessionCreationMetaDataEntry<L>> creationMetaDataCache; private final MutatorFactory<SessionCreationMetaDataKey, SessionCreationMetaDataEntry<L>> creationMetaDataMutatorFactory; private final RemoteCache<SessionAccessMetaDataKey, SessionAccessMetaData> accessMetaDataCache; private final MutatorFactory<SessionAccessMetaDataKey, SessionAccessMetaData> accessMetaDataMutatorFactory; private final CacheProperties properties; public HotRodSessionMetaDataFactory(HotRodConfiguration configuration) { this.cache = configuration.getCache(); this.creationMetaDataCache = configuration.getCache(); this.creationMetaDataMutatorFactory = new RemoteCacheMutatorFactory<>(this.creationMetaDataCache, new Function<SessionCreationMetaDataEntry<L>, Duration>() { @Override public Duration apply(SessionCreationMetaDataEntry<L> entry) { return entry.getMetaData().getTimeout(); } }); this.accessMetaDataCache = configuration.getCache(); this.accessMetaDataMutatorFactory = new RemoteCacheMutatorFactory<>(this.accessMetaDataCache); this.properties = configuration.getCacheProperties(); } @Override public CompositeSessionMetaDataEntry<L> createValue(String id, SessionCreationMetaData creationMetaData) { SessionCreationMetaDataEntry<L> creationMetaDataEntry = new SessionCreationMetaDataEntry<>(creationMetaData); SessionAccessMetaData accessMetaData = new SimpleSessionAccessMetaData(); this.creationMetaDataMutatorFactory.createMutator(new SessionCreationMetaDataKey(id), creationMetaDataEntry).mutate(); this.accessMetaDataMutatorFactory.createMutator(new SessionAccessMetaDataKey(id), accessMetaData).mutate(); return new CompositeSessionMetaDataEntry<>(creationMetaDataEntry, accessMetaData); } @Override public CompositeSessionMetaDataEntry<L> findValue(String id) { SessionCreationMetaDataKey creationMetaDataKey = new SessionCreationMetaDataKey(id); SessionAccessMetaDataKey accessMetaDataKey = new SessionAccessMetaDataKey(id); Set<Key<String>> keys = new HashSet<>(3); keys.add(creationMetaDataKey); keys.add(accessMetaDataKey); // Use bulk read Map<Key<String>, Object> entries = this.cache.getAll(keys); @SuppressWarnings("unchecked") SessionCreationMetaDataEntry<L> creationMetaDataEntry = (SessionCreationMetaDataEntry<L>) entries.get(creationMetaDataKey); SessionAccessMetaData accessMetaData = (SessionAccessMetaData) entries.get(accessMetaDataKey); if ((creationMetaDataEntry != null) && (accessMetaData != null)) { return new CompositeSessionMetaDataEntry<>(creationMetaDataEntry, accessMetaData); } return null; } @Override public InvalidatableSessionMetaData createSessionMetaData(String id, CompositeSessionMetaDataEntry<L> entry) { boolean newSession = entry.getCreationMetaData().isNew(); SessionCreationMetaDataKey creationMetaDataKey = new SessionCreationMetaDataKey(id); Mutator creationMutator = this.properties.isTransactional() && newSession ? Mutator.PASSIVE : this.creationMetaDataMutatorFactory.createMutator(creationMetaDataKey, new SessionCreationMetaDataEntry<>(entry.getCreationMetaData(), entry.getLocalContext())); SessionCreationMetaData creationMetaData = new MutableSessionCreationMetaData(entry.getCreationMetaData(), creationMutator); SessionAccessMetaDataKey accessMetaDataKey = new SessionAccessMetaDataKey(id); Mutator accessMutator = this.properties.isTransactional() && newSession ? Mutator.PASSIVE : this.accessMetaDataMutatorFactory.createMutator(accessMetaDataKey, entry.getAccessMetaData()); SessionAccessMetaData accessMetaData = new MutableSessionAccessMetaData(entry.getAccessMetaData(), accessMutator); return new CompositeSessionMetaData(creationMetaData, accessMetaData); } @Override public ImmutableSessionMetaData createImmutableSessionMetaData(String id, CompositeSessionMetaDataEntry<L> entry) { return new CompositeSessionMetaData(entry.getCreationMetaData(), entry.getAccessMetaData()); } @Override public boolean remove(String id) { this.accessMetaDataCache.remove(new SessionAccessMetaDataKey(id)); this.creationMetaDataCache.remove(new SessionCreationMetaDataKey(id)); return true; } }
7,157
54.061538
263
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/SessionAccessMetaDataKey.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session; import org.wildfly.clustering.ee.hotrod.RemoteCacheKey; /** * Cache key for the session access meta data entry. * @author Paul Ferraro */ public class SessionAccessMetaDataKey extends RemoteCacheKey<String> { public SessionAccessMetaDataKey(String id) { super(id); } }
1,366
35.945946
70
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/HotRodSessionManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session; import java.time.Duration; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Supplier; import org.wildfly.clustering.Registrar; import org.wildfly.clustering.Registration; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ee.cache.tx.TransactionBatch; import org.wildfly.clustering.ee.expiration.Expiration; import org.wildfly.clustering.web.cache.session.SessionCreationMetaData; import org.wildfly.clustering.web.cache.session.SessionFactory; import org.wildfly.clustering.web.cache.session.SimpleImmutableSession; import org.wildfly.clustering.web.cache.session.SimpleSessionCreationMetaData; import org.wildfly.clustering.web.cache.session.ValidSession; import org.wildfly.clustering.web.hotrod.logging.Logger; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.Session; import org.wildfly.clustering.web.session.SessionManager; import org.wildfly.common.function.Functions; /** * Generic HotRod-based session manager implementation - independent of cache mapping strategy. * @param <SC> the ServletContext specification type * @param <MV> the meta-data value type * @param <AV> the attributes value type * @param <LC> the local context type * @author Paul Ferraro */ public class HotRodSessionManager<SC, MV, AV, LC> implements SessionManager<LC, TransactionBatch> { private final Registrar<Consumer<ImmutableSession>> expirationListenerRegistrar; private final Consumer<ImmutableSession> expirationListener; private final SessionFactory<SC, MV, AV, LC> factory; private final Supplier<String> identifierFactory; private final SC context; private final Batcher<TransactionBatch> batcher; private final Duration stopTimeout; private final Consumer<ImmutableSession> closeTask = Functions.discardingConsumer(); private final Expiration expiration; private volatile Registration expirationListenerRegistration; public HotRodSessionManager(SessionFactory<SC, MV, AV, LC> factory, HotRodSessionManagerConfiguration<SC> configuration) { this.factory = factory; this.expirationListenerRegistrar = configuration.getExpirationListenerRegistrar(); this.expirationListener = configuration.getExpirationListener(); this.context = configuration.getServletContext(); this.identifierFactory = configuration.getIdentifierFactory(); this.batcher = configuration.getBatcher(); this.stopTimeout = configuration.getStopTimeout(); this.expiration = configuration; } @Override public void start() { this.expirationListenerRegistration = this.expirationListenerRegistrar.register(this.expirationListener); } @Override public void stop() { if (this.expirationListenerRegistration != null) { this.expirationListenerRegistration.close(); } } @Override public Duration getStopTimeout() { return this.stopTimeout; } @Override public Batcher<TransactionBatch> getBatcher() { return this.batcher; } @Override public Supplier<String> getIdentifierFactory() { return this.identifierFactory; } @Override public Session<LC> findSession(String id) { Map.Entry<MV, AV> entry = this.factory.findValue(id); if (entry == null) { Logger.ROOT_LOGGER.tracef("Session %s not found", id); return null; } ImmutableSession session = this.factory.createImmutableSession(id, entry); if (session.getMetaData().isExpired()) { Logger.ROOT_LOGGER.tracef("Session %s was found, but has expired", id); this.expirationListener.accept(session); this.factory.remove(id); return null; } return new ValidSession<>(this.factory.createSession(id, entry, this.context), this.closeTask); } @Override public Session<LC> createSession(String id) { SessionCreationMetaData creationMetaData = new SimpleSessionCreationMetaData(); creationMetaData.setTimeout(this.expiration.getTimeout()); Map.Entry<MV, AV> entry = this.factory.createValue(id, creationMetaData); if (entry == null) return null; Session<LC> session = this.factory.createSession(id, entry, this.context); return new ValidSession<>(session, this.closeTask); } @Override public ImmutableSession readSession(String id) { Map.Entry<MV, AV> entry = this.factory.findValue(id); return (entry != null) ? new SimpleImmutableSession(this.factory.createImmutableSession(id, entry)) : null; } @Override public Set<String> getActiveSessions() { return Collections.emptySet(); } @Override public Set<String> getLocalSessions() { return Collections.emptySet(); } @Override public long getActiveSessionCount() { return this.getActiveSessions().size(); } }
6,120
38.746753
126
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/HotRodSessionManagerFactoryConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session; import org.wildfly.clustering.ee.hotrod.HotRodConfiguration; import org.wildfly.clustering.web.session.SessionManagerFactoryConfiguration; /** * @param <S> the HttpSession specification type * @param <SC> the ServletContext specification type * @param <AL> the HttpSessionAttributeListener specification type * @param <LC> the local context type * @author Paul Ferraro */ public interface HotRodSessionManagerFactoryConfiguration<S, SC, AL, LC> extends SessionManagerFactoryConfiguration<S, SC, AL, LC>, HotRodConfiguration { }
1,610
43.75
153
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/SessionCreationMetaDataKey.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session; import org.wildfly.clustering.ee.hotrod.RemoteCacheKey; /** * Cache key for the session creation meta data entry. * @author Paul Ferraro */ public class SessionCreationMetaDataKey extends RemoteCacheKey<String> { public SessionCreationMetaDataKey(String id) { super(id); } }
1,372
36.108108
72
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/SessionSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; import org.wildfly.clustering.web.cache.SessionKeyMarshaller; /** * @author Paul Ferraro */ @MetaInfServices(SerializationContextInitializer.class) public class SessionSerializationContextInitializer extends AbstractSerializationContextInitializer { @Override public void registerMarshallers(SerializationContext context) { context.registerMarshaller(new SessionKeyMarshaller<>(SessionCreationMetaDataKey.class, SessionCreationMetaDataKey::new)); context.registerMarshaller(new SessionKeyMarshaller<>(SessionAccessMetaDataKey.class, SessionAccessMetaDataKey::new)); } }
1,932
43.953488
130
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/fine/FineSessionAttributesSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session.fine; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; import org.wildfly.clustering.web.cache.SessionKeyMarshaller; /** * @author Paul Ferraro */ @MetaInfServices(SerializationContextInitializer.class) public class FineSessionAttributesSerializationContextInitializer extends AbstractSerializationContextInitializer { @Override public void registerMarshallers(SerializationContext context) { context.registerMarshaller(new SessionKeyMarshaller<>(SessionAttributeNamesKey.class, SessionAttributeNamesKey::new)); context.registerMarshaller(new SessionAttributeKeyMarshaller()); } }
1,893
43.046512
126
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/fine/SessionAttributeKey.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session.fine; import java.util.Map; import java.util.Objects; import java.util.UUID; import org.wildfly.clustering.ee.hotrod.RemoteCacheKey; /** * Cache key for session attributes. * @author Paul Ferraro */ public class SessionAttributeKey extends RemoteCacheKey<String> implements org.wildfly.clustering.web.cache.session.fine.SessionAttributeKey { private final UUID attributeId; public SessionAttributeKey(Map.Entry<String, UUID> entry) { this(entry.getKey(), entry.getValue()); } public SessionAttributeKey(String id, UUID attributeId) { super(id); this.attributeId = attributeId; } @Override public UUID getAttributeId() { return this.attributeId; } @Override public int hashCode() { return Objects.hash(this.getClass(), this.getId(), this.attributeId); } @Override public boolean equals(Object object) { return super.equals(object) && (object instanceof SessionAttributeKey) && this.attributeId.equals(((SessionAttributeKey) object).attributeId); } @Override public String toString() { return String.format("%s(%s[%s])", SessionAttributeKey.class.getSimpleName(), this.getId(), this.attributeId); } }
2,309
33.477612
150
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/fine/FineSessionAttributesFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session.fine; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import org.infinispan.client.hotrod.RemoteCache; import org.wildfly.clustering.ee.Immutability; import org.wildfly.clustering.ee.MutatorFactory; import org.wildfly.clustering.ee.cache.CacheProperties; import org.wildfly.clustering.ee.hotrod.RemoteCacheMap; import org.wildfly.clustering.ee.hotrod.RemoteCacheMutatorFactory; import org.wildfly.clustering.marshalling.spi.Marshaller; import org.wildfly.clustering.web.cache.session.CompositeImmutableSession; import org.wildfly.clustering.web.cache.session.ImmutableSessionAttributeActivationNotifier; import org.wildfly.clustering.web.cache.session.SessionAttributeActivationNotifier; import org.wildfly.clustering.web.cache.session.SessionAttributes; import org.wildfly.clustering.web.cache.session.SessionAttributesFactory; import org.wildfly.clustering.web.cache.session.fine.FineImmutableSessionAttributes; import org.wildfly.clustering.web.cache.session.fine.FineSessionAttributes; import org.wildfly.clustering.web.hotrod.logging.Logger; import org.wildfly.clustering.web.hotrod.session.HotRodSessionAttributesFactoryConfiguration; import org.wildfly.clustering.web.session.HttpSessionActivationListenerProvider; import org.wildfly.clustering.web.session.ImmutableSessionAttributes; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; /** * {@link SessionAttributesFactory} for fine granularity sessions. * A given session's attributes are mapped to N+1 co-located cache entries, where N is the number of session attributes. * A separate cache entry stores the activate attribute names for the session. * @author Paul Ferraro */ public class FineSessionAttributesFactory<S, C, L, V> implements SessionAttributesFactory<C, AtomicReference<Map<String, UUID>>> { private final RemoteCache<SessionAttributeNamesKey, Map<String, UUID>> namesCache; private final RemoteCache<SessionAttributeKey, V> attributeCache; private final Marshaller<Object, V> marshaller; private final Immutability immutability; private final CacheProperties properties; private final MutatorFactory<SessionAttributeKey, V> mutatorFactory; private final HttpSessionActivationListenerProvider<S, C, L> provider; public FineSessionAttributesFactory(HotRodSessionAttributesFactoryConfiguration<S, C, L, Object, V> configuration) { this.namesCache = configuration.getCache(); this.attributeCache = configuration.getCache(); this.marshaller = configuration.getMarshaller(); this.immutability = configuration.getImmutability(); this.properties = configuration.getCacheProperties(); this.mutatorFactory = new RemoteCacheMutatorFactory<>(this.attributeCache); this.provider = configuration.getHttpSessionActivationListenerProvider(); } @Override public AtomicReference<Map<String, UUID>> createValue(String id, Void context) { return new AtomicReference<>(Collections.emptyMap()); } @Override public AtomicReference<Map<String, UUID>> findValue(String id) { return this.getValue(id, true); } @Override public AtomicReference<Map<String, UUID>> tryValue(String id) { return this.getValue(id, false); } private AtomicReference<Map<String, UUID>> getValue(String id, boolean purgeIfInvalid) { Map<String, UUID> names = this.namesCache.get(new SessionAttributeNamesKey(id)); if (names != null) { // Validate all attributes Map<SessionAttributeKey, String> attributes = new HashMap<>(); for (Map.Entry<String, UUID> entry : names.entrySet()) { attributes.put(new SessionAttributeKey(id, entry.getValue()), entry.getKey()); } Map<SessionAttributeKey, V> entries = this.attributeCache.getAll(attributes.keySet()); for (Map.Entry<SessionAttributeKey, String> attribute : attributes.entrySet()) { V value = entries.get(attribute.getKey()); if (value != null) { try { this.marshaller.read(value); continue; } catch (IOException e) { Logger.ROOT_LOGGER.failedToActivateSessionAttribute(e, id, attribute.getValue()); } } else { Logger.ROOT_LOGGER.missingSessionAttributeCacheEntry(id, attribute.getValue()); } if (purgeIfInvalid) { this.purge(id); } return null; } return new AtomicReference<>(names); } return new AtomicReference<>(Collections.emptyMap()); } @Override public boolean remove(String id) { SessionAttributeNamesKey key = new SessionAttributeNamesKey(id); Map<String, UUID> names = this.namesCache.get(key); if (names != null) { for (UUID attributeId : names.values()) { this.attributeCache.remove(new SessionAttributeKey(id, attributeId)); } this.namesCache.remove(key); } return true; } @Override public SessionAttributes createSessionAttributes(String id, AtomicReference<Map<String, UUID>> names, ImmutableSessionMetaData metaData, C context) { SessionAttributeActivationNotifier notifier = new ImmutableSessionAttributeActivationNotifier<>(this.provider, new CompositeImmutableSession(id, metaData, this.createImmutableSessionAttributes(id, names)), context); return new FineSessionAttributes<>(new SessionAttributeNamesKey(id), names, this.namesCache, getKeyFactory(id), new RemoteCacheMap<>(this.attributeCache), this.marshaller, this.mutatorFactory, this.immutability, this.properties, notifier); } @Override public ImmutableSessionAttributes createImmutableSessionAttributes(String id, AtomicReference<Map<String, UUID>> names) { return new FineImmutableSessionAttributes<>(names, getKeyFactory(id), this.attributeCache, this.marshaller); } private static Function<UUID, SessionAttributeKey> getKeyFactory(String id) { return new Function<>() { @Override public SessionAttributeKey apply(UUID attributeId) { return new SessionAttributeKey(id, attributeId); } }; } }
7,640
47.360759
247
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/fine/SessionAttributeNamesKey.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session.fine; import org.wildfly.clustering.ee.hotrod.RemoteCacheKey; /** * Cache key for session attribute names. * @author Paul Ferraro */ public class SessionAttributeNamesKey extends RemoteCacheKey<String> { public SessionAttributeNamesKey(String id) { super(id); } }
1,359
36.777778
70
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/fine/SessionAttributeKeyMarshaller.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session.fine; import java.io.IOException; import org.infinispan.protostream.descriptors.WireType; import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller; import org.wildfly.clustering.marshalling.protostream.ProtoStreamReader; import org.wildfly.clustering.marshalling.protostream.ProtoStreamWriter; import org.wildfly.clustering.marshalling.protostream.util.UUIDBuilder; import org.wildfly.clustering.marshalling.protostream.util.UUIDMarshaller; import org.wildfly.clustering.web.cache.SessionIdentifierMarshaller; /** * @author Paul Ferraro */ public class SessionAttributeKeyMarshaller implements ProtoStreamMarshaller<SessionAttributeKey> { private static final int SESSION_IDENTIFIER_INDEX = 1; private static final int ATTRIBUTE_IDENTIFIER_INDEX = 2; @Override public SessionAttributeKey readFrom(ProtoStreamReader reader) throws IOException { String sessionId = null; UUIDBuilder attributeId = UUIDMarshaller.INSTANCE.getBuilder(); while (!reader.isAtEnd()) { int tag = reader.readTag(); int index = WireType.getTagFieldNumber(tag); if (index == SESSION_IDENTIFIER_INDEX) { sessionId = SessionIdentifierMarshaller.INSTANCE.readFrom(reader); } else if (index >= ATTRIBUTE_IDENTIFIER_INDEX && index < ATTRIBUTE_IDENTIFIER_INDEX + UUIDMarshaller.INSTANCE.getFields()) { attributeId = UUIDMarshaller.INSTANCE.readField(reader, index - ATTRIBUTE_IDENTIFIER_INDEX, attributeId); } else { reader.skipField(tag); } } return new SessionAttributeKey(sessionId, attributeId.build()); } @Override public void writeTo(ProtoStreamWriter writer, SessionAttributeKey key) throws IOException { writer.writeTag(SESSION_IDENTIFIER_INDEX, SessionIdentifierMarshaller.INSTANCE.getWireType()); SessionIdentifierMarshaller.INSTANCE.writeTo(writer, key.getId()); UUIDMarshaller.INSTANCE.writeFields(writer, ATTRIBUTE_IDENTIFIER_INDEX, key.getAttributeId()); } @Override public Class<? extends SessionAttributeKey> getJavaClass() { return SessionAttributeKey.class; } }
3,283
44.611111
137
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/coarse/CoarseSessionAttributesFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session.coarse; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.infinispan.client.hotrod.RemoteCache; import org.wildfly.clustering.ee.Immutability; import org.wildfly.clustering.ee.Mutator; import org.wildfly.clustering.ee.MutatorFactory; import org.wildfly.clustering.ee.cache.CacheProperties; import org.wildfly.clustering.ee.hotrod.RemoteCacheMutatorFactory; import org.wildfly.clustering.marshalling.spi.Marshaller; import org.wildfly.clustering.web.cache.session.CompositeImmutableSession; import org.wildfly.clustering.web.cache.session.ImmutableSessionActivationNotifier; import org.wildfly.clustering.web.cache.session.SessionActivationNotifier; import org.wildfly.clustering.web.cache.session.SessionAttributes; import org.wildfly.clustering.web.cache.session.SessionAttributesFactory; import org.wildfly.clustering.web.cache.session.coarse.CoarseImmutableSessionAttributes; import org.wildfly.clustering.web.cache.session.coarse.CoarseSessionAttributes; import org.wildfly.clustering.web.hotrod.logging.Logger; import org.wildfly.clustering.web.hotrod.session.HotRodSessionAttributesFactoryConfiguration; import org.wildfly.clustering.web.session.HttpSessionActivationListenerProvider; import org.wildfly.clustering.web.session.ImmutableSessionAttributes; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; /** * @author Paul Ferraro */ public class CoarseSessionAttributesFactory<S, C, L, V> implements SessionAttributesFactory<C, Map<String, Object>> { private final RemoteCache<SessionAttributesKey, V> cache; private final Marshaller<Map<String, Object>, V> marshaller; private final Immutability immutability; private final CacheProperties properties; private final MutatorFactory<SessionAttributesKey, V> mutatorFactory; private final HttpSessionActivationListenerProvider<S, C, L> provider; public CoarseSessionAttributesFactory(HotRodSessionAttributesFactoryConfiguration<S, C, L, Map<String, Object>, V> configuration) { this.cache = configuration.getCache(); this.marshaller = configuration.getMarshaller(); this.immutability = configuration.getImmutability(); this.properties = configuration.getCacheProperties(); this.mutatorFactory = new RemoteCacheMutatorFactory<>(this.cache); this.provider = configuration.getHttpSessionActivationListenerProvider(); } @Override public Map<String, Object> createValue(String id, Void context) { Map<String, Object> attributes = new ConcurrentHashMap<>(); try { V value = this.marshaller.write(attributes); this.cache.put(new SessionAttributesKey(id), value); return attributes; } catch (IOException e) { throw new IllegalStateException(e); } } @Override public Map<String, Object> findValue(String id) { V value = this.cache.get(new SessionAttributesKey(id)); if (value != null) { try { return this.marshaller.read(value); } catch (IOException e) { Logger.ROOT_LOGGER.failedToActivateSession(e, id.toString()); this.remove(id); } } return null; } @Override public SessionAttributes createSessionAttributes(String id, Map<String, Object> attributes, ImmutableSessionMetaData metaData, C context) { try { Mutator mutator = this.mutatorFactory.createMutator(new SessionAttributesKey(id), this.marshaller.write(attributes)); SessionActivationNotifier notifier = this.properties.isPersistent() ? new ImmutableSessionActivationNotifier<>(this.provider, new CompositeImmutableSession(id, metaData, this.createImmutableSessionAttributes(id, attributes)), context) : null; return new CoarseSessionAttributes(attributes, mutator, this.marshaller, this.immutability, this.properties, notifier); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public ImmutableSessionAttributes createImmutableSessionAttributes(String id, Map<String, Object> values) { return new CoarseImmutableSessionAttributes(values); } @Override public boolean remove(String id) { this.cache.remove(new SessionAttributesKey(id)); return true; } }
5,481
45.457627
254
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/coarse/SessionAttributesKey.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session.coarse; import org.wildfly.clustering.ee.hotrod.RemoteCacheKey; /** * Cache key for session attributes. * @author Paul Ferraro */ public class SessionAttributesKey extends RemoteCacheKey<String> { public SessionAttributesKey(String id) { super(id); } }
1,348
36.472222
70
java
null
wildfly-main/clustering/web/hotrod/src/main/java/org/wildfly/clustering/web/hotrod/session/coarse/CoarseSessionAttributeSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.hotrod.session.coarse; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; import org.wildfly.clustering.web.cache.SessionKeyMarshaller; /** * @author Paul Ferraro */ @MetaInfServices(SerializationContextInitializer.class) public class CoarseSessionAttributeSerializationContextInitializer extends AbstractSerializationContextInitializer { @Override public void registerMarshallers(SerializationContext context) { context.registerMarshaller(new SessionKeyMarshaller<>(SessionAttributesKey.class, SessionAttributesKey::new)); } }
1,815
42.238095
118
java
null
wildfly-main/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/IdentifierFactoryAdapterTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.function.Supplier; import org.junit.Test; import io.undertow.server.session.SessionIdGenerator; /** * Unit test for {@link IdentifierFactoryAdapter} * * @author Paul Ferraro */ public class IdentifierFactoryAdapterTestCase { private final SessionIdGenerator generator = mock(SessionIdGenerator.class); private final Supplier<String> factory = new IdentifierFactoryAdapter(this.generator); @Test public void test() { String expected = "expected"; when(this.generator.createSessionId()).thenReturn(expected); String result = this.factory.get(); assertSame(expected, result); } }
1,849
33.90566
90
java
null
wildfly-main/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/elytron/CachedIdentityMarshallingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.elytron; import java.io.IOException; import java.security.Principal; import jakarta.servlet.http.HttpServletRequest; import org.junit.Assert; import org.junit.Test; import org.wildfly.clustering.marshalling.Tester; import org.wildfly.clustering.marshalling.jboss.JBossMarshallingTesterFactory; import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; import org.wildfly.security.auth.principal.NamePrincipal; import org.wildfly.security.cache.CachedIdentity; /** * @author Paul Ferraro */ public class CachedIdentityMarshallingTestCase { @Test public void testProtoStream() throws IOException { test(ProtoStreamTesterFactory.INSTANCE.createTester()); } @Test public void testJBoss() throws IOException { test(JBossMarshallingTesterFactory.INSTANCE.createTester()); } private static void test(Tester<CachedIdentity> tester) throws IOException { Principal principal = new NamePrincipal("name"); tester.test(new CachedIdentity(HttpServletRequest.BASIC_AUTH, false, principal), CachedIdentityMarshallingTestCase::assertEquals); tester.test(new CachedIdentity(HttpServletRequest.CLIENT_CERT_AUTH, false, principal), CachedIdentityMarshallingTestCase::assertEquals); tester.test(new CachedIdentity(HttpServletRequest.DIGEST_AUTH, false, principal), CachedIdentityMarshallingTestCase::assertEquals); tester.test(new CachedIdentity(HttpServletRequest.FORM_AUTH, false, principal), CachedIdentityMarshallingTestCase::assertEquals); tester.test(new CachedIdentity("Programmatic", true, principal), CachedIdentityMarshallingTestCase::assertEquals); } static void assertEquals(CachedIdentity auth1, CachedIdentity auth2) { Assert.assertEquals(auth1.getMechanismName(), auth2.getMechanismName()); Assert.assertEquals(auth1.getName(), auth2.getName()); Assert.assertEquals(auth1.isProgrammatic(), auth2.isProgrammatic()); } }
3,041
43.735294
144
java
null
wildfly-main/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/elytron/IdentityContainerMarshallerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.elytron; import java.io.IOException; import java.security.Principal; import jakarta.servlet.http.HttpServletRequest; import org.junit.Assert; import org.junit.Test; import org.wildfly.clustering.marshalling.Tester; import org.wildfly.clustering.marshalling.jboss.JBossMarshallingTesterFactory; import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; import org.wildfly.elytron.web.undertow.server.servlet.ServletSecurityContextImpl.IdentityContainer; import org.wildfly.security.auth.principal.NamePrincipal; import org.wildfly.security.cache.CachedIdentity; /** * @author Paul Ferraro */ public class IdentityContainerMarshallerTestCase { @Test public void testProtoStream() throws IOException { test(ProtoStreamTesterFactory.INSTANCE.createTester()); } @Test public void testJBoss() throws IOException { test(JBossMarshallingTesterFactory.INSTANCE.createTester()); } private static void test(Tester<IdentityContainer> tester) throws IOException { Principal principal = new NamePrincipal("name"); tester.test(new IdentityContainer(new CachedIdentity(HttpServletRequest.BASIC_AUTH, false, principal), "foo"), IdentityContainerMarshallerTestCase::assertEquals); tester.test(new IdentityContainer(new CachedIdentity(HttpServletRequest.BASIC_AUTH, false, principal), null), IdentityContainerMarshallerTestCase::assertEquals); } static void assertEquals(IdentityContainer container1, IdentityContainer container2) { CachedIdentityMarshallingTestCase.assertEquals(container1.getSecurityIdentity(), container2.getSecurityIdentity()); Assert.assertEquals(container1.getAuthType(), container2.getAuthType()); } }
2,803
42.138462
170
java
null
wildfly-main/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/session/UndertowHttpSessionActivationListenerProviderTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.function.Consumer; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpSession; import jakarta.servlet.http.HttpSessionActivationListener; import jakarta.servlet.http.HttpSessionEvent; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.wildfly.clustering.web.session.HttpSessionActivationListenerProvider; /** * Unit test for {@link HttpSessionActivationListenerProvider}. * @author Paul Ferraro */ public class UndertowHttpSessionActivationListenerProviderTestCase { private HttpSessionActivationListenerProvider<HttpSession, ServletContext, HttpSessionActivationListener> provider = UndertowSpecificationProvider.INSTANCE; @Test public void prePassivateNotifier() { HttpSessionActivationListener listener = mock(HttpSessionActivationListener.class); ArgumentCaptor<HttpSessionEvent> capturedEvent = ArgumentCaptor.forClass(HttpSessionEvent.class); doNothing().when(listener).sessionWillPassivate(capturedEvent.capture()); Consumer<HttpSession> notifier = this.provider.prePassivateNotifier(listener); HttpSession session = mock(HttpSession.class); notifier.accept(session); assertSame(session, capturedEvent.getValue().getSession()); } @Test public void postActivateNotifier() { HttpSessionActivationListener listener = mock(HttpSessionActivationListener.class); ArgumentCaptor<HttpSessionEvent> capturedEvent = ArgumentCaptor.forClass(HttpSessionEvent.class); doNothing().when(listener).sessionDidActivate(capturedEvent.capture()); Consumer<HttpSession> notifier = this.provider.postActivateNotifier(listener); HttpSession session = mock(HttpSession.class); notifier.accept(session); assertSame(session, capturedEvent.getValue().getSession()); } @SuppressWarnings("unchecked") @Test public void createListener() { Consumer<HttpSession> prePassivate = mock(Consumer.class); Consumer<HttpSession> postActivate = mock(Consumer.class); HttpSessionActivationListener listener = this.provider.createListener(prePassivate, postActivate); HttpSession session = mock(HttpSession.class); HttpSessionEvent event = new HttpSessionEvent(session); listener.sessionWillPassivate(event); verify(prePassivate).accept(session); verifyNoInteractions(postActivate); reset(prePassivate, postActivate); listener.sessionDidActivate(event); verifyNoInteractions(prePassivate); verify(postActivate).accept(session); } }
3,781
35.718447
160
java
null
wildfly-main/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/session/DistributableInactiveSessionStatisticsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.time.Duration; import java.time.Instant; import org.junit.Test; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; /** * Unit test for {@link DistributableInactiveSessionStatistics}. * * @author Paul Ferraro */ public class DistributableInactiveSessionStatisticsTestCase { private final RecordableInactiveSessionStatistics statistics = new DistributableInactiveSessionStatistics(); @Test public void test() { ImmutableSessionMetaData metaData = mock(ImmutableSessionMetaData.class); Instant now = Instant.now(); Instant created = now.minus(Duration.ofMinutes(20L)); when(metaData.isExpired()).thenReturn(false); when(metaData.getCreationTime()).thenReturn(created); this.statistics.record(metaData); assertEquals(0L, this.statistics.getExpiredSessionCount()); assertEquals(20L, this.statistics.getMaxSessionLifetime().toMinutes()); assertEquals(20L, this.statistics.getMeanSessionLifetime().toMinutes()); now = Instant.now(); created = now.minus(Duration.ofMinutes(10L)); when(metaData.isExpired()).thenReturn(true); when(metaData.getCreationTime()).thenReturn(created); this.statistics.record(metaData); assertEquals(1L, this.statistics.getExpiredSessionCount()); assertEquals(20L, this.statistics.getMaxSessionLifetime().toMinutes()); assertEquals(15L, this.statistics.getMeanSessionLifetime().toMinutes()); this.statistics.reset(); assertEquals(0L, this.statistics.getExpiredSessionCount()); assertEquals(0L, this.statistics.getMaxSessionLifetime().toMinutes()); assertEquals(0L, this.statistics.getMeanSessionLifetime().toMinutes()); } }
2,975
37.649351
112
java
null
wildfly-main/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/session/DistributableSessionTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Supplier; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSessionActivationListener; import io.undertow.UndertowOptions; import io.undertow.connector.ByteBufferPool; import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; import io.undertow.security.idm.Account; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.protocol.http.HttpServerConnection; import io.undertow.server.session.SessionConfig; import io.undertow.server.session.SessionListener; import io.undertow.server.session.SessionListener.SessionDestroyedReason; import io.undertow.server.session.SessionListeners; import io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler; import io.undertow.util.Protocols; import org.junit.Assert; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.BatchContext; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ee.Recordable; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; import org.wildfly.clustering.web.session.Session; import org.wildfly.clustering.web.session.SessionAttributes; import org.wildfly.clustering.web.session.SessionManager; import org.wildfly.clustering.web.session.SessionMetaData; import org.xnio.OptionMap; import org.xnio.StreamConnection; import org.xnio.channels.Configurable; import org.xnio.conduits.ConduitStreamSinkChannel; import org.xnio.conduits.ConduitStreamSourceChannel; import org.xnio.conduits.StreamSinkConduit; import org.xnio.conduits.StreamSourceConduit; /** * Unit test for {@link DistributableSession}. * * @author Paul Ferraro */ public class DistributableSessionTestCase { private final SessionMetaData metaData = mock(SessionMetaData.class); private final UndertowSessionManager manager = mock(UndertowSessionManager.class); private final SessionConfig config = mock(SessionConfig.class); private final Session<Map<String, Object>> session = mock(Session.class); private final Batch batch = mock(Batch.class); private final Consumer<HttpServerExchange> closeTask = mock(Consumer.class); private final RecordableSessionManagerStatistics statistics = mock(RecordableSessionManagerStatistics.class); @Test public void getId() { String id = "id"; when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); when(this.session.getId()).thenReturn(id); String result = session.getId(); assertSame(id, result); } @Test public void requestDone() { Instant creationTime = Instant.now(); // New session when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(true); when(this.metaData.getCreationTime()).thenReturn(creationTime); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); HttpServerExchange exchange = new HttpServerExchange(null); ArgumentCaptor<Instant> capturedLastAccessStartTime = ArgumentCaptor.forClass(Instant.class); ArgumentCaptor<Instant> capturedLastAccessEndTime = ArgumentCaptor.forClass(Instant.class); when(this.session.isValid()).thenReturn(true); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); doNothing().when(this.metaData).setLastAccess(capturedLastAccessStartTime.capture(), capturedLastAccessEndTime.capture()); session.requestDone(exchange); Instant lastAccessStartTime = capturedLastAccessStartTime.getValue(); Instant lastAccessEndTime = capturedLastAccessEndTime.getValue(); Assert.assertSame(creationTime, lastAccessStartTime); Assert.assertNotSame(creationTime, lastAccessEndTime); Assert.assertFalse(lastAccessStartTime.isAfter(lastAccessEndTime)); verify(this.session).close(); verify(this.batch).close(); verify(context).close(); verify(this.closeTask).accept(exchange); reset(this.batch, this.session, this.metaData, context, this.closeTask); capturedLastAccessStartTime = ArgumentCaptor.forClass(Instant.class); capturedLastAccessEndTime = ArgumentCaptor.forClass(Instant.class); // Existing session when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); when(this.session.isValid()).thenReturn(true); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); doNothing().when(this.metaData).setLastAccess(capturedLastAccessStartTime.capture(), capturedLastAccessEndTime.capture()); session.requestDone(exchange); lastAccessStartTime = capturedLastAccessStartTime.getValue(); lastAccessEndTime = capturedLastAccessEndTime.getValue(); Assert.assertNotSame(lastAccessStartTime, lastAccessEndTime); Assert.assertFalse(lastAccessStartTime.isAfter(lastAccessEndTime)); verify(this.metaData).setLastAccess(any(Instant.class), any(Instant.class)); verify(this.session).close(); verify(this.batch).close(); verify(context).close(); verify(this.closeTask).accept(exchange); reset(this.batch, this.session, this.metaData, context, this.closeTask); // Invalid session, closed batch when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(true); session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); when(this.session.isValid()).thenReturn(false); when(this.batch.getState()).thenReturn(Batch.State.CLOSED); session.requestDone(exchange); verify(this.session).close(); verify(this.batch).close(); verify(context).close(); verify(this.closeTask).accept(exchange); reset(this.batch, this.session, this.metaData, context, this.closeTask); when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(true); session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); // Invalid session, active batch when(this.session.isValid()).thenReturn(false); when(this.batch.getState()).thenReturn(Batch.State.ACTIVE); session.requestDone(exchange); verify(this.session).close(); verify(this.batch).close(); verify(context).close(); verify(this.closeTask).accept(exchange); } @Test public void getCreationTime() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionMetaData metaData = mock(SessionMetaData.class); Instant now = Instant.now(); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.session.getMetaData()).thenReturn(metaData); when(metaData.getCreationTime()).thenReturn(now); long result = session.getCreationTime(); assertEquals(now.toEpochMilli(), result); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); doThrow(IllegalStateException.class).when(this.session).getMetaData(); assertThrows(IllegalStateException.class, () -> session.getCreationTime()); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(null); } @Test public void getLastAccessedTime() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionMetaData metaData = mock(SessionMetaData.class); Instant now = Instant.now(); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.session.getMetaData()).thenReturn(metaData); when(metaData.getLastAccessStartTime()).thenReturn(now); long result = session.getLastAccessedTime(); assertEquals(now.toEpochMilli(), result); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); doThrow(IllegalStateException.class).when(this.session).getMetaData(); assertThrows(IllegalStateException.class, () -> session.getLastAccessedTime()); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(null); } @Test public void getMaxInactiveInterval() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionMetaData metaData = mock(SessionMetaData.class); long expected = 3600L; when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.session.getMetaData()).thenReturn(metaData); when(metaData.getTimeout()).thenReturn(Duration.ofSeconds(expected)); long result = session.getMaxInactiveInterval(); assertEquals(expected, result); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); doThrow(IllegalStateException.class).when(this.session).getMetaData(); assertThrows(IllegalStateException.class, () -> session.getMaxInactiveInterval()); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(null); } @Test public void setMaxInactiveInterval() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); int interval = 3600; SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionMetaData metaData = mock(SessionMetaData.class); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.session.getMetaData()).thenReturn(metaData); session.setMaxInactiveInterval(interval); verify(metaData).setMaxInactiveInterval(Duration.ofSeconds(interval)); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); doThrow(IllegalStateException.class).when(this.session).getMetaData(); assertThrows(IllegalStateException.class, () -> session.setMaxInactiveInterval(interval)); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(null); } @Test public void getAttributeNames() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionAttributes attributes = mock(SessionAttributes.class); Set<String> expected = Collections.singleton("name"); when(this.session.getAttributes()).thenReturn(attributes); when(attributes.getAttributeNames()).thenReturn(expected); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); Object result = session.getAttributeNames(); assertSame(expected, result); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); doThrow(IllegalStateException.class).when(this.session).getAttributes(); assertThrows(IllegalStateException.class, () -> session.getAttributeNames()); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(null); } @Test public void getAttribute() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); String name = "name"; SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionAttributes attributes = mock(SessionAttributes.class); Object expected = new Object(); when(this.session.getAttributes()).thenReturn(attributes); when(attributes.getAttribute(name)).thenReturn(expected); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); Object result = session.getAttribute(name); assertSame(expected, result); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); doThrow(IllegalStateException.class).when(this.session).getAttributes(); assertThrows(IllegalStateException.class, () -> session.getAttribute(name)); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(null); } @Test public void getAuthenticatedSessionAttribute() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); String name = CachedAuthenticatedSessionHandler.class.getName() + ".AuthenticatedSession"; SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionAttributes attributes = mock(SessionAttributes.class); Account account = mock(Account.class); AuthenticatedSession auth = new AuthenticatedSession(account, HttpServletRequest.FORM_AUTH); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.session.getAttributes()).thenReturn(attributes); when(attributes.getAttribute(name)).thenReturn(auth); AuthenticatedSession result = (AuthenticatedSession) session.getAttribute(name); assertSame(account, result.getAccount()); assertSame(HttpServletRequest.FORM_AUTH, result.getMechanism()); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); AuthenticatedSession expected = new AuthenticatedSession(account, HttpServletRequest.BASIC_AUTH); Map<String, Object> localContext = Collections.singletonMap(name, expected); when(attributes.getAttribute(name)).thenReturn(null); when(this.session.getLocalContext()).thenReturn(localContext); result = (AuthenticatedSession) session.getAttribute(name); assertSame(expected, result); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); doThrow(IllegalStateException.class).when(this.session).getAttributes(); assertThrows(IllegalStateException.class, () -> session.getAttribute(name)); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(null); } @Test public void getWebSocketChannelsSessionAttribute() { this.getLocalContextSessionAttribute(DistributableSession.WEB_SOCKET_CHANNELS_ATTRIBUTE); } private void getLocalContextSessionAttribute(String name) { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); SessionAttributes attributes = mock(SessionAttributes.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); Object expected = new Object(); Map<String, Object> localContext = Collections.singletonMap(name, expected); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.session.getLocalContext()).thenReturn(localContext); Object result = session.getAttribute(name); assertSame(expected, result); verify(attributes, never()).getAttribute(name); verify(context).close(); } @Test public void setAttribute() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); String name = "name"; Integer value = 1; SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionAttributes attributes = mock(SessionAttributes.class); SessionListener listener = mock(SessionListener.class); SessionListeners listeners = new SessionListeners(); listeners.addSessionListener(listener); Object expected = new Object(); when(this.session.getAttributes()).thenReturn(attributes); when(attributes.setAttribute(name, value)).thenReturn(expected); when(this.manager.getSessionListeners()).thenReturn(listeners); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); Object result = session.setAttribute(name, value); assertSame(expected, result); verify(listener, never()).attributeAdded(session, name, value); verify(listener).attributeUpdated(session, name, value, expected); verify(listener, never()).attributeRemoved(same(session), same(name), any()); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); doThrow(IllegalStateException.class).when(this.session).getAttributes(); assertThrows(IllegalStateException.class, () -> session.setAttribute(name, value)); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(null); } @Test public void setNewAttribute() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); String name = "name"; Integer value = 1; SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionAttributes attributes = mock(SessionAttributes.class); SessionListener listener = mock(SessionListener.class); SessionListeners listeners = new SessionListeners(); listeners.addSessionListener(listener); Object expected = null; when(this.session.getAttributes()).thenReturn(attributes); when(attributes.setAttribute(name, value)).thenReturn(expected); when(this.manager.getSessionListeners()).thenReturn(listeners); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); Object result = session.setAttribute(name, value); assertSame(expected, result); verify(listener).attributeAdded(session, name, value); verify(listener, never()).attributeUpdated(same(session), same(name), same(value), any()); verify(listener, never()).attributeRemoved(same(session), same(name), any()); verify(context).close(); } @Test public void setNullAttribute() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); String name = "name"; Object value = null; SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionAttributes attributes = mock(SessionAttributes.class); SessionListener listener = mock(SessionListener.class); SessionListeners listeners = new SessionListeners(); listeners.addSessionListener(listener); Object expected = new Object(); when(this.session.getAttributes()).thenReturn(attributes); when(attributes.removeAttribute(name)).thenReturn(expected); when(this.manager.getSessionListeners()).thenReturn(listeners); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); Object result = session.setAttribute(name, value); assertSame(expected, result); verify(listener, never()).attributeAdded(session, name, value); verify(listener, never()).attributeUpdated(same(session), same(name), same(value), any()); verify(listener).attributeRemoved(session, name, expected); verify(context).close(); } @Test public void setSameAttribute() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); String name = "name"; Integer value = 1; SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionAttributes attributes = mock(SessionAttributes.class); SessionListener listener = mock(SessionListener.class); SessionListeners listeners = new SessionListeners(); listeners.addSessionListener(listener); Object expected = value; when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.session.getAttributes()).thenReturn(attributes); when(attributes.setAttribute(name, value)).thenReturn(expected); when(this.manager.getSessionListeners()).thenReturn(listeners); Object result = session.setAttribute(name, value); assertSame(expected, result); verify(listener, never()).attributeAdded(session, name, value); verify(listener, never()).attributeUpdated(same(session), same(name), same(value), any()); verify(listener, never()).attributeRemoved(same(session), same(name), any()); verify(context).close(); } @Test public void setAuthenticatedSessionAttribute() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); String name = CachedAuthenticatedSessionHandler.class.getName() + ".AuthenticatedSession"; Account account = mock(Account.class); AuthenticatedSession auth = new AuthenticatedSession(account, HttpServletRequest.FORM_AUTH); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionAttributes attributes = mock(SessionAttributes.class); Account oldAccount = mock(Account.class); AuthenticatedSession oldAuth = new AuthenticatedSession(oldAccount, HttpServletRequest.FORM_AUTH); ArgumentCaptor<AuthenticatedSession> capturedAuth = ArgumentCaptor.forClass(AuthenticatedSession.class); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.session.getAttributes()).thenReturn(attributes); when(attributes.setAttribute(same(name), capturedAuth.capture())).thenReturn(oldAuth); AuthenticatedSession result = (AuthenticatedSession) session.setAttribute(name, auth); assertSame(auth.getAccount(), capturedAuth.getValue().getAccount()); assertSame(auth.getMechanism(), capturedAuth.getValue().getMechanism()); assertSame(oldAccount, result.getAccount()); assertSame(HttpServletRequest.FORM_AUTH, result.getMechanism()); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context, attributes); capturedAuth = ArgumentCaptor.forClass(AuthenticatedSession.class); when(attributes.setAttribute(same(name), capturedAuth.capture())).thenReturn(null); result = (AuthenticatedSession) session.setAttribute(name, auth); assertSame(auth.getAccount(), capturedAuth.getValue().getAccount()); assertSame(auth.getMechanism(), capturedAuth.getValue().getMechanism()); assertNull(result); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context, attributes); auth = new AuthenticatedSession(account, HttpServletRequest.BASIC_AUTH); AuthenticatedSession oldSession = new AuthenticatedSession(oldAccount, HttpServletRequest.BASIC_AUTH); Map<String, Object> localContext = new HashMap<>(); localContext.put(name, oldSession); when(this.session.getLocalContext()).thenReturn(localContext); result = (AuthenticatedSession) session.setAttribute(name, auth); assertSame(auth, localContext.get(name)); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); doThrow(IllegalStateException.class).when(this.session).getAttributes(); assertThrows(IllegalStateException.class, () -> session.setAttribute(name, oldAuth)); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(null); } @Test public void setWebSocketChannelsSessionAttribute() { this.setLocalContextSessionAttribute(DistributableSession.WEB_SOCKET_CHANNELS_ATTRIBUTE); } private void setLocalContextSessionAttribute(String name) { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); Object newValue = new Object(); Object oldValue = new Object(); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); SessionAttributes attributes = mock(SessionAttributes.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); Map<String, Object> localContext = new HashMap<>(); localContext.put(name, oldValue); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.session.getLocalContext()).thenReturn(localContext); Object result = session.setAttribute(name, newValue); assertSame(oldValue, result); assertSame(newValue, localContext.get(name)); verify(attributes, never()).setAttribute(name, newValue); verify(context).close(); } @Test public void removeAttribute() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); String name = "name"; SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionAttributes attributes = mock(SessionAttributes.class); SessionListener listener = mock(SessionListener.class); SessionListeners listeners = new SessionListeners(); listeners.addSessionListener(listener); Object expected = new Object(); when(this.session.getAttributes()).thenReturn(attributes); when(attributes.removeAttribute(name)).thenReturn(expected); when(this.manager.getSessionListeners()).thenReturn(listeners); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); Object result = session.removeAttribute(name); assertSame(expected, result); verify(listener).attributeRemoved(session, name, expected); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); doThrow(IllegalStateException.class).when(this.session).getAttributes(); assertThrows(IllegalStateException.class, () -> session.removeAttribute(name)); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(null); } @Test public void removeNonExistingAttribute() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); String name = "name"; SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionAttributes attributes = mock(SessionAttributes.class); SessionListener listener = mock(SessionListener.class); SessionListeners listeners = new SessionListeners(); listeners.addSessionListener(listener); when(this.session.getAttributes()).thenReturn(attributes); when(attributes.removeAttribute(name)).thenReturn(null); when(this.manager.getSessionListeners()).thenReturn(listeners); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); Object result = session.removeAttribute(name); assertNull(result); verify(listener, never()).attributeRemoved(same(session), same(name), any()); verify(context).close(); } @Test public void removeAuthenticatedSessionAttribute() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); String name = CachedAuthenticatedSessionHandler.class.getName() + ".AuthenticatedSession"; SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionAttributes attributes = mock(SessionAttributes.class); Account oldAccount = mock(Account.class); AuthenticatedSession oldAuth = new AuthenticatedSession(oldAccount, HttpServletRequest.FORM_AUTH); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.session.getAttributes()).thenReturn(attributes); when(attributes.removeAttribute(same(name))).thenReturn(oldAuth); AuthenticatedSession result = (AuthenticatedSession) session.removeAttribute(name); assertSame(oldAccount, result.getAccount()); assertSame(HttpServletRequest.FORM_AUTH, result.getMechanism()); verify(context).close(); reset(context, attributes); Map<String, Object> localContext = new HashMap<>(); AuthenticatedSession oldSession = new AuthenticatedSession(oldAccount, HttpServletRequest.BASIC_AUTH); localContext.put(name, oldSession); when(attributes.removeAttribute(same(name))).thenReturn(null); when(this.session.getLocalContext()).thenReturn(localContext); result = (AuthenticatedSession) session.removeAttribute(name); assertSame(result, oldSession); assertNull(localContext.get(name)); verify(context).close(); reset(context, attributes); result = (AuthenticatedSession) session.removeAttribute(name); assertNull(result); verify(context).close(); verify(this.session, never()).close(); verify(this.closeTask, never()).accept(null); reset(context); doThrow(IllegalStateException.class).when(this.session).getAttributes(); assertThrows(IllegalStateException.class, () -> session.removeAttribute(name)); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(null); } @Test public void removeWebSocketChannelsSessionAttribute() { this.removeLocalContextSessionAttribute(DistributableSession.WEB_SOCKET_CHANNELS_ATTRIBUTE); } private void removeLocalContextSessionAttribute(String name) { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); Object oldValue = new Object(); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); SessionAttributes attributes = mock(SessionAttributes.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); Map<String, Object> localContext = new HashMap<>(); localContext.put(name, oldValue); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.session.getLocalContext()).thenReturn(localContext); Object result = session.removeAttribute(name); assertSame(oldValue, result); assertNull(localContext.get(name)); verify(attributes, never()).removeAttribute(name); verify(context).close(); } @Test public void invalidate() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); HttpServerExchange exchange = new HttpServerExchange(null); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); SessionListener listener = mock(SessionListener.class); SessionAttributes attributes = mock(SessionAttributes.class); SessionListeners listeners = new SessionListeners(); listeners.addSessionListener(listener); String sessionId = "session"; String attributeName = "attribute"; Object attributeValue = mock(HttpSessionActivationListener.class); Recordable<ImmutableSessionMetaData> recorder = mock(Recordable.class); when(this.manager.getSessionListeners()).thenReturn(listeners); when(this.session.isValid()).thenReturn(true); when(this.session.getId()).thenReturn(sessionId); when(this.session.getMetaData()).thenReturn(this.metaData); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(this.batch.getState()).thenReturn(Batch.State.ACTIVE); when(this.session.getAttributes()).thenReturn(attributes); when(attributes.getAttributeNames()).thenReturn(Collections.singleton("attribute")); when(attributes.getAttribute(attributeName)).thenReturn(attributeValue); when(this.statistics.getInactiveSessionRecorder()).thenReturn(recorder); session.invalidate(exchange); verify(recorder).record(this.metaData); verify(this.session).invalidate(); verify(this.config).clearSession(exchange, sessionId); verify(listener).sessionDestroyed(session, exchange, SessionDestroyedReason.INVALIDATED); verify(listener).attributeRemoved(session, attributeName, attributeValue); verify(this.batch).close(); verify(context).close(); verify(this.closeTask).accept(exchange); reset(context, this.session, this.closeTask); doThrow(IllegalStateException.class).when(this.session).invalidate(); assertThrows(IllegalStateException.class, () -> session.invalidate(exchange)); verify(context).close(); verify(this.session).close(); verify(this.closeTask).accept(exchange); } @Test public void getSessionManager() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); assertSame(this.manager, session.getSessionManager()); } @Test public void changeSessionId() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); HttpServerExchange exchange = new HttpServerExchange(null); SessionConfig config = mock(SessionConfig.class); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Supplier<String> identifierFactory = mock(Supplier.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); Session<Map<String, Object>> newSession = mock(Session.class); SessionAttributes oldAttributes = mock(SessionAttributes.class); SessionAttributes newAttributes = mock(SessionAttributes.class); SessionMetaData oldMetaData = mock(SessionMetaData.class); SessionMetaData newMetaData = mock(SessionMetaData.class); Map<String, Object> oldContext = new HashMap<>(); oldContext.put("foo", "bar"); Map<String, Object> newContext = new HashMap<>(); SessionListener listener = mock(SessionListener.class); SessionListeners listeners = new SessionListeners(); listeners.addSessionListener(listener); String oldSessionId = "old"; String newSessionId = "new"; String name = "name"; Object value = new Object(); Instant now = Instant.now(); Duration interval = Duration.ofSeconds(10L); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(manager.getIdentifierFactory()).thenReturn(identifierFactory); when(identifierFactory.get()).thenReturn(newSessionId); when(manager.createSession(newSessionId)).thenReturn(newSession); when(this.session.getAttributes()).thenReturn(oldAttributes); when(this.session.getMetaData()).thenReturn(oldMetaData); when(newSession.getAttributes()).thenReturn(newAttributes); when(newSession.getMetaData()).thenReturn(newMetaData); when(oldAttributes.getAttributeNames()).thenReturn(Collections.singleton(name)); when(oldAttributes.getAttribute(name)).thenReturn(value); when(newAttributes.setAttribute(name, value)).thenReturn(null); when(oldMetaData.getLastAccessStartTime()).thenReturn(now); when(oldMetaData.getLastAccessTime()).thenReturn(now); when(oldMetaData.getTimeout()).thenReturn(interval); when(this.session.getId()).thenReturn(oldSessionId); when(newSession.getId()).thenReturn(newSessionId); when(this.session.getLocalContext()).thenReturn(oldContext); when(newSession.getLocalContext()).thenReturn(newContext); when(this.manager.getSessionListeners()).thenReturn(listeners); String result = session.changeSessionId(exchange, config); assertSame(newSessionId, result); verify(newMetaData).setLastAccess(now, now); verify(newMetaData).setMaxInactiveInterval(interval); verify(config).setSessionId(exchange, newSessionId); assertEquals(oldContext, newContext); verify(this.session).invalidate(); verify(newSession, never()).invalidate(); verify(listener).sessionIdChanged(session, oldSessionId); verify(context).close(); } public void changeSessionIdResponseCommitted() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); when(this.session.isValid()).thenReturn(true); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); // Ugh - all this, just to get HttpServerExchange.isResponseStarted() to return true Configurable configurable = mock(Configurable.class); StreamSourceConduit sourceConduit = mock(StreamSourceConduit.class); ConduitStreamSourceChannel sourceChannel = new ConduitStreamSourceChannel(configurable, sourceConduit); StreamSinkConduit sinkConduit = mock(StreamSinkConduit.class); ConduitStreamSinkChannel sinkChannel = new ConduitStreamSinkChannel(configurable, sinkConduit); StreamConnection stream = mock(StreamConnection.class); when(stream.getSourceChannel()).thenReturn(sourceChannel); when(stream.getSinkChannel()).thenReturn(sinkChannel); ByteBufferPool bufferPool = mock(ByteBufferPool.class); HttpHandler handler = mock(HttpHandler.class); HttpServerConnection connection = new HttpServerConnection(stream, bufferPool, handler, OptionMap.create(UndertowOptions.ALWAYS_SET_DATE, false), 0, null); HttpServerExchange exchange = new HttpServerExchange(connection); exchange.setProtocol(Protocols.HTTP_1_1); exchange.getResponseChannel(); SessionConfig config = mock(SessionConfig.class); Assert.assertThrows(IllegalStateException.class, () -> session.changeSessionId(exchange, config)); } @Test public void changeSessionIdConcurrentInvalidate() { when(this.session.getMetaData()).thenReturn(this.metaData); when(this.metaData.isNew()).thenReturn(false); io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask, this.statistics); HttpServerExchange exchange = new HttpServerExchange(null); SessionConfig config = mock(SessionConfig.class); SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); Supplier<String> identifierFactory = mock(Supplier.class); Batcher<Batch> batcher = mock(Batcher.class); BatchContext context = mock(BatchContext.class); Session<Map<String, Object>> newSession = mock(Session.class); SessionAttributes oldAttributes = mock(SessionAttributes.class); SessionAttributes newAttributes = mock(SessionAttributes.class); SessionMetaData oldMetaData = mock(SessionMetaData.class); SessionMetaData newMetaData = mock(SessionMetaData.class); Map<String, Object> oldContext = new HashMap<>(); oldContext.put("foo", "bar"); Map<String, Object> newContext = new HashMap<>(); SessionListener listener = mock(SessionListener.class); SessionListeners listeners = new SessionListeners(); listeners.addSessionListener(listener); String oldSessionId = "old"; String newSessionId = "new"; String name = "name"; Object value = new Object(); Instant now = Instant.now(); Duration interval = Duration.ofSeconds(10L); when(this.manager.getSessionManager()).thenReturn(manager); when(manager.getBatcher()).thenReturn(batcher); when(batcher.resumeBatch(this.batch)).thenReturn(context); when(manager.getIdentifierFactory()).thenReturn(identifierFactory); when(identifierFactory.get()).thenReturn(newSessionId); when(manager.createSession(newSessionId)).thenReturn(newSession); when(this.session.getAttributes()).thenReturn(oldAttributes); when(this.session.getMetaData()).thenReturn(oldMetaData); when(newSession.getAttributes()).thenReturn(newAttributes); when(newSession.getMetaData()).thenReturn(newMetaData); when(oldAttributes.getAttributeNames()).thenReturn(Collections.singleton(name)); when(oldAttributes.getAttribute(name)).thenReturn(value); when(newAttributes.setAttribute(name, value)).thenReturn(null); when(oldMetaData.getLastAccessStartTime()).thenReturn(now); when(oldMetaData.getLastAccessTime()).thenReturn(now); when(oldMetaData.getTimeout()).thenReturn(interval); when(this.session.getId()).thenReturn(oldSessionId); when(newSession.getId()).thenReturn(newSessionId); when(this.session.getLocalContext()).thenReturn(oldContext); when(newSession.getLocalContext()).thenReturn(newContext); doThrow(IllegalStateException.class).when(this.session).invalidate(); assertThrows(IllegalStateException.class, () -> session.changeSessionId(exchange, config)); verify(context).close(); verify(listener, never()).sessionIdChanged(session, oldSessionId); verify(this.session).close(); verify(this.closeTask).accept(exchange); verify(newSession).invalidate(); } }
53,864
43.333333
164
java
null
wildfly-main/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/session/UndertowSessionExpirationListenerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.Map; import java.util.function.Consumer; import io.undertow.server.session.Session; import io.undertow.server.session.SessionListener; import io.undertow.server.session.SessionListeners; import io.undertow.servlet.api.Deployment; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ee.Recordable; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.ImmutableSessionAttributes; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; import org.wildfly.clustering.web.session.SessionManager; public class UndertowSessionExpirationListenerTestCase { @Test public void sessionExpired() { Deployment deployment = mock(Deployment.class); UndertowSessionManager manager = mock(UndertowSessionManager.class); SessionManager<Map<String, Object>, Batch> delegateManager = mock(SessionManager.class); Batcher<Batch> batcher = mock(Batcher.class); Batch batch = mock(Batch.class); SessionListener listener = mock(SessionListener.class); ImmutableSession session = mock(ImmutableSession.class); ImmutableSessionAttributes attributes = mock(ImmutableSessionAttributes.class); ImmutableSessionMetaData metaData = mock(ImmutableSessionMetaData.class); ArgumentCaptor<Session> capturedSession = ArgumentCaptor.forClass(Session.class); Recordable<ImmutableSessionMetaData> recorder = mock(Recordable.class); String expectedSessionId = "session"; SessionListeners listeners = new SessionListeners(); listeners.addSessionListener(listener); Consumer<ImmutableSession> expirationListener = new UndertowSessionExpirationListener(deployment, listeners, recorder); when(deployment.getSessionManager()).thenReturn(manager); when(manager.getSessionManager()).thenReturn(delegateManager); when(delegateManager.getBatcher()).thenReturn(batcher); when(batcher.suspendBatch()).thenReturn(batch); when(session.getId()).thenReturn(expectedSessionId); when(session.getAttributes()).thenReturn(attributes); when(attributes.getAttributeNames()).thenReturn(Collections.emptySet()); when(session.getMetaData()).thenReturn(metaData); when(metaData.getCreationTime()).thenReturn(Instant.now()); when(metaData.getLastAccessStartTime()).thenReturn(Instant.now()); when(metaData.getTimeout()).thenReturn(Duration.ZERO); expirationListener.accept(session); verify(recorder).record(metaData); verify(batcher).suspendBatch(); verify(listener).sessionDestroyed(capturedSession.capture(), isNull(), same(SessionListener.SessionDestroyedReason.TIMEOUT)); verify(batcher).resumeBatch(batch); assertSame(expectedSessionId, capturedSession.getValue().getId()); assertSame(manager, capturedSession.getValue().getSessionManager()); } }
4,492
45.802083
133
java
null
wildfly-main/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/session/UndertowHttpSessionFactoryTestCase.java
package org.wildfly.clustering.web.undertow.session; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Set; import java.util.TreeSet; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpSession; import org.junit.Test; import org.wildfly.clustering.web.session.HttpSessionFactory; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.SessionAttributes; import org.wildfly.clustering.web.session.SessionMetaData; /** * Unit test for {@link HttpSessionFactory}. * @author Paul Ferraro */ public class UndertowHttpSessionFactoryTestCase { private final HttpSessionFactory<HttpSession, ServletContext> factory = UndertowSpecificationProvider.INSTANCE; @Test public void getId() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); String expected = "session"; when(session.getId()).thenReturn(expected); String result = this.factory.createHttpSession(session, context).getId(); assertSame(expected, result); } @Test public void getCreationTime() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); SessionMetaData metaData = mock(SessionMetaData.class); Instant now = Instant.now(); when(session.getMetaData()).thenReturn(metaData); when(metaData.getCreationTime()).thenReturn(now); long result = this.factory.createHttpSession(session, context).getCreationTime(); assertEquals(now.toEpochMilli(), result); } @Test public void getLastAccessedTime() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); SessionMetaData metaData = mock(SessionMetaData.class); Instant now = Instant.now(); when(session.getMetaData()).thenReturn(metaData); when(metaData.getLastAccessStartTime()).thenReturn(now); long result = this.factory.createHttpSession(session, context).getLastAccessedTime(); assertEquals(now.toEpochMilli(), result); } @Test public void getMaxInactiveInterval() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); SessionMetaData metaData = mock(SessionMetaData.class); Duration interval = Duration.of(100L, ChronoUnit.SECONDS); when(session.getMetaData()).thenReturn(metaData); when(metaData.getTimeout()).thenReturn(interval); int result = this.factory.createHttpSession(session, context).getMaxInactiveInterval(); assertEquals(interval.getSeconds(), result); } @Test public void setMaxInactiveInterval() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); this.factory.createHttpSession(session, context).setMaxInactiveInterval(10); verifyNoInteractions(session); } @Test public void getServletContext() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); ServletContext result = this.factory.createHttpSession(session, context).getServletContext(); assertSame(context, result); } @Test public void getAttributeNames() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); SessionAttributes attributes = mock(SessionAttributes.class); Set<String> expected = new TreeSet<>(); when(session.getAttributes()).thenReturn(attributes); when(attributes.getAttributeNames()).thenReturn(expected); Enumeration<String> result = this.factory.createHttpSession(session, context).getAttributeNames(); assertEquals(new ArrayList<>(expected), Collections.list(result)); } @Test public void getAttribute() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); SessionAttributes attributes = mock(SessionAttributes.class); String name = "name"; Object expected = new Object(); when(session.getAttributes()).thenReturn(attributes); when(attributes.getAttribute(name)).thenReturn(expected); Object result = this.factory.createHttpSession(session, context).getAttribute(name); assertSame(expected, result); } @Test public void setAttribute() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); this.factory.createHttpSession(session, context).setAttribute("name", "value"); verifyNoInteractions(session); } @Test public void removeAttribute() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); this.factory.createHttpSession(session, context).removeAttribute("name"); verifyNoInteractions(session); } @Test public void invalidate() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); this.factory.createHttpSession(session, context).invalidate(); verifyNoInteractions(session); } @Test public void isNew() { ImmutableSession session = mock(ImmutableSession.class); ServletContext context = mock(ServletContext.class); SessionMetaData metaData = mock(SessionMetaData.class); when(session.getMetaData()).thenReturn(metaData); when(metaData.isNew()).thenReturn(true, false); assertTrue(this.factory.createHttpSession(session, context).isNew()); assertFalse(this.factory.createHttpSession(session, context).isNew()); } }
6,467
33.774194
115
java
null
wildfly-main/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/session/DistributableSessionManagerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.time.Duration; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import io.undertow.UndertowOptions; import io.undertow.connector.ByteBufferPool; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.protocol.http.HttpServerConnection; import io.undertow.server.session.SessionConfig; import io.undertow.server.session.SessionListener; import io.undertow.server.session.SessionListeners; import io.undertow.util.Protocols; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; import org.wildfly.clustering.web.session.Session; import org.wildfly.clustering.web.session.SessionManager; import org.wildfly.clustering.web.session.SessionMetaData; import org.wildfly.common.function.Functions; import org.xnio.OptionMap; import org.xnio.StreamConnection; import org.xnio.channels.Configurable; import org.xnio.conduits.ConduitStreamSinkChannel; import org.xnio.conduits.ConduitStreamSourceChannel; import org.xnio.conduits.StreamSinkConduit; import org.xnio.conduits.StreamSourceConduit; public class DistributableSessionManagerTestCase { private final String deploymentName = "mydeployment.war"; private final SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class); private final SessionListener listener = mock(SessionListener.class); private final SessionListeners listeners = new SessionListeners(); private final RecordableSessionManagerStatistics statistics = mock(RecordableSessionManagerStatistics.class); private DistributableSessionManager adapter; @Before public void init() { DistributableSessionManagerConfiguration config = mock(DistributableSessionManagerConfiguration.class); when(config.getDeploymentName()).thenReturn(this.deploymentName); when(config.getSessionListeners()).thenReturn(this.listeners); when(config.getSessionManager()).thenReturn(this.manager); when(config.getStatistics()).thenReturn(this.statistics); this.adapter = new DistributableSessionManager(config); this.adapter.registerSessionListener(this.listener); } @Test public void getDeploymentName() { assertSame(this.deploymentName, this.adapter.getDeploymentName()); } @Test public void start() { this.adapter.start(); verify(this.manager).start(); verify(this.statistics).reset(); } @Test public void stop() { when(this.manager.getStopTimeout()).thenReturn(Duration.ZERO); this.adapter.stop(); verify(this.manager).stop(); } @Test public void createSessionResponseCommitted() { // Ugh - all this, just to get HttpServerExchange.isResponseStarted() to return true Configurable configurable = mock(Configurable.class); StreamSourceConduit sourceConduit = mock(StreamSourceConduit.class); ConduitStreamSourceChannel sourceChannel = new ConduitStreamSourceChannel(configurable, sourceConduit); StreamSinkConduit sinkConduit = mock(StreamSinkConduit.class); ConduitStreamSinkChannel sinkChannel = new ConduitStreamSinkChannel(configurable, sinkConduit); StreamConnection stream = mock(StreamConnection.class); String id = "foo"; Supplier<String> identifierFactory = Functions.constantSupplier(id); int expectedTimeout = 10; this.adapter.setDefaultSessionTimeout(expectedTimeout); when(this.manager.getIdentifierFactory()).thenReturn(identifierFactory); when(stream.getSourceChannel()).thenReturn(sourceChannel); when(stream.getSinkChannel()).thenReturn(sinkChannel); ByteBufferPool bufferPool = mock(ByteBufferPool.class); HttpHandler handler = mock(HttpHandler.class); HttpServerConnection connection = new HttpServerConnection(stream, bufferPool, handler, OptionMap.create(UndertowOptions.ALWAYS_SET_DATE, false), 0, null); HttpServerExchange exchange = new HttpServerExchange(connection); exchange.setProtocol(Protocols.HTTP_1_1); exchange.getResponseChannel(); SessionConfig config = mock(SessionConfig.class); io.undertow.server.session.Session session = this.adapter.createSession(exchange, config); // Verify that a nonce session was created verify(this.manager, never()).createSession(id); Assert.assertEquals(id, session.getId()); Assert.assertEquals(expectedTimeout, session.getMaxInactiveInterval()); } @Test public void createSessionNoSessionId() { HttpServerExchange exchange = new HttpServerExchange(null); Supplier<String> identifierFactory = mock(Supplier.class); Batcher<Batch> batcher = mock(Batcher.class); Batch batch = mock(Batch.class); SessionConfig config = mock(SessionConfig.class); Session<Map<String, Object>> session = mock(Session.class); SessionMetaData metaData = mock(SessionMetaData.class); String sessionId = "session"; when(this.manager.getIdentifierFactory()).thenReturn(identifierFactory); when(identifierFactory.get()).thenReturn(sessionId); when(this.manager.createSession(sessionId)).thenReturn(session); when(this.manager.getBatcher()).thenReturn(batcher); when(batcher.createBatch()).thenReturn(batch); when(session.getId()).thenReturn(sessionId); when(session.getMetaData()).thenReturn(metaData); when(metaData.isNew()).thenReturn(true); io.undertow.server.session.Session sessionAdapter = this.adapter.createSession(exchange, config); assertNotNull(sessionAdapter); verify(this.listener).sessionCreated(sessionAdapter, exchange); verify(config).setSessionId(exchange, sessionId); verify(batcher).suspendBatch(); verify(this.statistics).record(metaData); String expected = "expected"; when(session.getId()).thenReturn(expected); String result = sessionAdapter.getId(); assertSame(expected, result); } @Test public void createSessionSpecifiedSessionId() { HttpServerExchange exchange = new HttpServerExchange(null); Batcher<Batch> batcher = mock(Batcher.class); Batch batch = mock(Batch.class); SessionConfig config = mock(SessionConfig.class); Session<Map<String, Object>> session = mock(Session.class); SessionMetaData metaData = mock(SessionMetaData.class); String sessionId = "session"; when(config.findSessionId(exchange)).thenReturn(sessionId); when(this.manager.createSession(sessionId)).thenReturn(session); when(this.manager.getBatcher()).thenReturn(batcher); when(batcher.createBatch()).thenReturn(batch); when(session.getId()).thenReturn(sessionId); when(session.getMetaData()).thenReturn(metaData); when(metaData.isNew()).thenReturn(true); io.undertow.server.session.Session sessionAdapter = this.adapter.createSession(exchange, config); assertNotNull(sessionAdapter); verify(this.listener).sessionCreated(sessionAdapter, exchange); verify(batcher).suspendBatch(); verify(this.statistics).record(metaData); String expected = "expected"; when(session.getId()).thenReturn(expected); String result = sessionAdapter.getId(); assertSame(expected, result); } @Test public void createSessionAlreadyExists() { HttpServerExchange exchange = new HttpServerExchange(null); Batcher<Batch> batcher = mock(Batcher.class); Batch batch = mock(Batch.class); SessionConfig config = mock(SessionConfig.class); String sessionId = "session"; when(config.findSessionId(exchange)).thenReturn(sessionId); when(this.manager.createSession(sessionId)).thenReturn(null); when(this.manager.getBatcher()).thenReturn(batcher); when(batcher.createBatch()).thenReturn(batch); IllegalStateException exception = null; try { this.adapter.createSession(exchange, config); } catch (IllegalStateException e) { exception = e; } assertNotNull(exception); verify(batch).discard(); verify(batch).close(); } @Test public void getSession() { HttpServerExchange exchange = new HttpServerExchange(null); Batcher<Batch> batcher = mock(Batcher.class); Batch batch = mock(Batch.class); SessionConfig config = mock(SessionConfig.class); Session<Map<String, Object>> session = mock(Session.class); SessionMetaData metaData = mock(SessionMetaData.class); String sessionId = "session"; when(config.findSessionId(exchange)).thenReturn(sessionId); when(this.manager.findSession(sessionId)).thenReturn(session); when(this.manager.getBatcher()).thenReturn(batcher); when(batcher.createBatch()).thenReturn(batch); when(session.getId()).thenReturn(sessionId); when(session.getMetaData()).thenReturn(metaData); when(metaData.isNew()).thenReturn(false); io.undertow.server.session.Session sessionAdapter = this.adapter.getSession(exchange, config); assertNotNull(sessionAdapter); verifyNoInteractions(this.statistics); verify(batcher).suspendBatch(); String expected = "expected"; when(session.getId()).thenReturn(expected); String result = sessionAdapter.getId(); assertSame(expected, result); } @Test public void getSessionNoSessionId() { HttpServerExchange exchange = new HttpServerExchange(null); SessionConfig config = mock(SessionConfig.class); when(config.findSessionId(exchange)).thenReturn(null); io.undertow.server.session.Session sessionAdapter = this.adapter.getSession(exchange, config); assertNull(sessionAdapter); } @Test public void getSessionInvalidCharacters() { HttpServerExchange exchange = new HttpServerExchange(null); SessionConfig config = mock(SessionConfig.class); String sessionId = "session+"; when(config.findSessionId(exchange)).thenReturn(sessionId); io.undertow.server.session.Session sessionAdapter = this.adapter.getSession(exchange, config); assertNull(sessionAdapter); sessionAdapter = this.adapter.getSession(sessionId); assertNull(sessionAdapter); verify(this.manager, never()).findSession(sessionId); } @Test public void getSessionNotExists() { HttpServerExchange exchange = new HttpServerExchange(null); Batcher<Batch> batcher = mock(Batcher.class); Batch batch = mock(Batch.class); SessionConfig config = mock(SessionConfig.class); String sessionId = "session"; when(config.findSessionId(exchange)).thenReturn(sessionId); when(this.manager.findSession(sessionId)).thenReturn(null); when(this.manager.getBatcher()).thenReturn(batcher); when(batcher.createBatch()).thenReturn(batch); io.undertow.server.session.Session sessionAdapter = this.adapter.getSession(exchange, config); assertNull(sessionAdapter); verify(batch).close(); verify(batcher, never()).suspendBatch(); } @Test public void activeSessions() { when(this.manager.getActiveSessions()).thenReturn(Collections.singleton("expected")); int result = this.adapter.getActiveSessions().size(); assertEquals(1, result); } @Test public void getTransientSessions() { Set<String> result = this.adapter.getTransientSessions(); assertTrue(result.isEmpty()); } @Test public void getActiveSessions() { String expected = "expected"; when(this.manager.getActiveSessions()).thenReturn(Collections.singleton(expected)); Set<String> result = this.adapter.getActiveSessions(); assertEquals(1, result.size()); assertSame(expected, result.iterator().next()); } @Test public void getAllSessions() { String expected = "expected"; when(this.manager.getLocalSessions()).thenReturn(Collections.singleton(expected)); Set<String> result = this.adapter.getAllSessions(); assertEquals(1, result.size()); assertSame(expected, result.iterator().next()); } @Test public void getSessionByIdentifier() { Batcher<Batch> batcher = mock(Batcher.class); Batch batch1 = mock(Batch.class); Batch batch2 = mock(Batch.class); ImmutableSession session = mock(ImmutableSession.class); ImmutableSessionMetaData metaData = mock(ImmutableSessionMetaData.class); String id = "ABC123"; when(this.manager.getBatcher()).thenReturn(batcher); when(batcher.createBatch()).thenReturn(batch1, batch2); when(this.manager.readSession(id)).thenReturn(session); when(session.getMetaData()).thenReturn(metaData); when(metaData.isNew()).thenReturn(false); io.undertow.server.session.Session result = this.adapter.getSession(id); Assert.assertSame(id, result.getId()); verify(batch1).close(); verify(batch2).close(); } @Test public void getSessionByIdentifierNotExists() { Batcher<Batch> batcher = mock(Batcher.class); Batch batch = mock(Batch.class); String id = "ABC123"; when(this.manager.getBatcher()).thenReturn(batcher); when(batcher.createBatch()).thenReturn(batch); when(this.manager.readSession(id)).thenReturn(null); io.undertow.server.session.Session result = this.adapter.getSession(id); Assert.assertNull(result); verify(batch).close(); reset(batch); } @Test public void getStatistics() { assertSame(this.statistics, this.adapter.getStatistics()); } }
15,840
36.98801
163
java
null
wildfly-main/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/routing/DistributableSessionIdentifierCodecTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.routing; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.AbstractMap.SimpleImmutableEntry; import org.jboss.as.web.session.RoutingSupport; import org.jboss.as.web.session.SessionIdentifierCodec; import org.junit.Test; import org.wildfly.clustering.web.routing.RouteLocator; /** * Unit test for {@link DistributableSessionIdentifierCodec}. * * @author Paul Ferraro */ public class DistributableSessionIdentifierCodecTestCase { private final RoutingSupport routing = mock(RoutingSupport.class); private final RouteLocator locator = mock(RouteLocator.class); private SessionIdentifierCodec codec = new DistributableSessionIdentifierCodec(this.locator, this.routing); @Test public void encode() { String sessionId = "session"; when(this.locator.locate(sessionId)).thenReturn(null); CharSequence result = this.codec.encode(sessionId); assertSame(sessionId, result); String route = "route"; String encodedSessionId = "session.route"; when(this.locator.locate(sessionId)).thenReturn(route); when(this.routing.format(sessionId, route)).thenReturn(encodedSessionId); result = this.codec.encode(sessionId); assertSame(encodedSessionId, result); } @Test public void decode() { String encodedSessionId = "session.route"; String sessionId = "session"; String route = "route"; when(this.routing.parse(encodedSessionId)).thenReturn(new SimpleImmutableEntry<>(sessionId, route)); CharSequence result = this.codec.decode(encodedSessionId); assertSame(sessionId, result); } }
2,802
34.0375
111
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/UndertowSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow; import org.infinispan.protostream.SerializationContextInitializer; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.protostream.CompositeSerializationContextInitializer; /** * @author Paul Ferraro */ @MetaInfServices(SerializationContextInitializer.class) public class UndertowSerializationContextInitializer extends CompositeSerializationContextInitializer { public UndertowSerializationContextInitializer() { super(UndertowSerializationContextInitializerProvider.class); } }
1,596
39.948718
103
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/UndertowIdentifierSerializerProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow; import java.security.PrivilegedAction; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.web.IdentifierMarshaller; import org.wildfly.clustering.web.IdentifierMarshallerProvider; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author Paul Ferraro */ @MetaInfServices(IdentifierMarshallerProvider.class) public class UndertowIdentifierSerializerProvider implements IdentifierMarshallerProvider, PrivilegedAction<String> { @Override public IdentifierMarshaller getMarshaller() { // Disable session ID marshalling optimization for custom alphabets String customAlphabet = WildFlySecurityManager.doUnchecked(this); return (customAlphabet == null) ? IdentifierMarshaller.BASE64 : IdentifierMarshaller.ISO_LATIN_1; } @Override public String run() { return System.getProperty("io.undertow.server.session.SecureRandomSessionIdGenerator.ALPHABET"); } }
2,011
39.24
117
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/IdentifierFactoryAdapter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow; import io.undertow.server.session.SessionIdGenerator; import java.util.function.Supplier; /** * Adapts a {@link SessionIdGenerator} to a {@link IdentifierFactory}. * @author Paul Ferraro */ public class IdentifierFactoryAdapter implements Supplier<String> { private final SessionIdGenerator generator; public IdentifierFactoryAdapter(SessionIdGenerator generator) { this.generator = generator; } @Override public String get() { return this.generator.createSessionId(); } }
1,590
34.355556
70
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/UndertowRequirement.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow; import org.jboss.as.clustering.controller.RequirementServiceNameFactory; import org.jboss.as.clustering.controller.ServiceNameFactory; import org.jboss.as.clustering.controller.ServiceNameFactoryProvider; import org.wildfly.clustering.service.Requirement; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.UndertowService; /** * @author Paul Ferraro */ public enum UndertowRequirement implements Requirement, ServiceNameFactoryProvider { UNDERTOW(Capabilities.CAPABILITY_UNDERTOW, UndertowService.class), ; private final String name; private final Class<?> type; private final ServiceNameFactory factory = new RequirementServiceNameFactory(this); UndertowRequirement(String name, Class<?> type) { this.name = name; this.type = type; } @Override public String getName() { return this.name; } @Override public Class<?> getType() { return this.type; } @Override public ServiceNameFactory getServiceNameFactory() { return this.factory; } }
2,157
33.806452
87
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/UndertowBinaryRequirement.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow; import org.jboss.as.clustering.controller.BinaryRequirementServiceNameFactory; import org.jboss.as.clustering.controller.BinaryServiceNameFactory; import org.jboss.as.clustering.controller.BinaryServiceNameFactoryProvider; import org.wildfly.clustering.service.BinaryRequirement; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Host; /** * @author Paul Ferraro */ public enum UndertowBinaryRequirement implements BinaryRequirement, BinaryServiceNameFactoryProvider { HOST(Capabilities.CAPABILITY_HOST, Host.class), ; private final String name; private final Class<?> type; private final BinaryServiceNameFactory factory = new BinaryRequirementServiceNameFactory(this); UndertowBinaryRequirement(String name, Class<?> type) { this.name = name; this.type = type; } @Override public String getName() { return this.name; } @Override public Class<?> getType() { return this.type; } @Override public BinaryServiceNameFactory getServiceNameFactory() { return this.factory; } }
2,193
34.387097
102
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/UndertowUnaryRequirement.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow; import org.jboss.as.clustering.controller.UnaryRequirementServiceNameFactory; import org.jboss.as.clustering.controller.UnaryServiceNameFactory; import org.jboss.as.clustering.controller.UnaryServiceNameFactoryProvider; import org.wildfly.clustering.service.UnaryRequirement; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Server; /** * @author Paul Ferraro */ public enum UndertowUnaryRequirement implements UnaryRequirement, UnaryServiceNameFactoryProvider { SERVER(Capabilities.CAPABILITY_SERVER, Server.class), ; private final String name; private final Class<?> type; private final UnaryServiceNameFactory factory = new UnaryRequirementServiceNameFactory(this); UndertowUnaryRequirement(String name, Class<?> type) { this.name = name; this.type = type; } @Override public String getName() { return this.name; } @Override public Class<?> getType() { return this.type; } @Override public UnaryServiceNameFactory getServiceNameFactory() { return this.factory; } }
2,190
34.33871
99
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/UndertowSerializationContextInitializerProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow; import org.infinispan.protostream.SerializationContextInitializer; import org.wildfly.clustering.marshalling.protostream.SerializationContextInitializerProvider; import org.wildfly.clustering.web.undertow.elytron.ElytronUndertowSerializationContextInitializer; import org.wildfly.clustering.web.undertow.elytron.SecurityCacheSerializationContextInitializer; /** * @author Paul Ferraro */ public enum UndertowSerializationContextInitializerProvider implements SerializationContextInitializerProvider { SECURITY_CACHE(new SecurityCacheSerializationContextInitializer()), ELYTRON_UNDERTOW(new ElytronUndertowSerializationContextInitializer()), ; private final SerializationContextInitializer initializer; UndertowSerializationContextInitializerProvider(SerializationContextInitializer initializer) { this.initializer = initializer; } @Override public SerializationContextInitializer getInitializer() { return this.initializer; } }
2,056
40.979592
112
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/elytron/IdentityContainerMarshaller.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.elytron; import java.io.IOException; import org.infinispan.protostream.descriptors.WireType; import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller; import org.wildfly.clustering.marshalling.protostream.ProtoStreamReader; import org.wildfly.clustering.marshalling.protostream.ProtoStreamWriter; import org.wildfly.elytron.web.undertow.server.servlet.ServletSecurityContextImpl.IdentityContainer; import org.wildfly.security.cache.CachedIdentity; /** * Marshaller for an {@link IdentityContainer}. * @author Paul Ferraro */ public class IdentityContainerMarshaller implements ProtoStreamMarshaller<IdentityContainer> { private static final int IDENTITY_INDEX = 1; private static final int TYPE_INDEX = 2; @Override public Class<? extends IdentityContainer> getJavaClass() { return IdentityContainer.class; } @Override public IdentityContainer readFrom(ProtoStreamReader reader) throws IOException { CachedIdentity identity = null; String type = null; while (!reader.isAtEnd()) { int tag = reader.readTag(); switch (WireType.getTagFieldNumber(tag)) { case IDENTITY_INDEX: identity = reader.readObject(CachedIdentity.class); break; case TYPE_INDEX: type = reader.readString(); break; default: reader.skipField(tag); } } return new IdentityContainer(identity, type); } @Override public void writeTo(ProtoStreamWriter writer, IdentityContainer container) throws IOException { CachedIdentity identity = container.getSecurityIdentity(); if (identity != null) { writer.writeObject(IDENTITY_INDEX, identity); } String type = container.getAuthType(); if (type != null) { writer.writeString(TYPE_INDEX, type); } } }
3,052
37.1625
100
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/elytron/ElytronUndertowSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.elytron; import org.infinispan.protostream.SerializationContext; import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; /** * Marshaller registration for the {@link org.wildfly.elytron.web.undertow.server.servlet} package. * @author Paul Ferraro */ public class ElytronUndertowSerializationContextInitializer extends AbstractSerializationContextInitializer { public ElytronUndertowSerializationContextInitializer() { super("org.wildfly.elytron.web.undertow.server.servlet.proto"); } @Override public void registerMarshallers(SerializationContext context) { context.registerMarshaller(new IdentityContainerMarshaller()); } }
1,775
40.302326
109
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/elytron/CachedIdentityMarshaller.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.elytron; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Set; import jakarta.servlet.http.HttpServletRequest; import org.infinispan.protostream.descriptors.WireType; import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller; import org.wildfly.clustering.marshalling.protostream.ProtoStreamReader; import org.wildfly.clustering.marshalling.protostream.ProtoStreamWriter; import org.wildfly.security.auth.principal.NamePrincipal; import org.wildfly.security.cache.CachedIdentity; /** * Marshaller for a {@link CachedIdentity}. * @author Paul Ferraro */ public class CachedIdentityMarshaller implements ProtoStreamMarshaller<CachedIdentity> { private static final int MECHANISM_INDEX = 1; private static final int NON_PROGRAMMIC_NAME_INDEX = 2; private static final int PROGRAMMATIC_NAME_INDEX = 3; private static final int ROLE_INDEX = 4; private static final String DEFAULT_MECHANISM = HttpServletRequest.FORM_AUTH; @Override public CachedIdentity readFrom(ProtoStreamReader reader) throws IOException { String mechanism = DEFAULT_MECHANISM; String name = null; boolean programmatic = false; List<String> roles = new LinkedList<>(); while (!reader.isAtEnd()) { int tag = reader.readTag(); switch (WireType.getTagFieldNumber(tag)) { case MECHANISM_INDEX: mechanism = reader.readString(); break; case PROGRAMMATIC_NAME_INDEX: programmatic = true; case NON_PROGRAMMIC_NAME_INDEX: name = reader.readString(); break; case ROLE_INDEX: roles.add(reader.readString()); break; default: reader.skipField(tag); } } return new CachedIdentity(mechanism, programmatic, new NamePrincipal(name), toSet(roles)); } private static Set<String> toSet(List<String> roles) { switch (roles.size()) { case 0: return Set.of(); case 1: return Set.of(roles.get(0)); default: return Set.of(roles.toArray(String[]::new)); } } @Override public void writeTo(ProtoStreamWriter writer, CachedIdentity identity) throws IOException { String mechanism = identity.getMechanismName(); if (!mechanism.equals(DEFAULT_MECHANISM)) { writer.writeString(MECHANISM_INDEX, mechanism); } String name = identity.getName(); if (name != null) { writer.writeString(identity.isProgrammatic() ? PROGRAMMATIC_NAME_INDEX : NON_PROGRAMMIC_NAME_INDEX, name); } for (String role : identity.getRoles()) { writer.writeString(ROLE_INDEX, role); } } @Override public Class<? extends CachedIdentity> getJavaClass() { return CachedIdentity.class; } }
4,138
36.627273
118
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/elytron/SecurityCacheSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.elytron; import org.infinispan.protostream.SerializationContext; import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; /** * Marshaller registration for the {@link org.wildfly.security.cache} package. * @author Paul Ferraro */ public class SecurityCacheSerializationContextInitializer extends AbstractSerializationContextInitializer { public SecurityCacheSerializationContextInitializer() { super("org.wildfly.security.cache.proto"); } @Override public void registerMarshallers(SerializationContext context) { context.registerMarshaller(new CachedIdentityMarshaller()); } }
1,726
39.162791
107
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SSOManagerServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.sso; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.server.Services; import org.jboss.modules.ModuleLoader; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.marshalling.protostream.ModuleClassLoaderMarshaller; import org.wildfly.clustering.marshalling.protostream.ProtoStreamByteBufferMarshaller; import org.wildfly.clustering.marshalling.protostream.SerializationContextBuilder; import org.wildfly.clustering.marshalling.spi.ByteBufferMarshaller; import org.wildfly.clustering.service.CompositeDependency; import org.wildfly.clustering.service.FunctionalService; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.clustering.web.LocalContextFactory; import org.wildfly.clustering.web.sso.SSOManager; import org.wildfly.clustering.web.sso.SSOManagerConfiguration; import org.wildfly.clustering.web.sso.SSOManagerFactory; import org.wildfly.clustering.web.undertow.IdentifierFactoryAdapter; import org.wildfly.security.manager.WildFlySecurityManager; import io.undertow.server.session.SessionIdGenerator; /** * @author Paul Ferraro */ public class SSOManagerServiceConfigurator<A, D, S, L> extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, Supplier<SSOManager<A, D, S, L, Batch>>, Consumer<SSOManager<A, D, S, L, Batch>>, SSOManagerConfiguration<L> { private final SupplierDependency<SSOManagerFactory<A, D, S, Batch>> factory; private final SupplierDependency<SessionIdGenerator> generator; private final SupplierDependency<ModuleLoader> loader = new ServiceSupplierDependency<>(Services.JBOSS_SERVICE_MODULE_LOADER); private final LocalContextFactory<L> localContextFactory; private volatile ByteBufferMarshaller marshaller; public SSOManagerServiceConfigurator(ServiceName name, SupplierDependency<SSOManagerFactory<A, D, S, Batch>> factory, SupplierDependency<SessionIdGenerator> generator, LocalContextFactory<L> localContextFactory) { super(name); this.factory = factory; this.generator = generator; this.localContextFactory = localContextFactory; } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceBuilder<?> builder = target.addService(this.getServiceName()); Consumer<SSOManager<A, D, S, L, Batch>> manager = new CompositeDependency(this.factory, this.generator, this.loader).register(builder).provides(this.getServiceName()); Service service = new FunctionalService<>(manager, Function.identity(), this, this); return builder.setInstance(service).setInitialMode(ServiceController.Mode.ON_DEMAND); } @Override public SSOManager<A, D, S, L, Batch> get() { SSOManagerFactory<A, D, S, Batch> factory = this.factory.get(); this.marshaller = new ProtoStreamByteBufferMarshaller(new SerializationContextBuilder(new ModuleClassLoaderMarshaller(this.loader.get())).load(WildFlySecurityManager.getClassLoaderPrivileged(this.getClass())).build()); SSOManager<A, D, S, L, Batch> manager = factory.createSSOManager(this); manager.start(); return manager; } @Override public void accept(SSOManager<A, D, S, L, Batch> manager) { manager.stop(); } @Override public Supplier<String> getIdentifierFactory() { return new IdentifierFactoryAdapter(this.generator.get()); } @Override public LocalContextFactory<L> getLocalContextFactory() { return this.localContextFactory; } @Override public ByteBufferMarshaller getMarshaller() { return this.marshaller; } }
5,155
45.035714
241
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/elytron/LocalSSOContext.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.sso.elytron; import org.wildfly.security.auth.server.SecurityIdentity; /** * @author Paul Ferraro */ public interface LocalSSOContext { SecurityIdentity getSecurityIdentity(); void setSecurityIdentity(SecurityIdentity identity); }
1,311
37.588235
70
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/elytron/DistributableSingleSignOnManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.sso.elytron; import java.net.URI; import java.util.Map; import java.util.Map.Entry; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.web.sso.SSO; import org.wildfly.clustering.web.sso.SSOManager; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.cache.CachedIdentity; import org.wildfly.security.http.util.sso.SingleSignOn; import org.wildfly.security.http.util.sso.SingleSignOnManager; /** * @author Paul Ferraro */ public class DistributableSingleSignOnManager implements SingleSignOnManager { private final SSOManager<CachedIdentity, String, Map.Entry<String, URI>, LocalSSOContext, Batch> manager; public DistributableSingleSignOnManager(SSOManager<CachedIdentity, String, Map.Entry<String, URI>, LocalSSOContext, Batch> manager) { this.manager = manager; } @Override public SingleSignOn create(String mechanismName, boolean programmatic, SecurityIdentity identity) { String id = this.manager.getIdentifierFactory().get(); Batcher<Batch> batcher = this.manager.getBatcher(); // Batch will be closed when SSO is closed @SuppressWarnings("resource") Batch batch = batcher.createBatch(); try { SSO<CachedIdentity, String, Entry<String, URI>, LocalSSOContext> sso = this.manager.createSSO(id, new CachedIdentity(mechanismName, programmatic, identity)); sso.getLocalContext().setSecurityIdentity(identity); return new DistributableSingleSignOn(sso, batcher, batcher.suspendBatch()); } catch (RuntimeException | Error e) { batch.discard(); batch.close(); throw e; } } @Override public SingleSignOn find(String id) { Batcher<Batch> batcher = this.manager.getBatcher(); // Batch will be closed when SSO is closed Batch batch = batcher.createBatch(); boolean close = true; try { SSO<CachedIdentity, String, Entry<String, URI>, LocalSSOContext> sso = this.manager.findSSO(id); if (sso == null) return null; close = false; return new DistributableSingleSignOn(sso, batcher, batcher.suspendBatch()); } catch (RuntimeException | Error e) { batch.discard(); throw e; } finally { if (close) { batch.close(); } } } }
3,537
39.204545
169
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/elytron/UndertowSingleSignOnManagementProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.sso.elytron; import java.util.Iterator; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.msc.service.ServiceName; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.web.container.SecurityDomainSingleSignOnManagementConfiguration; import org.wildfly.clustering.web.container.SecurityDomainSingleSignOnManagementProvider; import org.wildfly.clustering.web.service.sso.LegacySSOManagementProviderFactory; /** * {@link org.wildfly.extension.undertow.session.SessionManagementProviderFactory} for Undertow using either the {@link org.wildfly.clustering.web.sso.DistributableSSOManagementProvider} for the given security domain, the default provider, or a legacy provider. * @author Paul Ferraro */ @MetaInfServices(SecurityDomainSingleSignOnManagementProvider.class) public class UndertowSingleSignOnManagementProvider implements SecurityDomainSingleSignOnManagementProvider { private final LegacySSOManagementProviderFactory legacyProviderFactory; public UndertowSingleSignOnManagementProvider() { Iterator<LegacySSOManagementProviderFactory> factories = ServiceLoader.load(LegacySSOManagementProviderFactory.class, LegacySSOManagementProviderFactory.class.getClassLoader()).iterator(); if (!factories.hasNext()) { throw new ServiceConfigurationError(LegacySSOManagementProviderFactory.class.getName()); } this.legacyProviderFactory = factories.next(); } @Override public CapabilityServiceConfigurator getServiceConfigurator(ServiceName name, SecurityDomainSingleSignOnManagementConfiguration configuration) { return new DistributableSingleSignOnManagerServiceConfigurator(name, configuration, this.legacyProviderFactory); } }
2,908
49.155172
261
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/elytron/DistributableSingleSignOn.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.sso.elytron; import java.net.URI; import java.util.AbstractMap; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.BatchContext; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.web.sso.SSO; import org.wildfly.clustering.web.sso.Sessions; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.cache.CachedIdentity; import org.wildfly.security.http.util.sso.SingleSignOn; /** * @author Paul Ferraro */ public class DistributableSingleSignOn implements SingleSignOn { private final SSO<CachedIdentity, String, Map.Entry<String, URI>, LocalSSOContext> sso; private final Batcher<Batch> batcher; private final Batch batch; private final AtomicBoolean closed = new AtomicBoolean(false); public DistributableSingleSignOn(SSO<CachedIdentity, String, Map.Entry<String, URI>, LocalSSOContext> sso, Batcher<Batch> batcher, Batch batch) { this.sso = sso; this.batcher = batcher; this.batch = batch; } @Override public String getId() { return this.sso.getId(); } @Override public String getMechanism() { try (BatchContext context = this.batcher.resumeBatch(this.batch)) { return this.sso.getAuthentication().getMechanismName(); } } @Override public boolean isProgrammatic() { try (BatchContext context = this.batcher.resumeBatch(this.batch)) { return this.sso.getAuthentication().isProgrammatic(); } } @Override public String getName() { try (BatchContext context = this.batcher.resumeBatch(this.batch)) { return this.sso.getAuthentication().getName(); } } @Override public SecurityIdentity getIdentity() { try (BatchContext context = this.batcher.resumeBatch(this.batch)) { return this.sso.getLocalContext().getSecurityIdentity(); } } @Override public Map<String, Map.Entry<String, URI>> getParticipants() { try (BatchContext context = this.batcher.resumeBatch(this.batch)) { Sessions<String, Map.Entry<String, URI>> sessions = this.sso.getSessions(); Map<String, Map.Entry<String, URI>> participants = new HashMap<>(); for (String deployment : sessions.getDeployments()) { participants.put(deployment, sessions.getSession(deployment)); } return Collections.unmodifiableMap(participants); } } @Override public void setIdentity(SecurityIdentity identity) { try (BatchContext context = this.batcher.resumeBatch(this.batch)) { this.sso.getLocalContext().setSecurityIdentity(identity); } } @Override public boolean addParticipant(String applicationId, String sessionId, URI participant) { try (BatchContext context = this.batcher.resumeBatch(this.batch)) { return this.sso.getSessions().addSession(applicationId, new AbstractMap.SimpleImmutableEntry<>(sessionId, participant)); } } @Override public Map.Entry<String, URI> removeParticipant(String applicationId) { try (BatchContext context = this.batcher.resumeBatch(this.batch)) { return this.sso.getSessions().removeSession(applicationId); } } @Override public void invalidate() { // The batch associated with this SSO might not be valid (e.g. in the case of logout). try (BatchContext context = this.closed.compareAndSet(false, true) ? this.batcher.resumeBatch(this.batch) : null) { try (Batch batch = (context != null) ? this.batch : this.batcher.createBatch()) { this.sso.invalidate(); } } } @Override public void close() { if (this.closed.compareAndSet(false, true)) { try (BatchContext context = this.batcher.resumeBatch(this.batch)) { this.batch.close(); } } } }
5,193
35.577465
149
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/elytron/SessionIdGeneratorAdapter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.sso.elytron; import java.util.function.Supplier; import io.undertow.server.session.SessionIdGenerator; /** * Adapts a {@link String} {@link Supplier} to a {@link SessionIdGenerator}. * @author Paul Ferraro */ public class SessionIdGeneratorAdapter implements SessionIdGenerator { private final Supplier<String> generator; public SessionIdGeneratorAdapter(Supplier<String> generator) { this.generator = generator; } @Override public String createSessionId() { return this.generator.get(); } }
1,609
34
76
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/elytron/LocalSSOContextFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.sso.elytron; import org.wildfly.clustering.web.LocalContextFactory; import org.wildfly.security.auth.server.SecurityIdentity; /** * @author Paul Ferraro */ public class LocalSSOContextFactory implements LocalContextFactory<LocalSSOContext> { @Override public LocalSSOContext createLocalContext() { return new LocalSSOContext() { private volatile SecurityIdentity identity; @Override public SecurityIdentity getSecurityIdentity() { return this.identity; } @Override public void setSecurityIdentity(SecurityIdentity identity) { this.identity = identity; } }; } }
1,780
34.62
85
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/elytron/DistributableSingleSignOnManagerServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.sso.elytron; import java.net.URI; import java.util.Map; import java.util.Map.Entry; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.service.CascadeRemovalLifecycleListener; import org.wildfly.clustering.service.ChildTargetService; import org.wildfly.clustering.service.FunctionalService; import org.wildfly.clustering.service.ServiceConfigurator; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SimpleSupplierDependency; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.clustering.web.container.SecurityDomainSingleSignOnManagementConfiguration; import org.wildfly.clustering.web.service.WebDefaultProviderRequirement; import org.wildfly.clustering.web.service.WebProviderRequirement; import org.wildfly.clustering.web.service.sso.DistributableSSOManagementProvider; import org.wildfly.clustering.web.service.sso.LegacySSOManagementProviderFactory; import org.wildfly.clustering.web.sso.SSOManager; import org.wildfly.clustering.web.sso.SSOManagerFactory; import org.wildfly.clustering.web.undertow.logging.UndertowClusteringLogger; import org.wildfly.clustering.web.undertow.sso.SSOManagerServiceConfigurator; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.security.cache.CachedIdentity; import org.wildfly.security.http.util.sso.SingleSignOnManager; import io.undertow.server.session.SessionIdGenerator; /** * @author Paul Ferraro */ public class DistributableSingleSignOnManagerServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, Function<SSOManager<CachedIdentity, String, Map.Entry<String, URI>, LocalSSOContext, Batch>, SingleSignOnManager> { private final SecurityDomainSingleSignOnManagementConfiguration configuration; private final LegacySSOManagementProviderFactory legacyProviderFactory; private volatile SupplierDependency<DistributableSSOManagementProvider> provider; private volatile SupplierDependency<SSOManager<CachedIdentity, String, Map.Entry<String, URI>, LocalSSOContext, Batch>> manager; private volatile Consumer<ServiceTarget> installer; public DistributableSingleSignOnManagerServiceConfigurator(ServiceName name, SecurityDomainSingleSignOnManagementConfiguration configuration, LegacySSOManagementProviderFactory legacyProviderFactory) { super(name); this.configuration = configuration; this.legacyProviderFactory = legacyProviderFactory; } @Override public SingleSignOnManager apply(SSOManager<CachedIdentity, String, Entry<String, URI>, LocalSSOContext, Batch> manager) { return new DistributableSingleSignOnManager(manager); } @Override public ServiceConfigurator configure(OperationContext context) { String securityDomainName = this.configuration.getSecurityDomainName(); Supplier<String> generator = this.configuration.getIdentifierGenerator(); CapabilityServiceSupport support = context.getCapabilityServiceSupport(); SupplierDependency<DistributableSSOManagementProvider> provider = getProvider(context, securityDomainName); ServiceName managerServiceName = this.getServiceName().append("manager"); this.manager = new ServiceSupplierDependency<>(managerServiceName); this.provider = provider; this.installer = new Consumer<>() { @Override public void accept(ServiceTarget target) { ServiceConfigurator factoryConfigurator = provider.get().getServiceConfigurator(securityDomainName).configure(support); factoryConfigurator.build(target).install(); SupplierDependency<SSOManagerFactory<CachedIdentity, String, Map.Entry<String, URI>, Batch>> factoryDependency = new ServiceSupplierDependency<>(factoryConfigurator); SupplierDependency<SessionIdGenerator> generatorDependency = new SimpleSupplierDependency<>(new SessionIdGeneratorAdapter(generator)); new SSOManagerServiceConfigurator<>(managerServiceName, factoryDependency, generatorDependency, new LocalSSOContextFactory()).configure(support).build(target).install(); } }; return this; } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceName name = this.getServiceName(); ServiceController<?> installerController = this.provider.register(target.addService(name.append("installer"))).setInstance(new ChildTargetService(this.installer)).install(); ServiceBuilder<?> builder = target.addService(name).addListener(new CascadeRemovalLifecycleListener(installerController)); Consumer<SingleSignOnManager> manager = this.manager.register(builder).provides(name); Service service = new FunctionalService<>(manager, this, this.manager); return builder.setInstance(service); } private SupplierDependency<DistributableSSOManagementProvider> getProvider(OperationContext context, String securityDomainName) { String securityDomainCapabilityName = RuntimeCapability.buildDynamicCapabilityName(Capabilities.CAPABILITY_APPLICATION_SECURITY_DOMAIN, securityDomainName); if (context.hasOptionalCapability(WebProviderRequirement.SSO_MANAGEMENT_PROVIDER.resolve(securityDomainName), securityDomainCapabilityName, null)) { return new ServiceSupplierDependency<>(WebProviderRequirement.SSO_MANAGEMENT_PROVIDER.getServiceName(context, securityDomainName)); } else if (context.hasOptionalCapability(WebDefaultProviderRequirement.SSO_MANAGEMENT_PROVIDER.getName(), securityDomainCapabilityName, null)) { return new ServiceSupplierDependency<>(WebDefaultProviderRequirement.SSO_MANAGEMENT_PROVIDER.getServiceName(context)); } UndertowClusteringLogger.ROOT_LOGGER.legacySingleSignOnProviderInUse(securityDomainName); return new SimpleSupplierDependency<>(this.legacyProviderFactory.createSSOManagementProvider()); } }
7,710
56.977444
256
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/logging/UndertowClusteringLogger.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 2110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.logging; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; @MessageLogger(projectCode = "WFLYCLWEBUT", length = 4) public interface UndertowClusteringLogger extends BasicLogger { UndertowClusteringLogger ROOT_LOGGER = Logger.getMessageLogger(UndertowClusteringLogger.class, "org.wildfly.clustering.web.undertow"); @Message(id = 1, value = "Session %s is invalid") IllegalStateException sessionIsInvalid(String sessionId); @Message(id = 2, value = "Session %s already exists") IllegalStateException sessionAlreadyExists(String sessionId); @Message(id = 3, value = "Session manager was stopped") IllegalStateException sessionManagerStopped(); @Message(id = 4, value = "Legacy <replication-config/> overriding attached distributable session management provider for %s") @LogMessage(level = Level.WARN) void legacySessionManagementProviderOverride(String deploymentName); @Message(id = 5, value = "No distributable session management provider found for %s; using legacy provider based on <replication-config/>") @LogMessage(level = Level.WARN) void legacySessionManagementProviderInUse(String name); @Message(id = 7, value = "No routing provider found for %s; using legacy provider based on static configuration") @LogMessage(level = Level.WARN) void legacyRoutingProviderInUse(String name); @Message(id = 8, value = "No distributable single sign-on management provider found for %s; using legacy provider based on static configuration") @LogMessage(level = Level.WARN) void legacySingleSignOnProviderInUse(String name); @Message(id = 9, value = "Invalidation attempted for session %s after the response was committed (e.g. after HttpServletResponse.sendRedirect or sendError)") IllegalStateException batchIsAlreadyClosed(String sessionId); }
3,108
46.830769
161
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/DistributableInactiveSessionStatistics.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.time.Duration; import java.time.Instant; import java.util.AbstractMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; /** * Records statistics for inactive sessions. * @author Paul Ferraro */ public class DistributableInactiveSessionStatistics implements RecordableInactiveSessionStatistics { private final AtomicLong expiredSessions = new AtomicLong(); private final AtomicReference<Duration> maxLifetime = new AtomicReference<>(); // Tuple containing total lifetime of sessions, and total session count private final AtomicReference<Map.Entry<Duration, Long>> totals = new AtomicReference<>(); public DistributableInactiveSessionStatistics() { this.reset(); } @Override public void record(ImmutableSessionMetaData metaData) { Duration lifetime = Duration.between(metaData.getCreationTime(), Instant.now()); Duration currentMaxLifetime = this.maxLifetime.get(); while (lifetime.compareTo(currentMaxLifetime) > 0) { if (this.maxLifetime.compareAndSet(currentMaxLifetime, lifetime)) { break; } currentMaxLifetime = this.maxLifetime.get(); } Map.Entry<Duration, Long> currentTotals = this.totals.get(); Map.Entry<Duration, Long> sessions = createNewTotals(currentTotals, lifetime); while (!this.totals.compareAndSet(currentTotals, sessions)) { currentTotals = this.totals.get(); sessions = createNewTotals(currentTotals, lifetime); } if (metaData.isExpired()) { this.expiredSessions.incrementAndGet(); } } private static Map.Entry<Duration, Long> createNewTotals(Map.Entry<Duration, Long> totals, Duration lifetime) { Duration totalLifetime = totals.getKey(); long totalSessions = totals.getValue(); return new AbstractMap.SimpleImmutableEntry<>(totalLifetime.plus(lifetime), totalSessions + 1); } @Override public Duration getMeanSessionLifetime() { Map.Entry<Duration, Long> totals = this.totals.get(); Duration lifetime = totals.getKey(); long count = totals.getValue(); return (count > 0) ? lifetime.dividedBy(count) : Duration.ZERO; } @Override public Duration getMaxSessionLifetime() { return this.maxLifetime.get(); } @Override public long getExpiredSessionCount() { return this.expiredSessions.get(); } @Override public void reset() { this.maxLifetime.set(Duration.ZERO); this.totals.set(new AbstractMap.SimpleImmutableEntry<>(Duration.ZERO, 0L)); this.expiredSessions.set(0L); } }
3,900
36.509615
115
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/UndertowSessionManagementProviderFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.Iterator; import java.util.List; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.metadata.web.jboss.ReplicationConfig; import org.jboss.modules.Module; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.ee.immutable.SimpleImmutability; import org.wildfly.clustering.web.container.SessionManagementProvider; import org.wildfly.clustering.web.service.session.DistributableSessionManagementProvider; import org.wildfly.clustering.web.service.session.LegacySessionManagementProviderFactory; import org.wildfly.clustering.web.session.DistributableSessionManagementConfiguration; import org.wildfly.clustering.web.undertow.logging.UndertowClusteringLogger; import org.wildfly.extension.undertow.session.SessionManagementProviderFactory; /** * {@link SessionManagementProviderFactory} for Undertow using either an attached {@link DistributableSessionManagementProvider} or generated from a legacy {@link ReplicationConfig}. * @author Paul Ferraro */ @SuppressWarnings("deprecation") @MetaInfServices(SessionManagementProviderFactory.class) public class UndertowSessionManagementProviderFactory implements SessionManagementProviderFactory { private final LegacySessionManagementProviderFactory<DistributableSessionManagementConfiguration<DeploymentUnit>> legacyFactory; public UndertowSessionManagementProviderFactory() { @SuppressWarnings("rawtypes") Iterator<LegacySessionManagementProviderFactory> factories = ServiceLoader.load(LegacySessionManagementProviderFactory.class, LegacySessionManagementProviderFactory.class.getClassLoader()).iterator(); if (!factories.hasNext()) { throw new ServiceConfigurationError(LegacySessionManagementProviderFactory.class.getName()); } this.legacyFactory = factories.next(); } @Override public SessionManagementProvider createSessionManagementProvider(DeploymentUnit unit, ReplicationConfig config) { DistributableSessionManagementProvider<DistributableSessionManagementConfiguration<DeploymentUnit>> provider = unit.getAttachment(DistributableSessionManagementProvider.ATTACHMENT_KEY); // For compatibility, honor legacy <replication-config/> over an attached provider if ((config != null) || (provider == null)) { if (provider != null) { UndertowClusteringLogger.ROOT_LOGGER.legacySessionManagementProviderOverride(unit.getName()); } else { UndertowClusteringLogger.ROOT_LOGGER.legacySessionManagementProviderInUse(unit.getName()); } // Fabricate DistributableSessionManagementProvider from legacy ReplicationConfig provider = this.legacyFactory.createSessionManagerProvider(unit, config); } Module module = unit.getAttachment(Attachments.MODULE); List<String> immutableClasses = unit.getAttachmentList(DistributableSessionManagementProvider.IMMUTABILITY_ATTACHMENT_KEY); return new UndertowDistributableSessionManagementProvider<>(provider, new SimpleImmutability(module.getClassLoader(), immutableClasses)); } }
4,340
53.2625
208
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/DistributableSessionManagerStatistics.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.concurrent.atomic.AtomicLong; import org.wildfly.clustering.ee.Recordable; import org.wildfly.clustering.web.session.ActiveSessionStatistics; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; /** * @author Paul Ferraro */ public class DistributableSessionManagerStatistics implements RecordableSessionManagerStatistics { private final RecordableInactiveSessionStatistics inactiveSessionStatistics; private final ActiveSessionStatistics activeSessionStatistics; private final Integer maxActiveSessions; private volatile long startTime = System.currentTimeMillis(); private final AtomicLong createdSessionCount = new AtomicLong(); public DistributableSessionManagerStatistics(ActiveSessionStatistics activeSessionStatistics, RecordableInactiveSessionStatistics inactiveSessionStatistics, Integer maxActiveSessions) { this.activeSessionStatistics = activeSessionStatistics; this.inactiveSessionStatistics = inactiveSessionStatistics; this.maxActiveSessions = maxActiveSessions; this.reset(); } @Override public Recordable<ImmutableSessionMetaData> getInactiveSessionRecorder() { return this.inactiveSessionStatistics; } @Override public void record(ImmutableSessionMetaData metaData) { this.createdSessionCount.incrementAndGet(); } @Override public void reset() { this.createdSessionCount.set(0L); this.startTime = System.currentTimeMillis(); this.inactiveSessionStatistics.reset(); } @Override public long getCreatedSessionCount() { return this.createdSessionCount.get(); } @Override public long getMaxActiveSessions() { return (this.maxActiveSessions != null) ? this.maxActiveSessions.longValue() : -1L; } @Override public long getActiveSessionCount() { return this.activeSessionStatistics.getActiveSessionCount(); } @Override public long getExpiredSessionCount() { return this.inactiveSessionStatistics.getExpiredSessionCount(); } @Override public long getRejectedSessions() { // We never reject sessions return 0; } @Override public long getMaxSessionAliveTime() { return this.inactiveSessionStatistics.getMaxSessionLifetime().toMillis(); } @Override public long getAverageSessionAliveTime() { return this.inactiveSessionStatistics.getMeanSessionLifetime().toMillis(); } @Override public long getStartTime() { return this.startTime; } }
3,672
33.327103
189
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/LocalSessionContextFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.wildfly.clustering.web.LocalContextFactory; public enum LocalSessionContextFactory implements LocalContextFactory<Map<String, Object>> { INSTANCE; @Override public Map<String, Object> createLocalContext() { return new ConcurrentHashMap<>(); } }
1,429
37.648649
92
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/UndertowSessionExpirationListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.function.Consumer; import io.undertow.server.session.Session; import io.undertow.server.session.SessionListener; import io.undertow.server.session.SessionListeners; import io.undertow.servlet.api.Deployment; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ee.Recordable; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.ImmutableSessionAttributes; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; /** * @author Paul Ferraro */ public class UndertowSessionExpirationListener implements Consumer<ImmutableSession> { private final Deployment deployment; private final SessionListeners listeners; private final Recordable<ImmutableSessionMetaData> recorder; public UndertowSessionExpirationListener(Deployment deployment, SessionListeners listeners, Recordable<ImmutableSessionMetaData> recorder) { this.deployment = deployment; this.listeners = listeners; this.recorder = recorder; } @Override public void accept(ImmutableSession session) { if (this.recorder != null) { this.recorder.record(session.getMetaData()); } UndertowSessionManager manager = (UndertowSessionManager) this.deployment.getSessionManager(); Session undertowSession = new DistributableImmutableSession(manager, session); Batcher<Batch> batcher = manager.getSessionManager().getBatcher(); // Perform listener invocation in isolated batch context Batch batch = batcher.suspendBatch(); try { this.listeners.sessionDestroyed(undertowSession, null, SessionListener.SessionDestroyedReason.TIMEOUT); } finally { batcher.resumeBatch(batch); } // Trigger attribute listeners ImmutableSessionAttributes attributes = session.getAttributes(); for (String name : attributes.getAttributeNames()) { Object value = attributes.getAttribute(name); manager.getSessionListeners().attributeRemoved(undertowSession, name, value); } } }
3,248
41.194805
144
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/DistributableSessionManagerConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.Map; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.web.session.SessionManager; import io.undertow.server.session.SessionListeners; /** * @author Paul Ferraro */ public interface DistributableSessionManagerConfiguration { String getDeploymentName(); SessionManager<Map<String, Object>, Batch> getSessionManager(); SessionListeners getSessionListeners(); RecordableSessionManagerStatistics getStatistics(); }
1,547
36.756098
70
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/DistributableSessionManagerFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.time.Duration; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; import jakarta.servlet.ServletContext; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.BatchContext; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.web.container.SessionManagerFactoryConfiguration; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.SessionManager; import org.wildfly.clustering.web.session.SessionManagerConfiguration; import org.wildfly.clustering.web.session.SessionManagerFactory; import org.wildfly.clustering.web.undertow.IdentifierFactoryAdapter; import io.undertow.server.HttpServerExchange; import io.undertow.server.session.SessionListeners; import io.undertow.servlet.api.Deployment; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.ThreadSetupHandler; /** * Factory for creating a {@link DistributableSessionManager}. * @author Paul Ferraro */ public class DistributableSessionManagerFactory implements io.undertow.servlet.api.SessionManagerFactory { private final SessionManagerFactory<ServletContext, Map<String, Object>, Batch> factory; private final SessionManagerFactoryConfiguration config; private final SessionListeners listeners = new SessionListeners(); public DistributableSessionManagerFactory(SessionManagerFactory<ServletContext, Map<String, Object>, Batch> factory, SessionManagerFactoryConfiguration config) { this.factory = factory; this.config = config; } @Override public io.undertow.server.session.SessionManager createSessionManager(final Deployment deployment) { DeploymentInfo info = deployment.getDeploymentInfo(); boolean statisticsEnabled = info.getMetricsCollector() != null; RecordableInactiveSessionStatistics inactiveSessionStatistics = statisticsEnabled ? new DistributableInactiveSessionStatistics() : null; Supplier<String> factory = new IdentifierFactoryAdapter(info.getSessionIdGenerator()); Consumer<ImmutableSession> expirationListener = new UndertowSessionExpirationListener(deployment, this.listeners, inactiveSessionStatistics); SessionManagerConfiguration<ServletContext> configuration = new SessionManagerConfiguration<>() { @Override public ServletContext getServletContext() { return deployment.getServletContext(); } @Override public Supplier<String> getIdentifierFactory() { return factory; } @Override public Consumer<ImmutableSession> getExpirationListener() { return expirationListener; } @Override public Duration getTimeout() { return Duration.ofMinutes(this.getServletContext().getSessionTimeout()); } }; SessionManager<Map<String, Object>, Batch> manager = this.factory.createSessionManager(configuration); Batcher<Batch> batcher = manager.getBatcher(); info.addThreadSetupAction(new ThreadSetupHandler() { @Override public <T, C> Action<T, C> create(Action<T, C> action) { return new Action<>() { @Override public T call(HttpServerExchange exchange, C context) throws Exception { Batch batch = batcher.suspendBatch(); try (BatchContext ctx = batcher.resumeBatch(batch)) { return action.call(exchange, context); } } }; } }); SessionListeners listeners = this.listeners; RecordableSessionManagerStatistics statistics = (inactiveSessionStatistics != null) ? new DistributableSessionManagerStatistics(manager, inactiveSessionStatistics, this.config.getMaxActiveSessions()) : null; io.undertow.server.session.SessionManager result = new DistributableSessionManager(new DistributableSessionManagerConfiguration() { @Override public String getDeploymentName() { return info.getDeploymentName(); } @Override public SessionManager<Map<String, Object>, Batch> getSessionManager() { return manager; } @Override public SessionListeners getSessionListeners() { return listeners; } @Override public RecordableSessionManagerStatistics getStatistics() { return statistics; } }); result.setDefaultSessionTimeout((int) this.config.getDefaultSessionTimeout().getSeconds()); return result; } }
5,928
43.578947
215
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/SimpleSessionConfig.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import io.undertow.server.HttpServerExchange; import io.undertow.server.session.SessionConfig; /** * {@link SessionConfig} implementation that returns a fixed sessionId. * @author Paul Ferraro */ public class SimpleSessionConfig implements SessionConfig { private final String sessionId; public SimpleSessionConfig(String sessionId) { this.sessionId = sessionId; } @Override public void setSessionId(HttpServerExchange exchange, String sessionId) { // No-op } @Override public void clearSession(HttpServerExchange exchange, String sessionId) { // No-op } @Override public String findSessionId(HttpServerExchange exchange) { return this.sessionId; } @Override public SessionCookieSource sessionCookieSource(HttpServerExchange exchange) { return SessionCookieSource.NONE; } @Override public String rewriteUrl(String originalUrl, String sessionId) { return originalUrl; } }
2,080
31.015385
81
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/OrphanSession.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import io.undertow.server.HttpServerExchange; import io.undertow.server.session.Session; import io.undertow.server.session.SessionConfig; import io.undertow.server.session.SessionManager; /** * A session implementation for sessions created after the response is committed. * This is a workaround for those applications that trigger creation of a new session after calling {@link jakarta.servlet.http.HttpServletResponse#sendRedirect(String)}. * @author Paul Ferraro */ public class OrphanSession implements Session { private final SessionManager manager; private final String id; private final long creationTime = System.currentTimeMillis(); private final Map<String, Object> attributes = new ConcurrentHashMap<>(); private volatile int maxInactiveInterval = 0; public OrphanSession(SessionManager manager, String id) { this.manager = manager; this.id = id; } @Override public String getId() { return this.id; } @Override public void requestDone(HttpServerExchange serverExchange) { // This will never be invoked } @Override public long getCreationTime() { return this.creationTime; } @Override public long getLastAccessedTime() { return this.creationTime; } @Override public void setMaxInactiveInterval(int interval) { this.maxInactiveInterval = interval; } @Override public int getMaxInactiveInterval() { return this.maxInactiveInterval; } @Override public Object getAttribute(String name) { return this.attributes.get(name); } @Override public Set<String> getAttributeNames() { return this.attributes.keySet(); } @Override public Object setAttribute(String name, Object value) { return this.attributes.put(name, value); } @Override public Object removeAttribute(String name) { return this.attributes.remove(name); } @Override public void invalidate(HttpServerExchange exchange) { // Do nothing // This session is not referenced by the session manager and will be garbage collected at the end of the current request } @Override public SessionManager getSessionManager() { return this.manager; } @Override public String changeSessionId(HttpServerExchange exchange, SessionConfig config) { // Don't actually change the session ID - since this session is not referenced by any client // Thus session fixation is a non-issue return this.id; } }
3,762
30.099174
170
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/RecordableSessionManagerStatistics.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import io.undertow.server.session.SessionManagerStatistics; import org.wildfly.clustering.ee.Recordable; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; /** * Recordable {@link SessionManagerStatistics}. * @author Paul Ferraro */ public interface RecordableSessionManagerStatistics extends SessionManagerStatistics, Recordable<ImmutableSessionMetaData> { Recordable<ImmutableSessionMetaData> getInactiveSessionRecorder(); }
1,530
41.527778
124
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/UndertowSpecificationProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.Collections; import java.util.Enumeration; import java.util.function.Consumer; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpSession; import jakarta.servlet.http.HttpSessionActivationListener; import jakarta.servlet.http.HttpSessionEvent; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.SpecificationProvider; /** * @author Paul Ferraro */ public enum UndertowSpecificationProvider implements SpecificationProvider<HttpSession, ServletContext, HttpSessionActivationListener> { INSTANCE; @Override public HttpSession createHttpSession(ImmutableSession session, ServletContext context) { return new HttpSession() { @Override public String getId() { return session.getId(); } @Override public ServletContext getServletContext() { return context; } @Override public boolean isNew() { return session.getMetaData().isNew(); } @Override public long getCreationTime() { return session.getMetaData().getCreationTime().toEpochMilli(); } @Override public long getLastAccessedTime() { return session.getMetaData().getLastAccessStartTime().toEpochMilli(); } @Override public int getMaxInactiveInterval() { return (int) session.getMetaData().getTimeout().getSeconds(); } @Override public Enumeration<String> getAttributeNames() { return Collections.enumeration(session.getAttributes().getAttributeNames()); } @Override public Object getAttribute(String name) { return session.getAttributes().getAttribute(name); } @Override public void setAttribute(String name, Object value) { // Ignore } @Override public void removeAttribute(String name) { // Ignore } @Override public void invalidate() { // Ignore } @Override public void setMaxInactiveInterval(int interval) { // Ignore } @Override public int hashCode() { return this.getId().hashCode(); } @Override public boolean equals(Object object) { if (!(object instanceof HttpSession)) return false; // To be consistent with io.undertow.servlet.spec.HttpSessionImpl, we will assume these sessions share the same servlet context return this.getId().equals(((HttpSession) object).getId()); } @Override public String toString() { return this.getId(); } }; } @Override public Class<HttpSessionActivationListener> getHttpSessionActivationListenerClass() { return HttpSessionActivationListener.class; } @Override public Consumer<HttpSession> prePassivateNotifier(HttpSessionActivationListener listener) { return new Consumer<>() { @Override public void accept(HttpSession session) { listener.sessionWillPassivate(new HttpSessionEvent(session)); } }; } @Override public Consumer<HttpSession> postActivateNotifier(HttpSessionActivationListener listener) { return new Consumer<>() { @Override public void accept(HttpSession session) { listener.sessionDidActivate(new HttpSessionEvent(session)); } }; } @Override public HttpSessionActivationListener createListener(Consumer<HttpSession> prePassivate, Consumer<HttpSession> postActivate) { return new HttpSessionActivationListener() { @Override public void sessionWillPassivate(HttpSessionEvent event) { prePassivate.accept(event.getSession()); } @Override public void sessionDidActivate(HttpSessionEvent event) { postActivate.accept(event.getSession()); } }; } }
5,490
32.278788
143
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/WebDeploymentConfigurationAdapter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import org.wildfly.clustering.web.container.WebDeploymentConfiguration; /** * @author Paul Ferraro */ public class WebDeploymentConfigurationAdapter implements org.wildfly.clustering.web.WebDeploymentConfiguration { private final WebDeploymentConfiguration configuration; public WebDeploymentConfigurationAdapter(WebDeploymentConfiguration configuration) { this.configuration = configuration; } @Override public String getServerName() { return this.configuration.getServerName(); } @Override public String getDeploymentName() { return this.configuration.getDeploymentName(); } }
1,724
34.9375
113
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/UndertowSessionAttributeImmutability.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.Arrays; import org.wildfly.clustering.ee.Immutability; import org.wildfly.clustering.ee.immutable.SimpleImmutability; import org.wildfly.elytron.web.undertow.server.servlet.ServletSecurityContextImpl.IdentityContainer; import org.wildfly.security.cache.CachedIdentity; import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; import io.undertow.servlet.util.SavedRequest; /** * @author Paul Ferraro */ public enum UndertowSessionAttributeImmutability implements Immutability { CLASSES(new SimpleImmutability(Arrays.asList(AuthenticatedSession.class, SavedRequest.class, CachedIdentity.class, IdentityContainer.class))), ; private final Immutability immutability; UndertowSessionAttributeImmutability(Immutability immutability) { this.immutability = immutability; } @Override public boolean test(Object object) { return this.immutability.test(object); } }
2,030
38.057692
146
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/DistributableSession.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; import io.undertow.server.HttpServerExchange; import io.undertow.server.session.SessionConfig; import io.undertow.server.session.SessionListener.SessionDestroyedReason; import io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler; import java.time.Duration; import java.time.Instant; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import jakarta.servlet.http.HttpServletRequest; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.BatchContext; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.web.session.ImmutableSessionAttributes; import org.wildfly.clustering.web.session.Session; import org.wildfly.clustering.web.session.SessionManager; import org.wildfly.clustering.web.session.oob.OOBSession; import org.wildfly.clustering.web.undertow.logging.UndertowClusteringLogger; /** * Adapts a distributable {@link Session} to an Undertow {@link io.undertow.server.session.Session}. * @author Paul Ferraro */ public class DistributableSession implements io.undertow.server.session.Session { // These mechanisms can auto-reauthenticate and thus use local context (instead of replicating) private static final Set<String> AUTO_REAUTHENTICATING_MECHANISMS = Set.of(HttpServletRequest.BASIC_AUTH, HttpServletRequest.DIGEST_AUTH, HttpServletRequest.CLIENT_CERT_AUTH); static final String WEB_SOCKET_CHANNELS_ATTRIBUTE = "io.undertow.websocket.current-connections"; private static final Set<String> LOCAL_CONTEXT_ATTRIBUTES = Set.of(WEB_SOCKET_CHANNELS_ATTRIBUTE); private final UndertowSessionManager manager; private final Batch batch; private final Consumer<HttpServerExchange> closeTask; private final Instant startTime; private final RecordableSessionManagerStatistics statistics; private volatile Map.Entry<Session<Map<String, Object>>, SessionConfig> entry; // The following references are only used to create an OOB session private volatile String id = null; private volatile Map<String, Object> localContext = null; public DistributableSession(UndertowSessionManager manager, Session<Map<String, Object>> session, SessionConfig config, Batch batch, Consumer<HttpServerExchange> closeTask, RecordableSessionManagerStatistics statistics) { this.manager = manager; this.id = session.getId(); this.entry = Map.entry(session, config); this.batch = batch; this.closeTask = closeTask; this.startTime = session.getMetaData().isNew() ? session.getMetaData().getCreationTime() : Instant.now(); this.statistics = statistics; } private Map.Entry<Session<Map<String, Object>>, SessionConfig> getSessionEntry() { Map.Entry<Session<Map<String, Object>>, SessionConfig> entry = this.entry; // If entry is null, we are outside of the context of a request if (entry == null) { // Only allow a single thread to lazily create OOB session synchronized (this) { if (this.entry == null) { // N.B. If entry is null, id and localContext will already have been set this.entry = Map.entry(new OOBSession<>(this.manager.getSessionManager(), this.id, this.localContext), new SimpleSessionConfig(this.id)); } entry = this.entry; } } return entry; } @Override public io.undertow.server.session.SessionManager getSessionManager() { return this.manager; } @Override public void requestDone(HttpServerExchange exchange) { Session<Map<String, Object>> requestSession = this.getSessionEntry().getKey(); Batcher<Batch> batcher = this.manager.getSessionManager().getBatcher(); try (BatchContext context = batcher.resumeBatch(this.batch)) { // If batch was discarded, close it if (this.batch.getState() == Batch.State.DISCARDED) { this.batch.close(); } // If batch is closed, close valid session in a new batch try (Batch batch = (this.batch.getState() == Batch.State.CLOSED) && requestSession.isValid() ? batcher.createBatch() : this.batch) { // Ensure session is closed, even if invalid try (Session<Map<String, Object>> session = requestSession) { if (session.isValid()) { // According to §7.6 of the servlet specification: // The session is considered to be accessed when a request that is part of the session is first handled by the servlet container. session.getMetaData().setLastAccess(this.startTime, Instant.now()); } } } } catch (Throwable e) { // Don't propagate exceptions at the stage, since response was already committed UndertowClusteringLogger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e); } finally { // Dereference the distributed session, but retain reference to session identifier and local context // If session is accessed after this method, getSessionEntry() will lazily create an OOB session this.id = requestSession.getId(); this.localContext = requestSession.getLocalContext(); this.entry = null; this.closeTask.accept(exchange); } } @Override public String getId() { Session<Map<String, Object>> session = this.getSessionEntry().getKey(); return session.getId(); } @Override public long getCreationTime() { Session<Map<String, Object>> session = this.getSessionEntry().getKey(); try (BatchContext context = this.resumeBatch()) { return session.getMetaData().getCreationTime().toEpochMilli(); } catch (IllegalStateException e) { this.closeIfInvalid(null, session); throw e; } } @Override public long getLastAccessedTime() { Session<Map<String, Object>> session = this.getSessionEntry().getKey(); try (BatchContext context = this.resumeBatch()) { return session.getMetaData().getLastAccessStartTime().toEpochMilli(); } catch (IllegalStateException e) { this.closeIfInvalid(null, session); throw e; } } @Override public int getMaxInactiveInterval() { Session<Map<String, Object>> session = this.getSessionEntry().getKey(); try (BatchContext context = this.resumeBatch()) { return (int) session.getMetaData().getTimeout().getSeconds(); } catch (IllegalStateException e) { this.closeIfInvalid(null, session); throw e; } } @Override public void setMaxInactiveInterval(int interval) { Session<Map<String, Object>> session = this.getSessionEntry().getKey(); try (BatchContext context = this.resumeBatch()) { session.getMetaData().setMaxInactiveInterval(Duration.ofSeconds(interval)); } catch (IllegalStateException e) { this.closeIfInvalid(null, session); throw e; } } @Override public Set<String> getAttributeNames() { Session<Map<String, Object>> session = this.getSessionEntry().getKey(); try (BatchContext context = this.resumeBatch()) { return session.getAttributes().getAttributeNames(); } catch (IllegalStateException e) { this.closeIfInvalid(null, session); throw e; } } @Override public Object getAttribute(String name) { Session<Map<String, Object>> session = this.getSessionEntry().getKey(); try (BatchContext context = this.resumeBatch()) { if (CachedAuthenticatedSessionHandler.ATTRIBUTE_NAME.equals(name)) { AuthenticatedSession auth = (AuthenticatedSession) session.getAttributes().getAttribute(name); return (auth != null) ? auth : session.getLocalContext().get(name); } if (LOCAL_CONTEXT_ATTRIBUTES.contains(name)) { return session.getLocalContext().get(name); } return session.getAttributes().getAttribute(name); } catch (IllegalStateException e) { this.closeIfInvalid(null, session); throw e; } } @Override public Object setAttribute(String name, Object value) { if (value == null) { return this.removeAttribute(name); } Session<Map<String, Object>> session = this.getSessionEntry().getKey(); try (BatchContext context = this.resumeBatch()) { if (CachedAuthenticatedSessionHandler.ATTRIBUTE_NAME.equals(name)) { AuthenticatedSession auth = (AuthenticatedSession) value; return AUTO_REAUTHENTICATING_MECHANISMS.contains(auth.getMechanism()) ? session.getLocalContext().put(name, auth) : session.getAttributes().setAttribute(name, auth); } if (LOCAL_CONTEXT_ATTRIBUTES.contains(name)) { return session.getLocalContext().put(name, value); } Object old = session.getAttributes().setAttribute(name, value); if (old == null) { this.manager.getSessionListeners().attributeAdded(this, name, value); } else if (old != value) { this.manager.getSessionListeners().attributeUpdated(this, name, value, old); } return old; } catch (IllegalStateException e) { this.closeIfInvalid(null, session); throw e; } } @Override public Object removeAttribute(String name) { Session<Map<String, Object>> session = this.getSessionEntry().getKey(); try (BatchContext context = this.resumeBatch()) { if (CachedAuthenticatedSessionHandler.ATTRIBUTE_NAME.equals(name)) { AuthenticatedSession auth = (AuthenticatedSession) session.getAttributes().removeAttribute(name); return (auth != null) ? auth : session.getLocalContext().remove(name); } if (LOCAL_CONTEXT_ATTRIBUTES.contains(name)) { return session.getLocalContext().remove(name); } Object old = session.getAttributes().removeAttribute(name); if (old != null) { this.manager.getSessionListeners().attributeRemoved(this, name, old); } return old; } catch (IllegalStateException e) { this.closeIfInvalid(null, session); throw e; } } @Override public void invalidate(HttpServerExchange exchange) { Map.Entry<Session<Map<String, Object>>, SessionConfig> entry = this.getSessionEntry(); Session<Map<String, Object>> session = entry.getKey(); if (session.isValid()) { // Invoke listeners outside of the context of the batch associated with this session // Trigger attribute listeners this.manager.getSessionListeners().sessionDestroyed(this, exchange, SessionDestroyedReason.INVALIDATED); ImmutableSessionAttributes attributes = session.getAttributes(); for (String name : attributes.getAttributeNames()) { Object value = attributes.getAttribute(name); this.manager.getSessionListeners().attributeRemoved(this, name, value); } if (this.statistics != null) { this.statistics.getInactiveSessionRecorder().record(session.getMetaData()); } } try (BatchContext context = this.resumeBatch()) { session.invalidate(); if (exchange != null) { String id = session.getId(); entry.getValue().clearSession(exchange, id); } // An OOB session has no batch if (this.batch != null) { this.batch.close(); } } catch (IllegalStateException e) { // If Session.invalidate() fails due to concurrent invalidation, close this session if (!session.isValid()) { session.close(); } throw e; } finally { this.closeTask.accept(exchange); } } @Override public String changeSessionId(HttpServerExchange exchange, SessionConfig config) { Session<Map<String, Object>> oldSession = this.getSessionEntry().getKey(); SessionManager<Map<String, Object>, Batch> manager = this.manager.getSessionManager(); String id = manager.getIdentifierFactory().get(); try (BatchContext context = this.resumeBatch()) { Session<Map<String, Object>> newSession = manager.createSession(id); try { for (String name: oldSession.getAttributes().getAttributeNames()) { newSession.getAttributes().setAttribute(name, oldSession.getAttributes().getAttribute(name)); } newSession.getMetaData().setMaxInactiveInterval(oldSession.getMetaData().getTimeout()); newSession.getMetaData().setLastAccess(oldSession.getMetaData().getLastAccessStartTime(), oldSession.getMetaData().getLastAccessTime()); newSession.getLocalContext().putAll(oldSession.getLocalContext()); oldSession.invalidate(); config.setSessionId(exchange, id); this.entry = Map.entry(newSession, config); } catch (IllegalStateException e) { this.closeIfInvalid(exchange, oldSession); newSession.invalidate(); throw e; } } if (!oldSession.isValid()) { // Invoke listeners outside of the context of the batch associated with this session this.manager.getSessionListeners().sessionIdChanged(this, oldSession.getId()); } return id; } private BatchContext resumeBatch() { Batch batch = (this.batch != null) && (this.batch.getState() != Batch.State.CLOSED) ? this.batch : null; return this.manager.getSessionManager().getBatcher().resumeBatch(batch); } private void closeIfInvalid(HttpServerExchange exchange, Session<Map<String, Object>> session) { if (!session.isValid()) { // If session was invalidated by a concurrent request, Undertow will not trigger Session.requestDone(...), so we need to close the session here try { session.close(); } finally { // Ensure close task is run this.closeTask.accept(exchange); } } } }
15,948
45.095376
225
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/UndertowSessionManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.Map; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.web.session.SessionManager; import io.undertow.server.session.SessionListeners; /** * Exposes additional session manager aspects to a session. * @author Paul Ferraro */ public interface UndertowSessionManager extends io.undertow.server.session.SessionManager { /** * Returns the configured session listeners for this web application * @return the session listeners */ SessionListeners getSessionListeners(); /** * Returns underlying distributable session manager implementation. * @return a session manager */ SessionManager<Map<String, Object>, Batch> getSessionManager(); }
1,798
36.479167
91
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/DistributableSessionManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.time.Duration; import java.util.Collections; import java.util.Map; import java.util.OptionalLong; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.StampedLock; import java.util.function.Consumer; import java.util.function.LongConsumer; import io.undertow.UndertowMessages; import io.undertow.server.HttpServerExchange; import io.undertow.server.session.SessionConfig; import io.undertow.server.session.SessionListener; import io.undertow.server.session.SessionListeners; import io.undertow.server.session.SessionManagerStatistics; import io.undertow.util.AttachmentKey; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.web.IdentifierMarshaller; import org.wildfly.clustering.web.session.Session; import org.wildfly.clustering.web.session.SessionManager; import org.wildfly.clustering.web.session.oob.OOBSession; import org.wildfly.clustering.web.undertow.UndertowIdentifierSerializerProvider; import org.wildfly.clustering.web.undertow.logging.UndertowClusteringLogger; import org.wildfly.common.function.Functions; /** * Adapts a distributable {@link SessionManager} to an Undertow {@link io.undertow.server.session.SessionManager}. * @author Paul Ferraro */ public class DistributableSessionManager implements UndertowSessionManager, LongConsumer { private static final IdentifierMarshaller IDENTIFIER_MARSHALLER = new UndertowIdentifierSerializerProvider().getMarshaller(); private final AttachmentKey<io.undertow.server.session.Session> key = AttachmentKey.create(io.undertow.server.session.Session.class); private final String deploymentName; private final SessionListeners listeners; private final SessionManager<Map<String, Object>, Batch> manager; private final RecordableSessionManagerStatistics statistics; private final StampedLock lifecycleLock = new StampedLock(); // Matches io.undertow.server.session.InMemorySessionManager private volatile int defaultSessionTimeout = 30 * 60; // Guarded by this private OptionalLong lifecycleStamp = OptionalLong.empty(); public DistributableSessionManager(DistributableSessionManagerConfiguration config) { this.deploymentName = config.getDeploymentName(); this.manager = config.getSessionManager(); this.listeners = config.getSessionListeners(); this.statistics = config.getStatistics(); } @Override public SessionListeners getSessionListeners() { return this.listeners; } @Override public SessionManager<Map<String, Object>, Batch> getSessionManager() { return this.manager; } @Override public synchronized void start() { this.lifecycleStamp.ifPresent(this); this.manager.start(); if (this.statistics != null) { this.statistics.reset(); } } @Override public void accept(long stamp) { this.lifecycleLock.unlock(stamp); this.lifecycleStamp = OptionalLong.empty(); } @Override public synchronized void stop() { if (!this.lifecycleStamp.isPresent()) { Duration stopTimeout = this.manager.getStopTimeout(); try { long stamp = this.lifecycleLock.tryWriteLock(stopTimeout.getSeconds(), TimeUnit.SECONDS); if (stamp != 0) { this.lifecycleStamp = OptionalLong.of(stamp); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } this.manager.stop(); } private Consumer<HttpServerExchange> getSessionCloseTask() { StampedLock lock = this.lifecycleLock; long stamp = lock.tryReadLock(); if (stamp == 0L) { throw UndertowClusteringLogger.ROOT_LOGGER.sessionManagerStopped(); } AttachmentKey<io.undertow.server.session.Session> key = this.key; AtomicLong stampRef = new AtomicLong(stamp); return new Consumer<>() { @Override public void accept(HttpServerExchange exchange) { try { // Ensure we only unlock once. long stamp = stampRef.getAndSet(0L); if (stamp != 0L) { lock.unlock(stamp); } } finally { if (exchange != null) { exchange.removeAttachment(key); } } } }; } @Override public io.undertow.server.session.Session createSession(HttpServerExchange exchange, SessionConfig config) { if (config == null) { throw UndertowMessages.MESSAGES.couldNotFindSessionCookieConfig(); } if (exchange.isResponseStarted()) { // Should match the condition in io.undertow.servlet.spec.HttpServletResponseImpl#isCommitted() // Return single-use session to be garbage collected at the end of the request io.undertow.server.session.Session session = new OrphanSession(this, this.manager.getIdentifierFactory().get()); session.setMaxInactiveInterval(this.defaultSessionTimeout); return session; } String requestedId = config.findSessionId(exchange); boolean close = true; Consumer<HttpServerExchange> closeTask = this.getSessionCloseTask(); try { String id = (requestedId == null) ? this.manager.getIdentifierFactory().get() : requestedId; Batcher<Batch> batcher = this.manager.getBatcher(); // Batch will be closed by Session.close(); Batch batch = batcher.createBatch(); try { Session<Map<String, Object>> session = this.manager.createSession(id); if (session == null) { throw UndertowClusteringLogger.ROOT_LOGGER.sessionAlreadyExists(id); } // Apply session ID encoding config.setSessionId(exchange, id); io.undertow.server.session.Session result = new DistributableSession(this, session, config, batcher.suspendBatch(), closeTask, this.statistics); this.listeners.sessionCreated(result, exchange); if (this.statistics != null) { this.statistics.record(session.getMetaData()); } exchange.putAttachment(this.key, result); close = false; return result; } catch (RuntimeException | Error e) { batch.discard(); throw e; } finally { if (close) { batch.close(); } } } finally { if (close) { closeTask.accept(exchange); } } } @Override public io.undertow.server.session.Session getSession(HttpServerExchange exchange, SessionConfig config) { if (exchange != null) { io.undertow.server.session.Session attachedSession = exchange.getAttachment(this.key); if (attachedSession != null) { return attachedSession; } } if (config == null) { throw UndertowMessages.MESSAGES.couldNotFindSessionCookieConfig(); } String id = config.findSessionId(exchange); if (id == null) { return null; } // If requested id contains invalid characters, then session cannot exist and would otherwise cause session lookup to fail if (!IDENTIFIER_MARSHALLER.validate(id)) { return null; } boolean close = true; Consumer<HttpServerExchange> closeTask = this.getSessionCloseTask(); try { Batcher<Batch> batcher = this.manager.getBatcher(); Batch batch = batcher.createBatch(); try { Session<Map<String, Object>> session = this.manager.findSession(id); if (session == null) { return null; } // Update session ID encoding config.setSessionId(exchange, id); io.undertow.server.session.Session result = new DistributableSession(this, session, config, batcher.suspendBatch(), closeTask, this.statistics); if (exchange != null) { exchange.putAttachment(this.key, result); } close = false; return result; } catch (RuntimeException | Error e) { batch.discard(); throw e; } finally { if (close) { batch.close(); } } } finally { if (close) { closeTask.accept(exchange); } } } @Override public void registerSessionListener(SessionListener listener) { this.listeners.addSessionListener(listener); } @Override public void removeSessionListener(SessionListener listener) { this.listeners.removeSessionListener(listener); } @Override public void setDefaultSessionTimeout(int timeout) { this.defaultSessionTimeout = timeout; } @Override public Set<String> getTransientSessions() { // We are a distributed session manager, so none of our sessions are transient return Collections.emptySet(); } @Override public Set<String> getActiveSessions() { return this.manager.getActiveSessions(); } @Override public Set<String> getAllSessions() { return this.manager.getLocalSessions(); } @Override public io.undertow.server.session.Session getSession(String sessionId) { // If requested id contains invalid characters, then session cannot exist and would otherwise cause session lookup to fail if (!IDENTIFIER_MARSHALLER.validate(sessionId)) { return null; } Session<Map<String, Object>> session = new OOBSession<>(this.manager, sessionId, LocalSessionContextFactory.INSTANCE.createLocalContext()); return session.isValid() ? new DistributableSession(this, session, new SimpleSessionConfig(sessionId), null, Functions.discardingConsumer(), null) : null; } @Override public String getDeploymentName() { return this.deploymentName; } @Override public SessionManagerStatistics getStatistics() { return this.statistics; } @Override public boolean equals(Object object) { if (!(object instanceof DistributableSessionManager)) return false; DistributableSessionManager manager = (DistributableSessionManager) object; return this.deploymentName.equals(manager.getDeploymentName()); } @Override public int hashCode() { return this.deploymentName.hashCode(); } @Override public String toString() { return this.deploymentName; } }
12,227
36.509202
162
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/DistributableSessionManagerFactoryServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import jakarta.servlet.ServletContext; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.service.FunctionalService; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.clustering.web.container.SessionManagerFactoryConfiguration; import org.wildfly.clustering.web.session.DistributableSessionManagementConfiguration; import io.undertow.servlet.api.SessionManagerFactory; /** * Distributable {@link SessionManagerFactory} builder for Undertow. * @author Paul Ferraro */ public class DistributableSessionManagerFactoryServiceConfigurator<C extends DistributableSessionManagementConfiguration<DeploymentUnit>> extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, Function<org.wildfly.clustering.web.session.SessionManagerFactory<ServletContext, Map<String, Object>, Batch>, SessionManagerFactory> { private final SessionManagerFactoryConfiguration configuration; private final SupplierDependency<org.wildfly.clustering.web.session.SessionManagerFactory<ServletContext, Map<String, Object>, Batch>> dependency; public DistributableSessionManagerFactoryServiceConfigurator(ServiceName name, SessionManagerFactoryConfiguration configuration, SupplierDependency<org.wildfly.clustering.web.session.SessionManagerFactory<ServletContext, Map<String, Object>, Batch>> dependency) { super(name); this.configuration = configuration; this.dependency = dependency; } @Override public SessionManagerFactory apply(org.wildfly.clustering.web.session.SessionManagerFactory<ServletContext, Map<String, Object>, Batch> factory) { return new DistributableSessionManagerFactory(factory, this.configuration); } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceBuilder<?> builder = target.addService(this.getServiceName()); Consumer<SessionManagerFactory> factory = this.dependency.register(builder).provides(this.getServiceName()); Service service = new FunctionalService<>(factory, this, this.dependency); return builder.setInstance(service).setInitialMode(ServiceController.Mode.ON_DEMAND); } }
3,750
49.689189
349
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/RecordableInactiveSessionStatistics.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import org.wildfly.clustering.ee.Recordable; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; import org.wildfly.clustering.web.session.InactiveSessionStatistics; /** * Recordable {@link InactiveSessionStatistics}. * @author Paul Ferraro */ public interface RecordableInactiveSessionStatistics extends InactiveSessionStatistics, Recordable<ImmutableSessionMetaData> { }
1,472
39.916667
126
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/DistributableImmutableSession.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.ImmutableSessionAttributes; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; import io.undertow.server.HttpServerExchange; import io.undertow.server.session.Session; import io.undertow.server.session.SessionConfig; import io.undertow.server.session.SessionManager; /** * Undertow adapter for an {@link ImmutableSession}. * @author Paul Ferraro */ public class DistributableImmutableSession implements Session { private final SessionManager manager; private final String id; private final Map<String, Object> attributes = new HashMap<>(); private final long creationTime; private final long lastAccessedTime; private final int maxInactiveInterval; public DistributableImmutableSession(SessionManager manager, ImmutableSession session) { this.manager = manager; this.id = session.getId(); ImmutableSessionAttributes attributes = session.getAttributes(); for (String name: attributes.getAttributeNames()) { this.attributes.put(name, attributes.getAttribute(name)); } ImmutableSessionMetaData metaData = session.getMetaData(); this.creationTime = metaData.getCreationTime().toEpochMilli(); this.lastAccessedTime = metaData.getLastAccessStartTime().toEpochMilli(); this.maxInactiveInterval = (int) metaData.getTimeout().getSeconds(); } @Override public String getId() { return this.id; } @Override public SessionManager getSessionManager() { return this.manager; } @Override public void requestDone(HttpServerExchange serverExchange) { // Do nothing } @Override public long getCreationTime() { return this.creationTime; } @Override public long getLastAccessedTime() { return this.lastAccessedTime; } @Override public int getMaxInactiveInterval() { return this.maxInactiveInterval; } @Override public void setMaxInactiveInterval(int interval) { throw new UnsupportedOperationException(); } @Override public Object getAttribute(String name) { return this.attributes.get(name); } @Override public Set<String> getAttributeNames() { return Collections.unmodifiableSet(this.attributes.keySet()); } @Override public Object setAttribute(String name, Object value) { return value; } @Override public Object removeAttribute(String name) { return null; } @Override public void invalidate(HttpServerExchange exchange) { // Do nothing } @Override public String changeSessionId(HttpServerExchange exchange, SessionConfig config) { return null; } }
4,024
30.20155
92
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/UndertowDistributableSessionManagementProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.List; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.msc.service.ServiceName; import org.wildfly.clustering.ee.Immutability; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.web.container.SessionManagementProvider; import org.wildfly.clustering.web.container.SessionManagerFactoryConfiguration; import org.wildfly.clustering.web.container.WebDeploymentConfiguration; import org.wildfly.clustering.web.service.session.DistributableSessionManagementProvider; import org.wildfly.clustering.web.session.DistributableSessionManagementConfiguration; import org.wildfly.clustering.web.undertow.routing.DistributableAffinityLocatorServiceConfigurator; import org.wildfly.clustering.web.undertow.routing.DistributableSessionIdentifierCodecServiceConfigurator; import org.wildfly.extension.undertow.session.SessionConfigWrapperFactoryServiceConfigurator; /** * {@link SessionManagementProvider} for Undertow. * @author Paul Ferraro */ public class UndertowDistributableSessionManagementProvider<C extends DistributableSessionManagementConfiguration<DeploymentUnit>> implements SessionManagementProvider { private final DistributableSessionManagementProvider<C> provider; private final Immutability immutability; public UndertowDistributableSessionManagementProvider(DistributableSessionManagementProvider<C> provider, Immutability immutability) { this.provider = provider; this.immutability = immutability; } @Override public Iterable<CapabilityServiceConfigurator> getSessionManagerFactoryServiceConfigurators(ServiceName name, SessionManagerFactoryConfiguration configuration) { CapabilityServiceConfigurator configurator = this.provider.getSessionManagerFactoryServiceConfigurator(new SessionManagerFactoryConfigurationAdapter<>(configuration, this.provider.getSessionManagementConfiguration(), this.immutability)); return List.of(configurator, new DistributableSessionManagerFactoryServiceConfigurator<>(name, configuration, new ServiceSupplierDependency<>(configurator))); } @Override public Iterable<CapabilityServiceConfigurator> getSessionAffinityServiceConfigurators(ServiceName name, WebDeploymentConfiguration configuration) { CapabilityServiceConfigurator routeLocatorConfigurator = this.provider.getRouteLocatorServiceConfigurator(new WebDeploymentConfigurationAdapter(configuration)); CapabilityServiceConfigurator codecConfigurator = new DistributableSessionIdentifierCodecServiceConfigurator(name.append("codec"), new ServiceSupplierDependency<>(routeLocatorConfigurator)); CapabilityServiceConfigurator affinityLocatorConfigurator = new DistributableAffinityLocatorServiceConfigurator(name.append("affinity"), new ServiceSupplierDependency<>(routeLocatorConfigurator)); CapabilityServiceConfigurator wrapperFactoryConfigurator = new SessionConfigWrapperFactoryServiceConfigurator(name, new ServiceSupplierDependency<>(codecConfigurator), new ServiceSupplierDependency<>(affinityLocatorConfigurator)); return List.of(routeLocatorConfigurator, codecConfigurator, affinityLocatorConfigurator, wrapperFactoryConfigurator); } }
4,389
61.714286
245
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/session/SessionManagerFactoryConfigurationAdapter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.session; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpSession; import jakarta.servlet.http.HttpSessionActivationListener; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.modules.Module; import org.wildfly.clustering.ee.Immutability; import org.wildfly.clustering.ee.immutable.CompositeImmutability; import org.wildfly.clustering.ee.immutable.DefaultImmutability; import org.wildfly.clustering.marshalling.spi.ByteBufferMarshaller; import org.wildfly.clustering.web.LocalContextFactory; import org.wildfly.clustering.web.container.SessionManagerFactoryConfiguration; import org.wildfly.clustering.web.session.DistributableSessionManagementConfiguration; import org.wildfly.clustering.web.session.SessionAttributeImmutability; import org.wildfly.clustering.web.session.SessionAttributePersistenceStrategy; import org.wildfly.clustering.web.session.SpecificationProvider; import org.wildfly.common.iteration.CompositeIterable; /** * @author Paul Ferraro */ public class SessionManagerFactoryConfigurationAdapter<C extends DistributableSessionManagementConfiguration<DeploymentUnit>> extends WebDeploymentConfigurationAdapter implements org.wildfly.clustering.web.session.SessionManagerFactoryConfiguration<HttpSession, ServletContext, HttpSessionActivationListener, Map<String, Object>> { private final Integer maxActiveSessions; private final ByteBufferMarshaller marshaller; private final Immutability immutability; private final SessionAttributePersistenceStrategy attributePersistenceStrategy; public SessionManagerFactoryConfigurationAdapter(SessionManagerFactoryConfiguration configuration, C managementConfiguration, Immutability immutability) { super(configuration); this.maxActiveSessions = configuration.getMaxActiveSessions(); DeploymentUnit unit = configuration.getDeploymentUnit(); Module module = unit.getAttachment(Attachments.MODULE); this.marshaller = managementConfiguration.getMarshallerFactory().apply(configuration.getDeploymentUnit()); List<Immutability> loadedImmutabilities = new LinkedList<>(); for (Immutability loadedImmutability : module.loadService(Immutability.class)) { loadedImmutabilities.add(loadedImmutability); } this.immutability = new CompositeImmutability(new CompositeIterable<>(EnumSet.allOf(DefaultImmutability.class), EnumSet.allOf(SessionAttributeImmutability.class), EnumSet.allOf(UndertowSessionAttributeImmutability.class), loadedImmutabilities, List.of(immutability))); this.attributePersistenceStrategy = managementConfiguration.getAttributePersistenceStrategy(); } @Override public Integer getMaxActiveSessions() { return this.maxActiveSessions; } @Override public ByteBufferMarshaller getMarshaller() { return this.marshaller; } @Override public LocalContextFactory<Map<String, Object>> getLocalContextFactory() { return LocalSessionContextFactory.INSTANCE; } @Override public Immutability getImmutability() { return this.immutability; } @Override public SpecificationProvider<HttpSession, ServletContext, HttpSessionActivationListener> getSpecificationProvider() { return UndertowSpecificationProvider.INSTANCE; } @Override public SessionAttributePersistenceStrategy getAttributePersistenceStrategy() { return this.attributePersistenceStrategy; } }
4,716
44.796117
331
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/routing/DistributableSessionIdentifierCodecServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.routing; import java.util.function.Consumer; import java.util.function.Function; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.web.session.RoutingSupport; import org.jboss.as.web.session.SessionIdentifierCodec; import org.jboss.as.web.session.SimpleRoutingSupport; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.FunctionalService; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.clustering.web.routing.RouteLocator; /** * Builds a distributable {@link SessionIdentifierCodec} service. * @author Paul Ferraro */ public class DistributableSessionIdentifierCodecServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, Function<RouteLocator, SessionIdentifierCodec> { private final SupplierDependency<RouteLocator> locatorDependency; private final RoutingSupport routing = new SimpleRoutingSupport(); public DistributableSessionIdentifierCodecServiceConfigurator(ServiceName name, SupplierDependency<RouteLocator> locatorDependency) { super(name); this.locatorDependency = locatorDependency; } @Override public SessionIdentifierCodec apply(RouteLocator locator) { return new DistributableSessionIdentifierCodec(locator, this.routing); } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceBuilder<?> builder = target.addService(this.getServiceName()); Consumer<SessionIdentifierCodec> codec = this.locatorDependency.register(builder).provides(this.getServiceName()); Service service = new FunctionalService<>(codec, this, this.locatorDependency); return builder.setInstance(service).setInitialMode(ServiceController.Mode.ON_DEMAND); } }
3,107
44.705882
192
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/routing/DistributableAffinityLocator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.routing; import org.jboss.as.web.session.AffinityLocator; import org.wildfly.clustering.web.routing.RouteLocator; /** * The {@link AffinityLocator} implementation that leverages distributable {@link RouteLocator}. * * @author Radoslav Husar */ public class DistributableAffinityLocator implements AffinityLocator { private final RouteLocator locator; public DistributableAffinityLocator(RouteLocator locator) { this.locator = locator; } @Override public String locate(String sessionId) { return this.locator.locate(sessionId); } }
1,648
34.847826
96
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/routing/DistributableSessionIdentifierCodec.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.routing; import org.jboss.as.web.session.RoutingSupport; import org.jboss.as.web.session.SessionIdentifierCodec; import org.wildfly.clustering.web.routing.RouteLocator; /** * {@link SessionIdentifierCodec} that encodes the route determined by a {@link RouteLocator}. * @author Paul Ferraro */ public class DistributableSessionIdentifierCodec implements SessionIdentifierCodec { private final RouteLocator locator; private final RoutingSupport routing; public DistributableSessionIdentifierCodec(RouteLocator locator, RoutingSupport routing) { this.locator = locator; this.routing = routing; } @Override public CharSequence encode(CharSequence sessionId) { String route = this.locator.locate(sessionId.toString()); return (route != null) ? this.routing.format(sessionId, route) : sessionId; } @Override public CharSequence decode(CharSequence encodedSessionId) { return this.routing.parse(encodedSessionId).getKey(); } }
2,077
37.481481
94
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/routing/UndertowDistributableServerRuntimeHandler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.routing; import java.util.Iterator; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.function.Consumer; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.service.ChildTargetService; import org.wildfly.clustering.service.FunctionSupplierDependency; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SimpleSupplierDependency; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.clustering.web.service.WebRequirement; import org.wildfly.clustering.web.service.routing.LegacyRoutingProviderFactory; import org.wildfly.clustering.web.service.routing.RoutingProvider; import org.wildfly.clustering.web.undertow.UndertowUnaryRequirement; import org.wildfly.clustering.web.undertow.logging.UndertowClusteringLogger; import org.wildfly.extension.undertow.Server; import org.wildfly.extension.undertow.session.DistributableServerRuntimeHandler; /** * @author Paul Ferraro */ @SuppressWarnings("deprecation") @MetaInfServices(DistributableServerRuntimeHandler.class) public class UndertowDistributableServerRuntimeHandler implements DistributableServerRuntimeHandler { private final LegacyRoutingProviderFactory legacyProviderFactory; public UndertowDistributableServerRuntimeHandler() { Iterator<LegacyRoutingProviderFactory> factories = ServiceLoader.load(LegacyRoutingProviderFactory.class, LegacyRoutingProviderFactory.class.getClassLoader()).iterator(); if (!factories.hasNext()) { throw new ServiceConfigurationError(LegacyRoutingProviderFactory.class.getName()); } this.legacyProviderFactory = factories.next(); } @Override public void execute(OperationContext context, String serverName) { SupplierDependency<RoutingProvider> provider = this.getRoutingProvider(context, serverName); if (provider != null) { ServiceTarget target = context.getServiceTarget(); CapabilityServiceSupport support = context.getCapabilityServiceSupport(); SupplierDependency<Server> server = new ServiceSupplierDependency<>(UndertowUnaryRequirement.SERVER.getServiceName(context, serverName)); SupplierDependency<String> route = new FunctionSupplierDependency<>(server, Server::getRoute); Consumer<ServiceTarget> installer = new Consumer<>() { @Override public void accept(ServiceTarget target) { for (CapabilityServiceConfigurator configurator : provider.get().getServiceConfigurators(serverName, route)) { configurator.configure(support).build(target).install(); } } }; ServiceName name = ServiceName.JBOSS.append("clustering", "web", "undertow", "routing", serverName); provider.register(target.addService(name)).setInstance(new ChildTargetService(installer)).install(); } } private SupplierDependency<RoutingProvider> getRoutingProvider(OperationContext context, String serverName) { if (context.hasOptionalCapability(WebRequirement.ROUTING_PROVIDER.getName(), UndertowUnaryRequirement.SERVER.resolve(serverName), null)) { return new ServiceSupplierDependency<>(WebRequirement.ROUTING_PROVIDER.getServiceName(context)); } UndertowClusteringLogger.ROOT_LOGGER.legacyRoutingProviderInUse(serverName); return new SimpleSupplierDependency<>(this.legacyProviderFactory.createRoutingProvider()); } }
4,914
50.736842
178
java
null
wildfly-main/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/routing/DistributableAffinityLocatorServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.undertow.routing; import java.util.function.Consumer; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.web.session.AffinityLocator; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.FunctionalService; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.clustering.web.routing.RouteLocator; /** * Builds a distributable {@link DistributableAffinityLocator} service. * * @author Radoslav Husar */ public class DistributableAffinityLocatorServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator { private final SupplierDependency<RouteLocator> dependency; public DistributableAffinityLocatorServiceConfigurator(ServiceName name, SupplierDependency<RouteLocator> dependency) { super(name); this.dependency = dependency; } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceBuilder<?> builder = target.addService(this.getServiceName()); Consumer<AffinityLocator> affinityLocator = this.dependency.register(builder).provides(this.getServiceName()); Service service = new FunctionalService<>(affinityLocator, DistributableAffinityLocator::new, this.dependency); return builder.setInstance(service).setInitialMode(ServiceController.Mode.ON_DEMAND); } }
2,676
43.616667
137
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/TestIdentifierSerializerProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan; import java.nio.ByteBuffer; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.spi.Marshaller; import org.wildfly.clustering.web.IdentifierMarshaller; import org.wildfly.clustering.web.IdentifierMarshallerProvider; /** * @author Paul Ferraro */ @MetaInfServices(IdentifierMarshallerProvider.class) public class TestIdentifierSerializerProvider implements IdentifierMarshallerProvider { @Override public Marshaller<String, ByteBuffer> getMarshaller() { return IdentifierMarshaller.ISO_LATIN_1; } }
1,621
36.72093
87
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/ServiceLoaderTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan; import java.util.ServiceLoader; import org.infinispan.persistence.keymappers.TwoWayKey2StringMapper; import org.jboss.logging.Logger; import org.junit.Test; import org.wildfly.clustering.marshalling.Externalizer; /** * Validates loading of services. * * @author Paul Ferraro */ public class ServiceLoaderTestCase { private static final Logger LOGGER = Logger.getLogger(ServiceLoaderTestCase.class); private static <T> void load(Class<T> targetClass) { ServiceLoader.load(targetClass, ServiceLoaderTestCase.class.getClassLoader()) .forEach(object -> LOGGER.trace("\t" + object.getClass().getName())); } @Test public void load() { load(Externalizer.class); load(TwoWayKey2StringMapper.class); } }
1,839
35.078431
87
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/KeyMapperTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan; import java.util.UUID; import org.junit.Test; import org.wildfly.clustering.infinispan.persistence.KeyMapperTester; import org.wildfly.clustering.web.infinispan.session.SessionAccessMetaDataKey; import org.wildfly.clustering.web.infinispan.session.SessionCreationMetaDataKey; import org.wildfly.clustering.web.infinispan.session.coarse.SessionAttributesKey; import org.wildfly.clustering.web.infinispan.session.fine.SessionAttributeKey; import org.wildfly.clustering.web.infinispan.session.fine.SessionAttributeNamesKey; import org.wildfly.clustering.web.infinispan.sso.AuthenticationKey; import org.wildfly.clustering.web.infinispan.sso.coarse.CoarseSessionsKey; /** * @author Paul Ferraro */ public class KeyMapperTestCase { @Test public void test() { KeyMapperTester tester = new KeyMapperTester(new KeyMapper()); String id = "ABC123"; tester.test(new SessionCreationMetaDataKey(id)); tester.test(new SessionAccessMetaDataKey(id)); tester.test(new SessionAttributesKey(id)); tester.test(new SessionAttributeNamesKey(id)); tester.test(new SessionAttributeKey(id, UUID.randomUUID())); tester.test(new AuthenticationKey(id)); tester.test(new CoarseSessionsKey(id)); } }
2,333
39.947368
83
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/sso/AuthenticationKeyTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.sso; import java.io.IOException; import org.junit.Test; import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; import org.wildfly.clustering.marshalling.spi.FormatterTester; /** * Unit test for {@link AuthenticationKey}. * @author Paul Ferraro */ public class AuthenticationKeyTestCase { @Test public void test() throws IOException { AuthenticationKey key = new AuthenticationKey("ABC123"); ProtoStreamTesterFactory.INSTANCE.createTester().test(key); new FormatterTester<>(new AuthenticationKeyFormatter()).test(key); } }
1,660
36.75
79
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/sso/coarse/CoarseSessionsKeyTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.sso.coarse; import java.io.IOException; import org.junit.Test; import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; import org.wildfly.clustering.marshalling.spi.FormatterTester; /** * Unit test for {@link CoarseSessionsKey}. * @author Paul Ferraro */ public class CoarseSessionsKeyTestCase { @Test public void test() throws IOException { CoarseSessionsKey key = new CoarseSessionsKey("ABC123"); ProtoStreamTesterFactory.INSTANCE.createTester().test(key); new FormatterTester<>(new CoarseSessionsKeyFormatter()).test(key); } }
1,667
36.909091
79
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/session/SessionAccessMetaDataKeyTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.session; import java.io.IOException; import org.junit.Test; import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; import org.wildfly.clustering.marshalling.spi.FormatterTester; /** * Unit test for {@link SessionAccessMetaDataKey}. * @author Paul Ferraro */ public class SessionAccessMetaDataKeyTestCase { @Test public void test() throws IOException { SessionAccessMetaDataKey key = new SessionAccessMetaDataKey("ABC123"); ProtoStreamTesterFactory.INSTANCE.createTester().test(key); new FormatterTester<>(new SessionAccessMetaDataKeyFormatter()).test(key); } }
1,699
37.636364
81
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/session/SessionExpirationSchedulerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.session; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.Duration; import java.time.Instant; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ee.Remover; import org.wildfly.clustering.ee.Scheduler; import org.wildfly.clustering.ee.cache.tx.TransactionBatch; import org.wildfly.clustering.ee.expiration.ExpirationMetaData; import org.wildfly.clustering.web.cache.session.ImmutableSessionMetaDataFactory; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; /** * Unit test for {@link SessionExpirationScheduler}. * * @author Paul Ferraro */ public class SessionExpirationSchedulerTestCase { @Test public void test() throws InterruptedException { Batcher<TransactionBatch> batcher = mock(Batcher.class); TransactionBatch batch = mock(TransactionBatch.class); Remover<String> remover = mock(Remover.class); ImmutableSessionMetaDataFactory<Object> metaDataFactory = mock(ImmutableSessionMetaDataFactory.class); ImmutableSessionMetaData immortalSessionMetaData = mock(ImmutableSessionMetaData.class); ImmutableSessionMetaData expiringSessionMetaData = mock(ImmutableSessionMetaData.class); ImmutableSessionMetaData canceledSessionMetaData = mock(ImmutableSessionMetaData.class); String immortalSessionId = "immortal"; String expiringSessionId = "expiring"; String canceledSessionId = "canceled"; when(batcher.createBatch()).thenReturn(batch); when(immortalSessionMetaData.isImmortal()).thenReturn(true); when(expiringSessionMetaData.isImmortal()).thenReturn(false); when(canceledSessionMetaData.isImmortal()).thenReturn(false); when(expiringSessionMetaData.getTimeout()).thenReturn(Duration.ofMillis(1L)); when(canceledSessionMetaData.getTimeout()).thenReturn(Duration.ofSeconds(100L)); Instant now = Instant.now(); when(expiringSessionMetaData.getLastAccessTime()).thenReturn(now); when(canceledSessionMetaData.getLastAccessTime()).thenReturn(now); when(remover.remove(expiringSessionId)).thenReturn(true); try (Scheduler<String, ExpirationMetaData> scheduler = new SessionExpirationScheduler<>(batcher, metaDataFactory, remover, Duration.ZERO)) { scheduler.schedule(immortalSessionId, immortalSessionMetaData); scheduler.schedule(canceledSessionId, canceledSessionMetaData); scheduler.schedule(expiringSessionId, expiringSessionMetaData); scheduler.cancel(canceledSessionId); TimeUnit.MILLISECONDS.sleep(500); } verify(remover, never()).remove(immortalSessionId); verify(remover, never()).remove(canceledSessionId); verify(batch).close(); } }
4,028
43.766667
148
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/session/ExpiredSessionRemoverTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.session; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.UUID; import java.util.function.Consumer; import org.junit.Test; import org.wildfly.clustering.Registration; import org.wildfly.clustering.web.cache.session.SessionAttributesFactory; import org.wildfly.clustering.web.cache.session.SessionFactory; import org.wildfly.clustering.web.cache.session.SessionMetaDataFactory; import org.wildfly.clustering.web.session.ImmutableSession; import org.wildfly.clustering.web.session.ImmutableSessionAttributes; import org.wildfly.clustering.web.session.ImmutableSessionMetaData; /** * Unit test for {@link ExpiredSessionRemover}. * * @author Paul Ferraro */ public class ExpiredSessionRemoverTestCase { @Test public void test() { SessionFactory<Object, UUID, UUID, Object> factory = mock(SessionFactory.class); SessionMetaDataFactory<UUID> metaDataFactory = mock(SessionMetaDataFactory.class); SessionAttributesFactory<Object, UUID> attributesFactory = mock(SessionAttributesFactory.class); Consumer<ImmutableSession> listener = mock(Consumer.class); ImmutableSessionAttributes expiredAttributes = mock(ImmutableSessionAttributes.class); ImmutableSessionMetaData validMetaData = mock(ImmutableSessionMetaData.class); ImmutableSessionMetaData expiredMetaData = mock(ImmutableSessionMetaData.class); ImmutableSession expiredSession = mock(ImmutableSession.class); String missingSessionId = "missing"; String expiredSessionId = "expired"; String validSessionId = "valid"; UUID expiredMetaDataValue = UUID.randomUUID(); UUID expiredAttributesValue = UUID.randomUUID(); UUID validMetaDataValue = UUID.randomUUID(); ExpiredSessionRemover<Object, UUID, UUID, Object> subject = new ExpiredSessionRemover<>(factory); try (Registration regisration = subject.register(listener)) { when(factory.getMetaDataFactory()).thenReturn(metaDataFactory); when(factory.getAttributesFactory()).thenReturn(attributesFactory); when(metaDataFactory.tryValue(missingSessionId)).thenReturn(null); when(metaDataFactory.tryValue(expiredSessionId)).thenReturn(expiredMetaDataValue); when(metaDataFactory.tryValue(validSessionId)).thenReturn(validMetaDataValue); when(metaDataFactory.createImmutableSessionMetaData(expiredSessionId, expiredMetaDataValue)).thenReturn(expiredMetaData); when(metaDataFactory.createImmutableSessionMetaData(validSessionId, validMetaDataValue)).thenReturn(validMetaData); when(expiredMetaData.isExpired()).thenReturn(true); when(validMetaData.isExpired()).thenReturn(false); when(attributesFactory.findValue(expiredSessionId)).thenReturn(expiredAttributesValue); when(attributesFactory.createImmutableSessionAttributes(expiredSessionId, expiredAttributesValue)).thenReturn(expiredAttributes); when(factory.createImmutableSession(same(expiredSessionId), same(expiredMetaData), same(expiredAttributes))).thenReturn(expiredSession); subject.remove(missingSessionId); subject.remove(expiredSessionId); subject.remove(validSessionId); verify(factory).remove(expiredSessionId); verify(factory, never()).remove(missingSessionId); verify(factory, never()).remove(validSessionId); verify(listener).accept(expiredSession); } } }
4,755
47.530612
148
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/session/SessionCreationMetaDataKeyTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.session; import java.io.IOException; import org.junit.Test; import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; import org.wildfly.clustering.marshalling.spi.FormatterTester; /** * Unit test for {@link SessionCreationMetaDataKey}. * @author Paul Ferraro */ public class SessionCreationMetaDataKeyTestCase { @Test public void test() throws IOException { SessionCreationMetaDataKey key = new SessionCreationMetaDataKey("ABC123"); ProtoStreamTesterFactory.INSTANCE.createTester().test(key); new FormatterTester<>(new SessionCreationMetaDataKeyFormatter()).test(key); } }
1,709
37.863636
83
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/session/fine/SessionAttributeKeyTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.session.fine; import java.io.IOException; import java.util.UUID; import org.junit.Test; import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; import org.wildfly.clustering.marshalling.spi.FormatterTester; /** * Unit test for {@link SessionAttributeKey}. * @author Paul Ferraro */ public class SessionAttributeKeyTestCase { @Test public void test() throws IOException { SessionAttributeKey key = new SessionAttributeKey("ABC123", UUID.randomUUID()); ProtoStreamTesterFactory.INSTANCE.createTester().test(key); new FormatterTester<>(new SessionAttributeKeyFormatter()).test(key); } }
1,721
37.266667
87
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/session/fine/SessionAttributeNamesKeyTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.session.fine; import java.io.IOException; import org.junit.Test; import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; import org.wildfly.clustering.marshalling.spi.FormatterTester; /** * Unit test for {@link SessionAttributeNamesKey}. * @author Paul Ferraro */ public class SessionAttributeNamesKeyTestCase { @Test public void test() throws IOException { SessionAttributeNamesKey key = new SessionAttributeNamesKey("ABC123"); ProtoStreamTesterFactory.INSTANCE.createTester().test(key); new FormatterTester<>(new SessionAttributeNamesKeyFormatter()).test(key); } }
1,704
37.75
81
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/session/coarse/SessionAttributesKeyTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.session.coarse; import java.io.IOException; import org.junit.Test; import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; import org.wildfly.clustering.marshalling.spi.FormatterTester; /** * Unit test for {@link SessionAttributesKey}. * @author Paul Ferraro */ public class SessionAttributesKeyTestCase { @Test public void test() throws IOException { SessionAttributesKey key = new SessionAttributesKey("ABC123"); ProtoStreamTesterFactory.INSTANCE.createTester().test(key); new FormatterTester<>(new SessionAttributesKeyFormatter()).test(key); } }
1,686
37.340909
79
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/routing/PrimaryOwnerRouteLocatorTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.routing; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.function.Function; import org.junit.Test; import org.wildfly.clustering.ee.infinispan.GroupedKey; import org.wildfly.clustering.group.Group; import org.wildfly.clustering.group.Node; import org.wildfly.clustering.registry.Registry; import org.wildfly.clustering.web.routing.RouteLocator; /** * Unit test for {@link InfinispanRouteLocator}. * @author Paul Ferraro */ public class PrimaryOwnerRouteLocatorTestCase { @Test public void test() { Function<GroupedKey<String>, Node> locator = mock(Function.class); Registry<String, Void> registry = mock(Registry.class); Group group = mock(Group.class); Node primary = mock(Node.class); Node local = mock(Node.class); Node missing = mock(Node.class); String primaryRoute = "primary"; String localRoute = "local"; when(registry.getGroup()).thenReturn(group); when(group.getLocalMember()).thenReturn(local); when(registry.getEntry(local)).thenReturn(new SimpleImmutableEntry<>(localRoute, null)); RouteLocator routeLocator = new PrimaryOwnerRouteLocator(locator, registry); when(locator.apply(new GroupedKey<>("session"))).thenReturn(primary); when(registry.getEntry(primary)).thenReturn(new SimpleImmutableEntry<>(primaryRoute, null)); String result = routeLocator.locate("session"); assertSame(primaryRoute, result); when(locator.apply(new GroupedKey<>("missing"))).thenReturn(missing); when(registry.getEntry(missing)).thenReturn(null); result = routeLocator.locate("missing"); assertSame(localRoute, result); } }
2,916
36.883117
100
java
null
wildfly-main/clustering/web/infinispan/src/test/java/org/wildfly/clustering/web/infinispan/routing/RankedRouteLocatorTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.routing; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Arrays; import java.util.Collections; import org.infinispan.remoting.transport.Address; import org.junit.Test; import org.wildfly.clustering.ee.infinispan.GroupedKey; import org.wildfly.clustering.group.Group; import org.wildfly.clustering.group.Node; import org.wildfly.clustering.infinispan.distribution.KeyDistribution; import org.wildfly.clustering.registry.Registry; import org.wildfly.clustering.server.NodeFactory; import org.wildfly.clustering.web.routing.RouteLocator; /** * @author Paul Ferraro */ public class RankedRouteLocatorTestCase { @Test public void test() { KeyDistribution distribution = mock(KeyDistribution.class); NodeFactory<Address> factory = mock(NodeFactory.class); Registry<String, Void> registry = mock(Registry.class); Group group = mock(Group.class); Address owner1 = mock(Address.class); Address owner2 = mock(Address.class); Address owner3 = mock(Address.class); Address owner4 = mock(Address.class); Address unregistered = mock(Address.class); Address local = mock(Address.class); Node member1 = mock(Node.class); Node member2 = mock(Node.class); Node member3 = mock(Node.class); Node member4 = mock(Node.class); Node unregisteredMember = mock(Node.class); Node localMember = mock(Node.class); when(registry.getGroup()).thenReturn(group); when(group.getLocalMember()).thenReturn(localMember); when(registry.getEntry(member1)).thenReturn(new SimpleImmutableEntry<>("member1", null)); when(registry.getEntry(member2)).thenReturn(new SimpleImmutableEntry<>("member2", null)); when(registry.getEntry(member3)).thenReturn(new SimpleImmutableEntry<>("member3", null)); when(registry.getEntry(member4)).thenReturn(new SimpleImmutableEntry<>("member4", null)); when(registry.getEntry(localMember)).thenReturn(new SimpleImmutableEntry<>("local", null)); when(registry.getEntry(unregisteredMember)).thenReturn(null); when(factory.createNode(owner1)).thenReturn(member1); when(factory.createNode(owner2)).thenReturn(member2); when(factory.createNode(owner3)).thenReturn(member3); when(factory.createNode(owner4)).thenReturn(member4); when(factory.createNode(local)).thenReturn(localMember); when(factory.createNode(unregistered)).thenReturn(unregisteredMember); RouteLocator locator = new RankedRouteLocator(distribution, registry, factory, ".", 3); when(distribution.getOwners(new GroupedKey<>("key"))).thenReturn(Arrays.asList(owner1, owner2, owner3, owner4)); assertEquals("member1.member2.member3", locator.locate("key")); when(distribution.getOwners(new GroupedKey<>("key"))).thenReturn(Arrays.asList(owner1, owner2, owner3, local)); assertEquals("member1.member2.member3", locator.locate("key")); when(distribution.getOwners(new GroupedKey<>("key"))).thenReturn(Arrays.asList(owner1, owner2, unregistered, owner4)); assertEquals("member1.member2.member4", locator.locate("key")); when(distribution.getOwners(new GroupedKey<>("key"))).thenReturn(Arrays.asList(owner1, local, owner3)); assertEquals("member1.local.member3", locator.locate("key")); when(distribution.getOwners(new GroupedKey<>("key"))).thenReturn(Arrays.asList(owner1, owner2)); assertEquals("member1.member2.local", locator.locate("key")); when(distribution.getOwners(new GroupedKey<>("key"))).thenReturn(Arrays.asList(local, owner2)); assertEquals("local.member2", locator.locate("key")); when(distribution.getOwners(new GroupedKey<>("key"))).thenReturn(Arrays.asList(owner1)); assertEquals("member1.local", locator.locate("key")); when(distribution.getOwners(new GroupedKey<>("key"))).thenReturn(Arrays.asList(local)); assertEquals("local", locator.locate("key")); when(distribution.getOwners(new GroupedKey<>("key"))).thenReturn(Arrays.asList(unregistered)); assertEquals("local", locator.locate("key")); when(distribution.getOwners(new GroupedKey<>("key"))).thenReturn(Collections.emptyList()); assertEquals("local", locator.locate("key")); } }
5,564
43.52
126
java
null
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/SessionKeyFormatter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan; import java.util.function.Function; import org.wildfly.clustering.ee.infinispan.GroupedKey; import org.wildfly.clustering.marshalling.spi.SimpleFormatter; /** * Base {@link org.wildfly.clustering.marshalling.spi.Formatter} for cache keys containing session identifiers. * @author Paul Ferraro */ public class SessionKeyFormatter<K extends GroupedKey<String>> extends SimpleFormatter<K> { protected SessionKeyFormatter(Class<K> targetClass, Function<String, K> resolver) { super(targetClass, resolver, GroupedKey::getId); } }
1,619
39.5
111
java
null
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/KeyMapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan; import org.infinispan.persistence.keymappers.TwoWayKey2StringMapper; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.infinispan.persistence.DynamicKeyFormatMapper; /** * @author Paul Ferraro */ @MetaInfServices(TwoWayKey2StringMapper.class) public class KeyMapper extends DynamicKeyFormatMapper { public KeyMapper() { super(KeyMapper.class.getClassLoader()); } }
1,473
36.794872
76
java
null
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/sso/SSOSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.sso; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; import org.wildfly.clustering.web.cache.SessionKeyMarshaller; /** * @author Paul Ferraro */ @MetaInfServices(SerializationContextInitializer.class) public class SSOSerializationContextInitializer extends AbstractSerializationContextInitializer { @Override public void registerMarshallers(SerializationContext context) { context.registerMarshaller(new SessionKeyMarshaller<>(AuthenticationKey.class, AuthenticationKey::new)); } }
1,783
41.47619
112
java
null
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/sso/AuthenticationKeyFormatter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.sso; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.spi.Formatter; import org.wildfly.clustering.web.infinispan.SessionKeyFormatter; /** * Formatter for {@link AuthenticationKey} * @author Paul Ferraro */ @MetaInfServices(Formatter.class) public class AuthenticationKeyFormatter extends SessionKeyFormatter<AuthenticationKey> { public AuthenticationKeyFormatter() { super(AuthenticationKey.class, AuthenticationKey::new); } }
1,549
37.75
88
java
null
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/sso/InfinispanSSOFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.sso; import java.io.IOException; import java.util.AbstractMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.Cache; import org.wildfly.clustering.ee.infinispan.InfinispanConfiguration; import org.wildfly.clustering.marshalling.spi.Marshaller; import org.wildfly.clustering.web.LocalContextFactory; import org.wildfly.clustering.web.cache.sso.AuthenticationEntry; import org.wildfly.clustering.web.cache.sso.CompositeSSO; import org.wildfly.clustering.web.cache.sso.SSOFactory; import org.wildfly.clustering.web.cache.sso.SessionsFactory; import org.wildfly.clustering.web.infinispan.logging.InfinispanWebLogger; import org.wildfly.clustering.web.sso.SSO; import org.wildfly.clustering.web.sso.Sessions; /** * @author Paul Ferraro */ public class InfinispanSSOFactory<AV, SV, A, D, S, L> implements SSOFactory<Map.Entry<A, AtomicReference<L>>, SV, A, D, S, L> { private final SessionsFactory<SV, D, S> sessionsFactory; private final Cache<AuthenticationKey, AuthenticationEntry<AV, L>> findCache; private final Cache<AuthenticationKey, AuthenticationEntry<AV, L>> writeCache; private final Marshaller<A, AV> marshaller; private final LocalContextFactory<L> localContextFactory; public InfinispanSSOFactory(InfinispanConfiguration configuration, Marshaller<A, AV> marshaller, LocalContextFactory<L> localContextFactory, SessionsFactory<SV, D, S> sessionsFactory) { this.writeCache = configuration.getWriteOnlyCache(); this.findCache = configuration.getReadForUpdateCache(); this.marshaller = marshaller; this.localContextFactory = localContextFactory; this.sessionsFactory = sessionsFactory; } @Override public SSO<A, D, S, L> createSSO(String id, Map.Entry<Map.Entry<A, AtomicReference<L>>, SV> value) { Map.Entry<A, AtomicReference<L>> authenticationEntry = value.getKey(); Sessions<D, S> sessions = this.sessionsFactory.createSessions(id, value.getValue()); return new CompositeSSO<>(id, authenticationEntry.getKey(), sessions, authenticationEntry.getValue(), this.localContextFactory, this); } @Override public Map.Entry<Map.Entry<A, AtomicReference<L>>, SV> createValue(String id, A authentication) { try { AuthenticationEntry<AV, L> entry = new AuthenticationEntry<>(this.marshaller.write(authentication)); this.writeCache.put(new AuthenticationKey(id), entry); SV sessions = this.sessionsFactory.createValue(id, null); return new AbstractMap.SimpleImmutableEntry<>(new AbstractMap.SimpleImmutableEntry<>(authentication, entry.getLocalContext()), sessions); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public Map.Entry<Map.Entry<A, AtomicReference<L>>, SV> findValue(String id) { AuthenticationEntry<AV, L> entry = this.findCache.get(new AuthenticationKey(id)); if (entry != null) { SV sessions = this.sessionsFactory.findValue(id); if (sessions != null) { try { A authentication = this.marshaller.read(entry.getAuthentication()); return new AbstractMap.SimpleImmutableEntry<>(new AbstractMap.SimpleImmutableEntry<>(authentication, entry.getLocalContext()), sessions); } catch (IOException e) { InfinispanWebLogger.ROOT_LOGGER.failedToActivateAuthentication(e, id); this.remove(id); } } } return null; } @Override public boolean remove(String id) { this.writeCache.remove(new AuthenticationKey(id)); this.sessionsFactory.remove(id); return true; } @Override public SessionsFactory<SV, D, S> getSessionsFactory() { return this.sessionsFactory; } }
4,979
44.272727
189
java
null
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/sso/InfinispanSSOManagerFactoryConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.sso; import org.wildfly.clustering.ee.infinispan.InfinispanConfiguration; import org.wildfly.clustering.infinispan.affinity.KeyAffinityServiceFactory; /** * Configuration for an SSO manager factory. * @author Paul Ferraro */ public interface InfinispanSSOManagerFactoryConfiguration extends InfinispanConfiguration { KeyAffinityServiceFactory getKeyAffinityServiceFactory(); }
1,456
40.628571
91
java
null
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/sso/AuthenticationKey.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.sso; import org.wildfly.clustering.ee.infinispan.GroupedKey; /** * Cache key for the authentication cache entry. * @author Paul Ferraro */ public class AuthenticationKey extends GroupedKey<String> { public AuthenticationKey(String id) { super(id); } }
1,344
35.351351
70
java
null
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/sso/InfinispanSSOManagerFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.sso; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.wildfly.clustering.ee.cache.IdentifierFactory; import org.wildfly.clustering.ee.cache.tx.TransactionBatch; import org.wildfly.clustering.ee.infinispan.affinity.AffinityIdentifierFactory; import org.wildfly.clustering.marshalling.spi.ByteBufferMarshalledValueFactory; import org.wildfly.clustering.marshalling.spi.ByteBufferMarshaller; import org.wildfly.clustering.marshalling.spi.MarshalledValue; import org.wildfly.clustering.marshalling.spi.MarshalledValueMarshaller; import org.wildfly.clustering.marshalling.spi.Marshaller; import org.wildfly.clustering.web.cache.sso.CompositeSSOManager; import org.wildfly.clustering.web.cache.sso.SSOFactory; import org.wildfly.clustering.web.cache.sso.SessionsFactory; import org.wildfly.clustering.web.infinispan.sso.coarse.CoarseSessionsFactory; import org.wildfly.clustering.web.sso.SSOManager; import org.wildfly.clustering.web.sso.SSOManagerConfiguration; import org.wildfly.clustering.web.sso.SSOManagerFactory; public class InfinispanSSOManagerFactory<A, D, S> implements SSOManagerFactory<A, D, S, TransactionBatch> { private final InfinispanSSOManagerFactoryConfiguration configuration; public InfinispanSSOManagerFactory(InfinispanSSOManagerFactoryConfiguration configuration) { this.configuration = configuration; } @Override public <L> SSOManager<A, D, S, L, TransactionBatch> createSSOManager(SSOManagerConfiguration<L> configuration) { SessionsFactory<Map<D, S>, D, S> sessionsFactory = new CoarseSessionsFactory<>(this.configuration); Marshaller<A, MarshalledValue<A, ByteBufferMarshaller>> marshaller = new MarshalledValueMarshaller<>(new ByteBufferMarshalledValueFactory(configuration.getMarshaller())); SSOFactory<Map.Entry<A, AtomicReference<L>>, Map<D, S>, A, D, S, L> factory = new InfinispanSSOFactory<>(this.configuration, marshaller, configuration.getLocalContextFactory(), sessionsFactory); IdentifierFactory<String> idFactory = new AffinityIdentifierFactory<>(configuration.getIdentifierFactory(), this.configuration.getCache(), this.configuration.getKeyAffinityServiceFactory()); return new CompositeSSOManager<>(factory, idFactory, this.configuration.getBatcher()); } }
3,377
55.3
202
java
null
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/sso/coarse/SessionsFilter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.infinispan.sso.coarse; import java.util.Map; import java.util.function.Function; import java.util.function.Predicate; /** * Filter/mapper that handles filtering and casting for cache entries containing SSO sessions. * @author Paul Ferraro */ public class SessionsFilter<D, S> implements Predicate<Map.Entry<?, ?>>, Function<Map.Entry<?, ?>, Map.Entry<CoarseSessionsKey, Map<D, S>>> { @SuppressWarnings("unchecked") @Override public Map.Entry<CoarseSessionsKey, Map<D, S>> apply(Map.Entry<?, ?> entry) { return (Map.Entry<CoarseSessionsKey, Map<D, S>>) entry; } @Override public boolean test(Map.Entry<?, ?> entry) { return (entry.getKey() instanceof CoarseSessionsKey); } }
1,784
37.804348
141
java