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/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/sso/coarse/CoarseSessionsKeyFormatter.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.infinispan.sso.coarse;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.spi.Formatter;
import org.wildfly.clustering.web.infinispan.SessionKeyFormatter;
/**
* Formatter for {@link CoarseSessionsKey}.
* @author Paul Ferraro
*/
@MetaInfServices(Formatter.class)
public class CoarseSessionsKeyFormatter extends SessionKeyFormatter<CoarseSessionsKey> {
public CoarseSessionsKeyFormatter() {
super(CoarseSessionsKey.class, CoarseSessionsKey::new);
}
}
| 1,557
| 37.95
| 88
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/sso/coarse/CoarseSessionsFactory.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.AbstractMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
import org.infinispan.Cache;
import org.wildfly.clustering.ee.Mutator;
import org.wildfly.clustering.ee.infinispan.CacheEntryMutator;
import org.wildfly.clustering.ee.infinispan.InfinispanConfiguration;
import org.wildfly.clustering.web.cache.sso.SessionsFactory;
import org.wildfly.clustering.web.cache.sso.coarse.CoarseSessions;
import org.wildfly.clustering.web.cache.sso.coarse.SessionFilter;
import org.wildfly.clustering.web.sso.Sessions;
/**
* @author Paul Ferraro
*/
public class CoarseSessionsFactory<D, S> implements SessionsFactory<Map<D, S>, D, S> {
private final SessionsFilter<D, S> filter = new SessionsFilter<>();
private final Cache<CoarseSessionsKey, Map<D, S>> cache;
private final Cache<CoarseSessionsKey, Map<D, S>> createCache;
public CoarseSessionsFactory(InfinispanConfiguration configuration) {
this.cache = configuration.getCache();
this.createCache = configuration.getWriteOnlyCache();
}
@Override
public Sessions<D, S> createSessions(String ssoId, Map<D, S> value) {
CoarseSessionsKey key = new CoarseSessionsKey(ssoId);
Mutator mutator = new CacheEntryMutator<>(this.cache, key, value);
return new CoarseSessions<>(value, mutator);
}
@Override
public Map<D, S> createValue(String id, Void context) {
Map<D, S> sessions = new ConcurrentHashMap<>();
this.createCache.put(new CoarseSessionsKey(id), sessions);
return sessions;
}
@Override
public Map<D, S> findValue(String id) {
return this.cache.get(new CoarseSessionsKey(id));
}
@Override
public Map.Entry<String, Map<D, S>> findEntryContaining(S session) {
SessionFilter<CoarseSessionsKey, D, S> filter = new SessionFilter<>(session);
// Erase type to handle compilation issues with generics
// Our filter will handle type safety and casting
@SuppressWarnings("rawtypes")
Cache cache = this.cache;
try (Stream<Map.Entry<?, ?>> stream = cache.entrySet().stream()) {
Map.Entry<CoarseSessionsKey, Map<D, S>> entry = stream.filter(this.filter).map(this.filter).filter(filter).findAny().orElse(null);
return (entry != null) ? new AbstractMap.SimpleImmutableEntry<>(entry.getKey().getId(), entry.getValue()) : null;
}
}
@Override
public boolean remove(String id) {
return this.cache.getAdvancedCache().remove(new CoarseSessionsKey(id)) != null;
}
}
| 3,687
| 39.977778
| 142
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/sso/coarse/CoarseSessionsKey.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.infinispan.sso.coarse;
import org.wildfly.clustering.ee.infinispan.GroupedKey;
/**
* @author Paul Ferraro
*/
public class CoarseSessionsKey extends GroupedKey<String> {
public CoarseSessionsKey(String id) {
super(id);
}
}
| 1,302
| 35.194444
| 70
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/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.infinispan.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,950
| 43.340909
| 112
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/logging/InfinispanWebLogger.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.logging;
import static org.jboss.logging.Logger.Level.DEBUG;
import static org.jboss.logging.Logger.Level.WARN;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
/**
* InfinispanWebLogger
*
* logging id range: 10320 - 10329
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@MessageLogger(projectCode = "WFLYCLWEBINF", length = 4)
public interface InfinispanWebLogger extends BasicLogger {
String ROOT_LOGGER_CATEGORY = "org.wildfly.clustering.web.infinispan";
InfinispanWebLogger ROOT_LOGGER = Logger.getMessageLogger(InfinispanWebLogger.class, ROOT_LOGGER_CATEGORY);
@LogMessage(level = WARN)
@Message(id = 1, value = "Failed to passivate attributes of session %s")
void failedToPassivateSession(@Cause Throwable cause, String sessionId);
@LogMessage(level = WARN)
@Message(id = 2, value = "Failed to passivate attribute %2$s of session %1$s")
void failedToPassivateSessionAttribute(@Cause Throwable cause, String sessionId, String attribute);
@Message(id = 3, value = "Session %s is not valid")
IllegalStateException invalidSession(String sessionId);
@LogMessage(level = WARN)
@Message(id = 4, value = "Failed to expire session %s")
void failedToExpireSession(@Cause Throwable cause, String sessionId);
@LogMessage(level = DEBUG)
@Message(id = 5, value = "Failed to cancel expiration/passivation of session %s on primary owner.")
void failedToCancelSession(@Cause Throwable cause, String sessionId);
@LogMessage(level = DEBUG)
@Message(id = 6, value = "Failed to schedule expiration/passivation of session %s on primary owner.")
void failedToScheduleSession(@Cause Throwable cause, 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);
@LogMessage(level = WARN)
@Message(id = 12, value = "Disabling eviction for cache '%s'. Web session passivation should be configured via <max-active-sessions/> in jboss-web.xml.")
void evictionDisabled(String cacheName);
@LogMessage(level = WARN)
@Message(id = 13, value = "Disabling expiration for cache '%s'. Web session expiration should be configured per \u00A77.5 of the servlet specification.")
void expirationDisabled(String cacheName);
}
| 4,460
| 44.989691
| 157
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/InfinispanSessionManager.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 java.time.Duration;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.PersistenceConfiguration;
import org.infinispan.configuration.cache.StoreConfiguration;
import org.infinispan.context.Flag;
import org.wildfly.clustering.Registrar;
import org.wildfly.clustering.Registration;
import org.wildfly.clustering.ee.Batcher;
import org.wildfly.clustering.ee.Key;
import org.wildfly.clustering.ee.Scheduler;
import org.wildfly.clustering.ee.cache.CacheProperties;
import org.wildfly.clustering.ee.cache.IdentifierFactory;
import org.wildfly.clustering.ee.cache.tx.TransactionBatch;
import org.wildfly.clustering.ee.expiration.Expiration;
import org.wildfly.clustering.ee.expiration.ExpirationMetaData;
import org.wildfly.clustering.infinispan.distribution.CacheLocality;
import org.wildfly.clustering.infinispan.distribution.Locality;
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.infinispan.logging.InfinispanWebLogger;
import org.wildfly.clustering.web.session.ImmutableSession;
import org.wildfly.clustering.web.session.Session;
import org.wildfly.clustering.web.session.SessionManager;
/**
* Generic 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 InfinispanSessionManager<SC, MV, AV, LC> implements SessionManager<LC, TransactionBatch> {
private final Consumer<ImmutableSession> expirationListener;
private final Batcher<TransactionBatch> batcher;
private final Cache<Key<String>, ?> cache;
private final CacheProperties properties;
private final SessionFactory<SC, MV, AV, LC> factory;
private final IdentifierFactory<String> identifierFactory;
private final Scheduler<String, ExpirationMetaData> expirationScheduler;
private final SC context;
private final Runnable startTask;
private final Consumer<ImmutableSession> closeTask;
private final Registrar<SessionManager<LC, TransactionBatch>> registrar;
private final Expiration expiration;
private volatile Registration registration;
public InfinispanSessionManager(SessionFactory<SC, MV, AV, LC> factory, InfinispanSessionManagerConfiguration<SC, LC> configuration) {
this.factory = factory;
this.cache = configuration.getCache();
this.properties = configuration.getCacheProperties();
this.expirationListener = configuration.getExpirationListener();
this.identifierFactory = configuration.getIdentifierFactory();
this.batcher = configuration.getBatcher();
this.expirationScheduler = configuration.getExpirationScheduler();
this.context = configuration.getServletContext();
this.registrar = configuration.getRegistrar();
this.startTask = configuration.getStartTask();
this.expiration = configuration;
this.closeTask = new Consumer<>() {
@Override
public void accept(ImmutableSession session) {
if (session.isValid()) {
configuration.getExpirationScheduler().schedule(session.getId(), session.getMetaData());
}
}
};
}
@Override
public void start() {
this.registration = this.registrar.register(this);
this.identifierFactory.start();
this.startTask.run();
}
@Override
public void stop() {
if (!this.properties.isPersistent()) {
PersistenceConfiguration persistence = this.cache.getCacheConfiguration().persistence();
// Don't passivate sessions on stop if we will purge the store on startup
if (persistence.passivation() && !persistence.stores().stream().allMatch(StoreConfiguration::purgeOnStartup)) {
try (Stream<Key<String>> stream = this.cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL, Flag.SKIP_CACHE_LOAD, Flag.SKIP_LOCKING).keySet().stream()) {
stream.filter(SessionCreationMetaDataKeyFilter.INSTANCE).forEach(this.cache::evict);
}
}
}
this.identifierFactory.stop();
this.registration.close();
}
@Override
public Duration getStopTimeout() {
return Duration.ofMillis(this.cache.getCacheConfiguration().transaction().cacheStopTimeout());
}
@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> value = this.factory.findValue(id);
if (value == null) {
InfinispanWebLogger.ROOT_LOGGER.tracef("Session %s not found", id);
return null;
}
ImmutableSession session = this.factory.createImmutableSession(id, value);
if (session.getMetaData().isExpired()) {
InfinispanWebLogger.ROOT_LOGGER.tracef("Session %s was found, but has expired", id);
this.expirationListener.accept(session);
this.factory.remove(id);
return null;
}
this.expirationScheduler.cancel(id);
return new ValidSession<>(this.factory.createSession(id, value, 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> value = this.factory.findValue(id);
return (value != null) ? new SimpleImmutableSession(this.factory.createImmutableSession(id, value)) : null;
}
@Override
public Set<String> getActiveSessions() {
// Omit remote sessions (i.e. when using DIST mode) as well as passivated sessions
return this.getSessions(Flag.CACHE_MODE_LOCAL, Flag.SKIP_CACHE_LOAD);
}
@Override
public Set<String> getLocalSessions() {
// Omit remote sessions (i.e. when using DIST mode)
return this.getSessions(Flag.CACHE_MODE_LOCAL);
}
private Set<String> getSessions(Flag... flags) {
Locality locality = new CacheLocality(this.cache);
try (Stream<Key<String>> keys = this.cache.getAdvancedCache().withFlags(flags).keySet().stream()) {
return keys.filter(SessionCreationMetaDataKeyFilter.INSTANCE.and(key -> locality.isLocal(key))).map(key -> key.getId()).collect(Collectors.toSet());
}
}
@Override
public long getActiveSessionCount() {
return this.getActiveSessions().size();
}
}
| 8,695
| 42.263682
| 174
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/InfinispanSessionAttributesFactoryConfiguration.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.session;
import java.util.function.Function;
import org.wildfly.clustering.ee.infinispan.InfinispanConfiguration;
import org.wildfly.clustering.web.cache.session.SessionAttributeActivationNotifier;
import org.wildfly.clustering.web.cache.session.SessionAttributesFactoryConfiguration;
/**
* @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
* @author Paul Ferraro
*/
public interface InfinispanSessionAttributesFactoryConfiguration<S, C, L, V, SV> extends InfinispanConfiguration, SessionAttributesFactoryConfiguration<S, C, L, V, SV> {
Function<String, SessionAttributeActivationNotifier> getActivationNotifierFactory();
}
| 1,909
| 43.418605
| 169
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/InfinispanSessionManagerFactory.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 java.time.Duration;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import org.infinispan.Cache;
import org.wildfly.clustering.Registrar;
import org.wildfly.clustering.Registration;
import org.wildfly.clustering.ee.Key;
import org.wildfly.clustering.ee.cache.CacheProperties;
import org.wildfly.clustering.ee.cache.ConcurrentManager;
import org.wildfly.clustering.ee.cache.IdentifierFactory;
import org.wildfly.clustering.ee.cache.SimpleManager;
import org.wildfly.clustering.ee.cache.tx.TransactionBatch;
import org.wildfly.clustering.ee.expiration.ExpirationMetaData;
import org.wildfly.clustering.ee.infinispan.InfinispanConfiguration;
import org.wildfly.clustering.ee.infinispan.PrimaryOwnerLocator;
import org.wildfly.clustering.ee.infinispan.affinity.AffinityIdentifierFactory;
import org.wildfly.clustering.ee.infinispan.expiration.ScheduleWithExpirationMetaDataCommandFactory;
import org.wildfly.clustering.ee.infinispan.scheduler.CacheEntryScheduler;
import org.wildfly.clustering.ee.infinispan.scheduler.PrimaryOwnerScheduler;
import org.wildfly.clustering.ee.infinispan.scheduler.ScheduleLocalKeysTask;
import org.wildfly.clustering.ee.infinispan.scheduler.ScheduleWithTransientMetaDataCommand;
import org.wildfly.clustering.ee.infinispan.scheduler.SchedulerTopologyChangeListener;
import org.wildfly.clustering.group.Group;
import org.wildfly.clustering.infinispan.affinity.KeyAffinityServiceFactory;
import org.wildfly.clustering.infinispan.distribution.CacheLocality;
import org.wildfly.clustering.infinispan.distribution.Locality;
import org.wildfly.clustering.infinispan.distribution.SimpleLocality;
import org.wildfly.clustering.infinispan.listener.ListenerRegistration;
import org.wildfly.clustering.marshalling.spi.ByteBufferMarshaller;
import org.wildfly.clustering.marshalling.spi.MarshalledValue;
import org.wildfly.clustering.server.dispatcher.CommandDispatcherFactory;
import org.wildfly.clustering.web.cache.session.CompositeSessionFactory;
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.SessionAttributeActivationNotifier;
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.infinispan.session.coarse.CoarseSessionAttributesFactory;
import org.wildfly.clustering.web.infinispan.session.fine.FineSessionAttributesFactory;
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.session.SpecificationProvider;
/**
* 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 InfinispanSessionManagerFactory<S, SC, AL, LC> implements SessionManagerFactory<SC, LC, TransactionBatch>, Runnable {
private final org.wildfly.clustering.ee.Scheduler<String, ExpirationMetaData> scheduler;
private final SpecificationProvider<S, SC, AL> provider;
private final KeyAffinityServiceFactory affinityFactory;
private final SessionFactory<SC, CompositeSessionMetaDataEntry<LC>, ?, LC> factory;
private final BiConsumer<Locality, Locality> scheduleTask;
private final ListenerRegistration schedulerListenerRegistration;
private final InfinispanConfiguration configuration;
private final ExpiredSessionRemover<SC, ?, ?, LC> remover;
private final SessionAttributeActivationNotifierFactory<S, SC, AL, LC, TransactionBatch> notifierFactory;
public InfinispanSessionManagerFactory(InfinispanSessionManagerFactoryConfiguration<S, SC, AL, LC> config) {
this.configuration = config;
this.affinityFactory = config.getKeyAffinityServiceFactory();
this.provider = config.getSpecificationProvider();
this.notifierFactory = new SessionAttributeActivationNotifierFactory<>(this.provider);
CacheProperties properties = config.getCacheProperties();
SessionMetaDataFactory<CompositeSessionMetaDataEntry<LC>> metaDataFactory = properties.isLockOnRead() ? new LockOnReadInfinispanSessionMetaDataFactory<>(config) : new BulkReadInfinispanSessionMetaDataFactory<>(config);
this.factory = new CompositeSessionFactory<>(metaDataFactory, this.createSessionAttributesFactory(config), config.getLocalContextFactory());
this.remover = new ExpiredSessionRemover<>(this.factory);
Cache<Key<String>, ?> cache = config.getCache();
CacheEntryScheduler<String, ExpirationMetaData> localScheduler = new SessionExpirationScheduler<>(config.getBatcher(), this.factory.getMetaDataFactory(), this.remover, Duration.ofMillis(cache.getCacheConfiguration().transaction().cacheStopTimeout()));
CommandDispatcherFactory dispatcherFactory = config.getCommandDispatcherFactory();
Group group = dispatcherFactory.getGroup();
this.scheduler = group.isSingleton() ? localScheduler : new PrimaryOwnerScheduler<>(dispatcherFactory, cache.getName(), localScheduler, new PrimaryOwnerLocator<>(cache, config.getMemberFactory()), SessionCreationMetaDataKey::new, properties.isTransactional() ? new ScheduleWithExpirationMetaDataCommandFactory<>() : ScheduleWithTransientMetaDataCommand::new);
this.scheduleTask = new ScheduleLocalKeysTask<>(cache, SessionCreationMetaDataKeyFilter.INSTANCE, localScheduler);
this.schedulerListenerRegistration = new SchedulerTopologyChangeListener<>(cache, localScheduler, this.scheduleTask).register();
}
@Override
public void run() {
this.scheduleTask.accept(new SimpleLocality(false), new CacheLocality(this.configuration.getCache()));
}
@Override
public SessionManager<LC, TransactionBatch> createSessionManager(final SessionManagerConfiguration<SC> configuration) {
IdentifierFactory<String> identifierFactory = new AffinityIdentifierFactory<>(configuration.getIdentifierFactory(), this.configuration.getCache(), this.affinityFactory);
Registrar<SessionManager<LC, TransactionBatch>> registrar = manager -> {
Registration contextRegistration = this.notifierFactory.register(Map.entry(configuration.getServletContext(), manager));
Registration expirationRegistration = this.remover.register(configuration.getExpirationListener());
return () -> {
expirationRegistration.close();
contextRegistration.close();
};
};
org.wildfly.clustering.ee.Scheduler<String, ExpirationMetaData> scheduler = this.scheduler;
InfinispanSessionManagerConfiguration<SC, LC> config = new AbstractInfinispanSessionManagerConfiguration<>(configuration, identifierFactory, this.configuration) {
@Override
public org.wildfly.clustering.ee.Scheduler<String, ExpirationMetaData> getExpirationScheduler() {
return scheduler;
}
@Override
public Runnable getStartTask() {
return InfinispanSessionManagerFactory.this;
}
@Override
public Registrar<SessionManager<LC, TransactionBatch>> getRegistrar() {
return registrar;
}
};
return new ConcurrentSessionManager<>(new InfinispanSessionManager<>(this.factory, config), this.configuration.getCacheProperties().isTransactional() ? SimpleManager::new : ConcurrentManager::new);
}
private SessionAttributesFactory<SC, ?> createSessionAttributesFactory(InfinispanSessionManagerFactoryConfiguration<S, SC, AL, LC> configuration) {
switch (configuration.getAttributePersistenceStrategy()) {
case FINE: {
return new FineSessionAttributesFactory<>(new InfinispanMarshalledValueSessionAttributesFactoryConfiguration<>(configuration, this.notifierFactory));
}
case COARSE: {
return new CoarseSessionAttributesFactory<>(new InfinispanMarshalledValueSessionAttributesFactoryConfiguration<>(configuration, this.notifierFactory));
}
default: {
// Impossible
throw new IllegalStateException();
}
}
}
@Override
public void close() {
this.schedulerListenerRegistration.close();
this.scheduler.close();
this.factory.close();
}
private abstract static class AbstractInfinispanSessionManagerConfiguration<SC, LC> extends DelegatingSessionManagerConfiguration<SC> implements InfinispanSessionManagerConfiguration<SC, LC> {
private final InfinispanConfiguration configuration;
private final IdentifierFactory<String> identifierFactory;
AbstractInfinispanSessionManagerConfiguration(SessionManagerConfiguration<SC> managerConfiguration, IdentifierFactory<String> identifierFactory, InfinispanConfiguration configuration) {
super(managerConfiguration);
this.identifierFactory = identifierFactory;
this.configuration = configuration;
}
@Override
public IdentifierFactory<String> getIdentifierFactory() {
return this.identifierFactory;
}
@Override
public <K, V> Cache<K, V> getCache() {
return this.configuration.getCache();
}
}
private static class InfinispanMarshalledValueSessionAttributesFactoryConfiguration<S, SC, AL, V, LC> extends MarshalledValueSessionAttributesFactoryConfiguration<S, SC, AL, V, LC> implements InfinispanSessionAttributesFactoryConfiguration<S, SC, AL, V, MarshalledValue<V, ByteBufferMarshaller>> {
private final InfinispanSessionManagerFactoryConfiguration<S, SC, AL, LC> configuration;
private final Function<String, SessionAttributeActivationNotifier> notifierFactory;
InfinispanMarshalledValueSessionAttributesFactoryConfiguration(InfinispanSessionManagerFactoryConfiguration<S, SC, AL, LC> configuration, Function<String, SessionAttributeActivationNotifier> notifierFactory) {
super(configuration);
this.configuration = configuration;
this.notifierFactory = notifierFactory;
}
@Override
public <CK, CV> Cache<CK, CV> getCache() {
return this.configuration.getCache();
}
@Override
public Function<String, SessionAttributeActivationNotifier> getActivationNotifierFactory() {
return this.notifierFactory;
}
}
}
| 12,190
| 56.504717
| 367
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/InfinispanSessionManagementConfiguration.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.session;
import org.wildfly.clustering.ee.infinispan.InfinispanCacheConfiguration;
import org.wildfly.clustering.web.session.DistributableSessionManagementConfiguration;
/**
* Configuration of an Infinispan session management provider.
* @author Paul Ferraro
*/
public interface InfinispanSessionManagementConfiguration<M> extends DistributableSessionManagementConfiguration<M>, InfinispanCacheConfiguration {
}
| 1,487
| 42.764706
| 147
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/SessionCreationMetaDataKeyFormatter.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.session;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.spi.Formatter;
import org.wildfly.clustering.web.infinispan.SessionKeyFormatter;
/**
* Formatter for a {@link SessionCreationMetaDataKey}.
* @author Paul Ferraro
*/
@MetaInfServices(Formatter.class)
public class SessionCreationMetaDataKeyFormatter extends SessionKeyFormatter<SessionCreationMetaDataKey> {
public SessionCreationMetaDataKeyFormatter() {
super(SessionCreationMetaDataKey.class, SessionCreationMetaDataKey::new);
}
}
| 1,610
| 39.275
| 106
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/ExpiredSessionRemover.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 java.util.Collection;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Consumer;
import org.wildfly.clustering.Registrar;
import org.wildfly.clustering.Registration;
import org.wildfly.clustering.ee.Remover;
import org.wildfly.clustering.web.cache.session.SessionFactory;
import org.wildfly.clustering.web.infinispan.logging.InfinispanWebLogger;
import org.wildfly.clustering.web.session.ImmutableSession;
import org.wildfly.clustering.web.session.ImmutableSessionAttributes;
import org.wildfly.clustering.web.session.ImmutableSessionMetaData;
/**
* Session remover that removes a session if and only if it is expired.
* @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 ExpiredSessionRemover<SC, MV, AV, LC> implements Remover<String>, Registrar<Consumer<ImmutableSession>> {
private final SessionFactory<SC, MV, AV, LC> factory;
private final Collection<Consumer<ImmutableSession>> listeners = new CopyOnWriteArraySet<>();
public ExpiredSessionRemover(SessionFactory<SC, MV, AV, LC> factory) {
this.factory = factory;
}
@Override
public boolean remove(String id) {
MV metaDataValue = this.factory.getMetaDataFactory().tryValue(id);
if (metaDataValue != null) {
ImmutableSessionMetaData metaData = this.factory.getMetaDataFactory().createImmutableSessionMetaData(id, metaDataValue);
if (metaData.isExpired()) {
AV attributesValue = this.factory.getAttributesFactory().findValue(id);
if (attributesValue != null) {
ImmutableSessionAttributes attributes = this.factory.getAttributesFactory().createImmutableSessionAttributes(id, attributesValue);
ImmutableSession session = this.factory.createImmutableSession(id, metaData, attributes);
InfinispanWebLogger.ROOT_LOGGER.tracef("Session %s has expired.", id);
for (Consumer<ImmutableSession> listener : this.listeners) {
listener.accept(session);
}
}
return this.factory.remove(id);
}
InfinispanWebLogger.ROOT_LOGGER.tracef("Session %s is not yet expired.", id);
} else {
InfinispanWebLogger.ROOT_LOGGER.tracef("Session %s was not found or is currently in use.", id);
}
return false;
}
@Override
public Registration register(Consumer<ImmutableSession> listener) {
this.listeners.add(listener);
return () -> this.listeners.remove(listener);
}
}
| 3,823
| 44.52381
| 150
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/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.infinispan.session;
import org.wildfly.clustering.ee.infinispan.GroupedKey;
/**
* Cache key for the session access meta data entry.
* @author Paul Ferraro
*/
public class SessionAccessMetaDataKey extends GroupedKey<String> {
public SessionAccessMetaDataKey(String id) {
super(id);
}
}
| 1,366
| 35.945946
| 70
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/AbstractInfinispanSessionMetaDataFactory.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.infinispan.session;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import jakarta.transaction.SystemException;
import org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.context.Flag;
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.infinispan.InfinispanConfiguration;
import org.wildfly.clustering.ee.infinispan.InfinispanMutatorFactory;
import org.wildfly.clustering.infinispan.listener.ListenerRegistration;
import org.wildfly.clustering.infinispan.listener.PostPassivateBlockingListener;
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;
/**
* Abstract {@link org.wildfly.clustering.web.cache.session.SessionMetaDataFactory} implementation that stores session meta-data in 2 distinct cache entries:
* <dl>
* <dt>Creation meta-data</dt>
* <dd>Meta data that is usually determined on session creation, and is rarely or never updated</dd>
* <dt>Access meta-data</dt>
* <dd>Meta data that is updated often, typically every request</dd>
* </dl>
* @author Paul Ferraro
*/
public abstract class AbstractInfinispanSessionMetaDataFactory<L> implements SessionMetaDataFactory<CompositeSessionMetaDataEntry<L>>, BiFunction<String, Set<Flag>, CompositeSessionMetaDataEntry<L>> {
private static final Set<Flag> TRY_LOCK_FLAGS = EnumSet.of(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT, Flag.FAIL_SILENTLY);
private final Cache<Key<String>, Object> writeOnlyCache;
private final Cache<Key<String>, Object> silentWriteCache;
private final Cache<SessionCreationMetaDataKey, SessionCreationMetaDataEntry<L>> creationMetaDataCache;
private final Cache<SessionCreationMetaDataKey, SessionCreationMetaDataEntry<L>> creationMetaDataTryLockCache;
private final MutatorFactory<SessionCreationMetaDataKey, SessionCreationMetaDataEntry<L>> creationMetaDataMutatorFactory;
private final Cache<SessionAccessMetaDataKey, SessionAccessMetaData> accessMetaDataCache;
private final MutatorFactory<SessionAccessMetaDataKey, SessionAccessMetaData> accessMetaDataMutatorFactory;
private final CacheProperties properties;
private final ListenerRegistration evictListenerRegistration;
public AbstractInfinispanSessionMetaDataFactory(InfinispanConfiguration configuration) {
this.writeOnlyCache = configuration.getWriteOnlyCache();
this.silentWriteCache = configuration.getSilentWriteCache();
this.creationMetaDataTryLockCache = configuration.getTryLockCache();
this.properties = configuration.getCacheProperties();
this.creationMetaDataCache = configuration.getCache();
this.creationMetaDataMutatorFactory = new InfinispanMutatorFactory<>(this.creationMetaDataCache, this.properties);
this.accessMetaDataCache = configuration.getCache();
this.accessMetaDataMutatorFactory = new InfinispanMutatorFactory<>(this.accessMetaDataCache, this.properties);
this.evictListenerRegistration = new PostPassivateBlockingListener<>(this.creationMetaDataCache, this::cascadeEvict).register(SessionCreationMetaDataKey.class);
}
@Override
public void close() {
this.evictListenerRegistration.close();
}
@Override
public CompositeSessionMetaDataEntry<L> createValue(String id, SessionCreationMetaData creationMetaData) {
Map<Key<String>, Object> entries = new HashMap<>(3);
SessionCreationMetaDataEntry<L> creationMetaDataEntry = new SessionCreationMetaDataEntry<>(creationMetaData);
entries.put(new SessionCreationMetaDataKey(id), creationMetaDataEntry);
SessionAccessMetaData accessMetaData = new SimpleSessionAccessMetaData();
entries.put(new SessionAccessMetaDataKey(id), accessMetaData);
this.writeOnlyCache.putAll(entries);
return new CompositeSessionMetaDataEntry<>(creationMetaDataEntry, accessMetaData);
}
@Override
public CompositeSessionMetaDataEntry<L> findValue(String id) {
return this.apply(id, EnumSet.noneOf(Flag.class));
}
@Override
public CompositeSessionMetaDataEntry<L> tryValue(String id) {
return this.apply(id, TRY_LOCK_FLAGS);
}
@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) {
SessionCreationMetaDataKey key = new SessionCreationMetaDataKey(id);
try {
if (!this.properties.isLockOnWrite() || (this.creationMetaDataCache.getAdvancedCache().getTransactionManager().getTransaction() == null) || this.creationMetaDataTryLockCache.getAdvancedCache().lock(key)) {
return delete(this.writeOnlyCache, id);
}
return false;
} catch (SystemException e) {
throw new CacheException(e);
}
}
@Override
public boolean purge(String id) {
return delete(this.silentWriteCache, id);
}
private static boolean delete(Cache<Key<String>, Object> cache, String id) {
cache.remove(new SessionAccessMetaDataKey(id));
cache.remove(new SessionCreationMetaDataKey(id));
return true;
}
void cascadeEvict(SessionCreationMetaDataKey key) {
this.silentWriteCache.evict(new SessionAccessMetaDataKey(key.getId()));
}
}
| 8,644
| 51.078313
| 263
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/SessionAccessMetaDataKeyFormatter.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.session;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.spi.Formatter;
import org.wildfly.clustering.web.infinispan.SessionKeyFormatter;
/**
* Formatter for a {@link SessionAccessMetaDataKey}
* @author Paul Ferraro
*/
@MetaInfServices(Formatter.class)
public class SessionAccessMetaDataKeyFormatter extends SessionKeyFormatter<SessionAccessMetaDataKey> {
public SessionAccessMetaDataKeyFormatter() {
super(SessionAccessMetaDataKey.class, SessionAccessMetaDataKey::new);
}
}
| 1,597
| 38.95
| 102
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/LockOnReadInfinispanSessionMetaDataFactory.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.session;
import java.util.Set;
import org.infinispan.Cache;
import org.infinispan.context.Flag;
import org.wildfly.clustering.ee.infinispan.InfinispanConfiguration;
import org.wildfly.clustering.web.cache.session.CompositeSessionMetaDataEntry;
import org.wildfly.clustering.web.cache.session.SessionAccessMetaData;
import org.wildfly.clustering.web.cache.session.SessionCreationMetaDataEntry;
/**
* {@link org.wildfly.clustering.web.cache.session.SessionMetaDataFactory} implementation for lock-on-read caches.
* @author Paul Ferraro
*/
public class LockOnReadInfinispanSessionMetaDataFactory<L> extends AbstractInfinispanSessionMetaDataFactory<L> {
private final Cache<SessionCreationMetaDataKey, SessionCreationMetaDataEntry<L>> creationMetaDataCache;
private final Cache<SessionAccessMetaDataKey, SessionAccessMetaData> accessMetaDataCache;
public LockOnReadInfinispanSessionMetaDataFactory(InfinispanConfiguration configuration) {
super(configuration);
this.creationMetaDataCache = configuration.getReadForUpdateCache();
this.accessMetaDataCache = configuration.getCache();
}
@Override
public CompositeSessionMetaDataEntry<L> apply(String id, Set<Flag> flags) {
SessionCreationMetaDataEntry<L> creationMetaDataEntry = this.creationMetaDataCache.getAdvancedCache().withFlags(flags).get(new SessionCreationMetaDataKey(id));
if (creationMetaDataEntry != null) {
SessionAccessMetaData accessMetaData = this.accessMetaDataCache.get(new SessionAccessMetaDataKey(id));
if (accessMetaData != null) {
return new CompositeSessionMetaDataEntry<>(creationMetaDataEntry, accessMetaData);
}
if (flags.isEmpty()) {
// Purge orphaned entry
this.purge(id);
}
}
return null;
}
}
| 2,936
| 44.184615
| 167
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/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.infinispan.session;
import org.wildfly.clustering.ee.infinispan.GroupedKey;
/**
* Cache key for the session creation meta data entry.
* @author Paul Ferraro
*/
public class SessionCreationMetaDataKey extends GroupedKey<String> {
public SessionCreationMetaDataKey(String id) {
super(id);
}
}
| 1,372
| 36.108108
| 70
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/BulkReadInfinispanSessionMetaDataFactory.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.infinispan.session;
import java.util.Map;
import java.util.Set;
import org.infinispan.Cache;
import org.infinispan.context.Flag;
import org.wildfly.clustering.ee.Key;
import org.wildfly.clustering.ee.infinispan.InfinispanConfiguration;
import org.wildfly.clustering.web.cache.session.CompositeSessionMetaDataEntry;
import org.wildfly.clustering.web.cache.session.SessionAccessMetaData;
import org.wildfly.clustering.web.cache.session.SessionCreationMetaDataEntry;
/**
* {@link org.wildfly.clustering.web.cache.session.SessionMetaDataFactory} implementation for read-committed and non-transactional caches.
* @author Paul Ferraro
*/
public class BulkReadInfinispanSessionMetaDataFactory<L> extends AbstractInfinispanSessionMetaDataFactory<L> {
private final Cache<Key<String>, Object> cache;
public BulkReadInfinispanSessionMetaDataFactory(InfinispanConfiguration configuration) {
super(configuration);
this.cache = configuration.getCache();
}
@Override
public CompositeSessionMetaDataEntry<L> apply(String id, Set<Flag> flags) {
SessionCreationMetaDataKey creationMetaDataKey = new SessionCreationMetaDataKey(id);
SessionAccessMetaDataKey accessMetaDataKey = new SessionAccessMetaDataKey(id);
Set<Key<String>> keys = Set.of(creationMetaDataKey, accessMetaDataKey);
// Use bulk read
Map<Key<String>, Object> entries = this.cache.getAdvancedCache().withFlags(flags).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);
}
if (flags.isEmpty() && ((creationMetaDataEntry != null) || (accessMetaData != null))) {
this.purge(id);
}
return null;
}
}
| 3,139
| 45.176471
| 138
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/SessionExpirationScheduler.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 java.time.Duration;
import java.util.function.Predicate;
import org.wildfly.clustering.ee.Batch;
import org.wildfly.clustering.ee.Batcher;
import org.wildfly.clustering.ee.Remover;
import org.wildfly.clustering.ee.cache.scheduler.LocalScheduler;
import org.wildfly.clustering.ee.cache.scheduler.SortedScheduledEntries;
import org.wildfly.clustering.ee.cache.tx.TransactionBatch;
import org.wildfly.clustering.ee.infinispan.expiration.AbstractExpirationScheduler;
import org.wildfly.clustering.web.cache.session.ImmutableSessionMetaDataFactory;
import org.wildfly.clustering.web.infinispan.logging.InfinispanWebLogger;
import org.wildfly.clustering.web.session.ImmutableSessionMetaData;
/**
* Session expiration scheduler that eagerly expires sessions as soon as they are eligible.
* If/When Infinispan implements expiration notifications (ISPN-694), this will be obsolete.
* @author Paul Ferraro
* @param <MV> the meta data value type
*/
public class SessionExpirationScheduler<MV> extends AbstractExpirationScheduler<String> {
private final ImmutableSessionMetaDataFactory<MV> metaDataFactory;
public SessionExpirationScheduler(Batcher<TransactionBatch> batcher, ImmutableSessionMetaDataFactory<MV> metaDataFactory, Remover<String> remover, Duration closeTimeout) {
super(new LocalScheduler<>(new SortedScheduledEntries<>(), new SessionRemoveTask(batcher, remover), closeTimeout));
this.metaDataFactory = metaDataFactory;
}
@Override
public void schedule(String sessionId) {
MV value = this.metaDataFactory.findValue(sessionId);
if (value != null) {
ImmutableSessionMetaData metaData = this.metaDataFactory.createImmutableSessionMetaData(sessionId, value);
this.schedule(sessionId, metaData);
}
}
private static class SessionRemoveTask implements Predicate<String> {
private final Batcher<TransactionBatch> batcher;
private final Remover<String> remover;
SessionRemoveTask(Batcher<TransactionBatch> batcher, Remover<String> remover) {
this.batcher = batcher;
this.remover = remover;
}
@Override
public boolean test(String sessionId) {
InfinispanWebLogger.ROOT_LOGGER.debugf("Expiring web session %s", sessionId);
try (Batch batch = this.batcher.createBatch()) {
try {
this.remover.remove(sessionId);
return true;
} catch (RuntimeException e) {
batch.discard();
throw e;
}
} catch (RuntimeException e) {
InfinispanWebLogger.ROOT_LOGGER.failedToExpireSession(e, sessionId);
return false;
}
}
}
}
| 3,878
| 42.58427
| 175
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/SessionAttributeActivationNotifierFactory.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.infinispan.session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import org.wildfly.clustering.Registrar;
import org.wildfly.clustering.Registration;
import org.wildfly.clustering.ee.Batch;
import org.wildfly.clustering.web.cache.session.SessionAttributeActivationNotifier;
import org.wildfly.clustering.web.session.HttpSessionActivationListenerProvider;
import org.wildfly.clustering.web.session.Session;
import org.wildfly.clustering.web.session.SessionManager;
import org.wildfly.clustering.web.session.oob.OOBSession;
/**
* Factory for creating a SessionAttributeActivationNotifier for a given session identifier.
* Session activation events will created using OOB sessions.
* @author Paul Ferraro
* @param <S> the HttpSession specification type
* @param <SC> the ServletContext specification type
* @param <AL> the HttpSessionActivationListener specification type
* @param <LC> the local context type
* @param <B> the batch type
*/
public class SessionAttributeActivationNotifierFactory<S, SC, AL, LC, B extends Batch> implements Function<String, SessionAttributeActivationNotifier>, Registrar<Map.Entry<SC, SessionManager<LC, B>>> {
private final Map<SC, SessionManager<LC, B>> contexts = new ConcurrentHashMap<>();
private final HttpSessionActivationListenerProvider<S, SC, AL> provider;
private final Function<AL, Consumer<S>> prePassivateNotifier;
private final Function<AL, Consumer<S>> postActivateNotifier;
public SessionAttributeActivationNotifierFactory(HttpSessionActivationListenerProvider<S, SC, AL> provider) {
this.provider = provider;
this.prePassivateNotifier = provider::prePassivateNotifier;
this.postActivateNotifier = provider::postActivateNotifier;
}
@Override
public Registration register(Map.Entry<SC, SessionManager<LC, B>> entry) {
SC context = entry.getKey();
this.contexts.put(context, entry.getValue());
return () -> this.contexts.remove(context);
}
@Override
public SessionAttributeActivationNotifier apply(String sessionId) {
Map<SC, SessionManager<LC, B>> contexts = this.contexts;
HttpSessionActivationListenerProvider<S, SC, AL> provider = this.provider;
Function<AL, Consumer<S>> prePassivateNotifier = this.prePassivateNotifier;
Function<AL, Consumer<S>> postActivateNotifier = this.postActivateNotifier;
return new SessionAttributeActivationNotifier() {
@Override
public void prePassivate(Object value) {
this.notify(prePassivateNotifier, value);
}
@Override
public void postActivate(Object value) {
this.notify(postActivateNotifier, value);
}
public void notify(Function<AL, Consumer<S>> notifier, Object value) {
Class<AL> listenerClass = provider.getHttpSessionActivationListenerClass();
if (listenerClass.isInstance(value)) {
AL listener = listenerClass.cast(value);
for (Map.Entry<SC, SessionManager<LC, B>> entry : contexts.entrySet()) {
SC context = entry.getKey();
SessionManager<LC, B> manager = entry.getValue();
Session<LC> session = new OOBSession<>(manager, sessionId, null);
notifier.apply(listener).accept(provider.createHttpSession(session, context));
}
}
}
@Override
public void close() {
// Nothing to close
}
};
}
}
| 4,779
| 43.672897
| 201
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/InfinispanSessionManagerConfiguration.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.infinispan.session;
import org.wildfly.clustering.Registrar;
import org.wildfly.clustering.ee.Scheduler;
import org.wildfly.clustering.ee.cache.IdentifierFactory;
import org.wildfly.clustering.ee.cache.tx.TransactionBatch;
import org.wildfly.clustering.ee.infinispan.InfinispanConfiguration;
import org.wildfly.clustering.ee.expiration.ExpirationMetaData;
import org.wildfly.clustering.web.session.SessionManager;
import org.wildfly.clustering.web.session.SessionManagerConfiguration;
/**
* Configuration for an {@link InfinispanSessionManager}.
* @param <SC> the ServletContext specification type
* @param <LC> the local context type
* @author Paul Ferraro
*/
public interface InfinispanSessionManagerConfiguration<SC, LC> extends SessionManagerConfiguration<SC>, InfinispanConfiguration {
@Override
IdentifierFactory<String> getIdentifierFactory();
Scheduler<String, ExpirationMetaData> getExpirationScheduler();
Runnable getStartTask();
Registrar<SessionManager<LC, TransactionBatch>> getRegistrar();
}
| 2,091
| 44.478261
| 129
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/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.infinispan.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.marshalling.protostream.EnumMarshaller;
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));
context.registerMarshaller(new EnumMarshaller<>(SessionCreationMetaDataKeyFilter.class));
}
}
| 2,104
| 45.777778
| 130
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/InfinispanSessionManagerFactoryConfiguration.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.infinispan.session;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.ee.infinispan.InfinispanConfiguration;
import org.wildfly.clustering.infinispan.affinity.KeyAffinityServiceFactory;
import org.wildfly.clustering.server.NodeFactory;
import org.wildfly.clustering.server.dispatcher.CommandDispatcherFactory;
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 InfinispanSessionManagerFactoryConfiguration<S, SC, AL, LC> extends SessionManagerFactoryConfiguration<S, SC, AL, LC>, InfinispanConfiguration {
KeyAffinityServiceFactory getKeyAffinityServiceFactory();
CommandDispatcherFactory getCommandDispatcherFactory();
NodeFactory<Address> getMemberFactory();
}
| 2,051
| 43.608696
| 161
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/SessionCreationMetaDataKeyFilter.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.infinispan.session;
import org.infinispan.util.function.SerializablePredicate;
/**
* Filters a cache for session creation meta data entries.
* @author Paul Ferraro
*/
public enum SessionCreationMetaDataKeyFilter implements SerializablePredicate<Object> {
INSTANCE;
@Override
public boolean test(Object key) {
return key instanceof SessionCreationMetaDataKey;
}
}
| 1,453
| 35.35
| 87
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/fine/SessionAttributeNamesKeyFormatter.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.session.fine;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.spi.Formatter;
import org.wildfly.clustering.web.infinispan.SessionKeyFormatter;
/**
* Formatter for {@link SessionAttributeNamesKey}.
* @author Paul Ferraro
*/
@MetaInfServices(Formatter.class)
public class SessionAttributeNamesKeyFormatter extends SessionKeyFormatter<SessionAttributeNamesKey> {
public SessionAttributeNamesKeyFormatter() {
super(SessionAttributeNamesKey.class, SessionAttributeNamesKey::new);
}
}
| 1,600
| 40.051282
| 102
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/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.infinispan.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,897
| 43.139535
| 126
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/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.infinispan.session.fine;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import org.wildfly.clustering.ee.infinispan.GroupedKey;
/**
* Cache key for session attributes.
* @author Paul Ferraro
*/
public class SessionAttributeKey extends GroupedKey<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 sessionId, UUID attributeId) {
super(sessionId);
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,322
| 34.19697
| 150
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/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.infinispan.session.fine;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Function;
import org.infinispan.Cache;
import org.wildfly.clustering.ee.Immutability;
import org.wildfly.clustering.ee.Key;
import org.wildfly.clustering.ee.MutatorFactory;
import org.wildfly.clustering.ee.cache.CacheProperties;
import org.wildfly.clustering.ee.infinispan.InfinispanMutatorFactory;
import org.wildfly.clustering.infinispan.listener.ListenerRegistration;
import org.wildfly.clustering.infinispan.listener.PostActivateBlockingListener;
import org.wildfly.clustering.infinispan.listener.PostPassivateBlockingListener;
import org.wildfly.clustering.infinispan.listener.PrePassivateBlockingListener;
import org.wildfly.clustering.infinispan.listener.PrePassivateNonBlockingListener;
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.infinispan.logging.InfinispanWebLogger;
import org.wildfly.clustering.web.infinispan.session.InfinispanSessionAttributesFactoryConfiguration;
import org.wildfly.clustering.web.infinispan.session.SessionCreationMetaDataKey;
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 Cache<SessionAttributeNamesKey, Map<String, UUID>> namesCache;
private final Cache<SessionAttributeKey, V> attributeCache;
private final Cache<Key<String>, Object> writeCache;
private final Cache<Key<String>, Object> silentCache;
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;
private final Function<String, SessionAttributeActivationNotifier> notifierFactory;
private final Executor executor;
private final ListenerRegistration evictListenerRegistration;
private final ListenerRegistration evictAttributesListenerRegistration;
private final ListenerRegistration prePassivateListenerRegistration;
private final ListenerRegistration postActivateListenerRegistration;
public FineSessionAttributesFactory(InfinispanSessionAttributesFactoryConfiguration<S, C, L, Object, V> configuration) {
this.namesCache = configuration.getCache();
this.attributeCache = configuration.getCache();
this.writeCache = configuration.getWriteOnlyCache();
this.silentCache = configuration.getSilentWriteCache();
this.marshaller = configuration.getMarshaller();
this.immutability = configuration.getImmutability();
this.properties = configuration.getCacheProperties();
this.mutatorFactory = new InfinispanMutatorFactory<>(this.attributeCache, this.properties);
this.provider = configuration.getHttpSessionActivationListenerProvider();
this.notifierFactory = configuration.getActivationNotifierFactory();
this.executor = configuration.getBlockingManager().asExecutor(this.getClass().getName());
this.evictListenerRegistration = new PostPassivateBlockingListener<>(configuration.getCache(), this::cascadeEvict).register(SessionCreationMetaDataKey.class);
this.evictAttributesListenerRegistration = new PrePassivateNonBlockingListener<>(this.namesCache, this::cascadeEvictAttributes).register(SessionAttributeNamesKey.class);
this.prePassivateListenerRegistration = !this.properties.isPersistent() ? new PrePassivateBlockingListener<>(this.attributeCache, this::prePassivate).register(SessionAttributeKey.class) : null;
this.postActivateListenerRegistration = !this.properties.isPersistent() ? new PostActivateBlockingListener<>(this.attributeCache, this::postActivate).register(SessionAttributeKey.class) : null;
}
@Override
public void close() {
this.evictListenerRegistration.close();
this.evictAttributesListenerRegistration.close();
if (this.prePassivateListenerRegistration != null) {
this.prePassivateListenerRegistration.close();
}
if (this.postActivateListenerRegistration != null) {
this.postActivateListenerRegistration.close();
}
}
@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 TreeMap<>();
for (Map.Entry<String, UUID> entry : names.entrySet()) {
attributes.put(new SessionAttributeKey(id, entry.getValue()), entry.getKey());
}
Map<SessionAttributeKey, V> entries = this.attributeCache.getAdvancedCache().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) {
InfinispanWebLogger.ROOT_LOGGER.failedToActivateSessionAttribute(e, id, attribute.getValue());
}
} else {
InfinispanWebLogger.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) {
return this.delete(this.writeCache, id);
}
@Override
public boolean purge(String id) {
return this.delete(this.silentCache, id);
}
private boolean delete(Cache<Key<String>, Object> cache, String id) {
SessionAttributeNamesKey key = new SessionAttributeNamesKey(id);
Map<String, UUID> names = this.namesCache.get(key);
if (names != null) {
for (UUID attributeId : names.values()) {
cache.remove(new SessionAttributeKey(id, attributeId));
}
cache.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), 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);
}
};
}
private void cascadeEvict(SessionCreationMetaDataKey key) {
this.namesCache.evict(new SessionAttributeNamesKey(key.getId()));
}
private void cascadeEvictAttributes(SessionAttributeNamesKey key, Map<String, UUID> value) {
String sessionId = key.getId();
for (UUID attributeId : value.values()) {
this.executor.execute(() -> this.attributeCache.evict(new SessionAttributeKey(sessionId, attributeId)));
}
}
private void prePassivate(SessionAttributeKey key, V value) {
this.notify(SessionAttributeActivationNotifier.PRE_PASSIVATE, key, value);
}
private void postActivate(SessionAttributeKey key, V value) {
this.notify(SessionAttributeActivationNotifier.POST_ACTIVATE, key, value);
}
private void notify(BiConsumer<SessionAttributeActivationNotifier, Object> notification, SessionAttributeKey key, V value) {
String sessionId = key.getId();
try (SessionAttributeActivationNotifier notifier = this.notifierFactory.apply(key.getId())) {
notification.accept(notifier, this.marshaller.read(value));
} catch (IOException e) {
InfinispanWebLogger.ROOT_LOGGER.failedToActivateSessionAttribute(e, sessionId, key.getAttributeId().toString());
}
}
}
| 11,720
| 49.74026
| 225
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/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.infinispan.session.fine;
import org.wildfly.clustering.ee.infinispan.GroupedKey;
/**
* Cache key for session attribute names.
* @author Paul Ferraro
*/
public class SessionAttributeNamesKey extends GroupedKey<String> {
public SessionAttributeNamesKey(String id) {
super(id);
}
}
| 1,359
| 36.777778
| 70
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/fine/SessionAttributeKeyMarshaller.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.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;
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 attributeIdBuilder = 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()) {
UUIDMarshaller.INSTANCE.readField(reader, index - ATTRIBUTE_IDENTIFIER_INDEX, attributeIdBuilder);
} else {
reader.skipField(tag);
}
}
return new SessionAttributeKey(sessionId, attributeIdBuilder.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,262
| 46.289855
| 137
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/fine/SessionAttributeKeyFormatter.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.session.fine;
import java.util.UUID;
import java.util.function.Function;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.spi.DelimitedFormatter;
import org.wildfly.clustering.marshalling.spi.Formatter;
/**
* Formatter for a {@link SessionAttributeKey}
* @author Paul Ferraro
*/
@MetaInfServices(Formatter.class)
public class SessionAttributeKeyFormatter extends DelimitedFormatter<SessionAttributeKey> {
public SessionAttributeKeyFormatter() {
super(SessionAttributeKey.class, "#", new Function<String[], SessionAttributeKey>() {
@Override
public SessionAttributeKey apply(String[] parts) {
return new SessionAttributeKey(parts[0], UUID.fromString(parts[1]));
}
}, new Function<SessionAttributeKey, String[]>() {
@Override
public String[] apply(SessionAttributeKey key) {
return new String[] { key.getId(), key.getAttributeId().toString() };
}
});
}
}
| 2,094
| 39.288462
| 93
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/coarse/SessionAttributesKeyFormatter.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.coarse;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.spi.Formatter;
import org.wildfly.clustering.web.infinispan.SessionKeyFormatter;
/**
* Resolver for {@link SessionAttributesKey}.
* @author Paul Ferraro
*/
@MetaInfServices(Formatter.class)
public class SessionAttributesKeyFormatter extends SessionKeyFormatter<SessionAttributesKey> {
public SessionAttributesKeyFormatter() {
super(SessionAttributesKey.class, SessionAttributesKey::new);
}
}
| 1,577
| 39.461538
| 94
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/session/coarse/CoarseSessionAttributesFactory.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.session.coarse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.function.Function;
import org.infinispan.Cache;
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.infinispan.InfinispanMutatorFactory;
import org.wildfly.clustering.infinispan.listener.ListenerRegistration;
import org.wildfly.clustering.infinispan.listener.PostActivateBlockingListener;
import org.wildfly.clustering.infinispan.listener.PostPassivateBlockingListener;
import org.wildfly.clustering.infinispan.listener.PrePassivateBlockingListener;
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.SessionAttributeActivationNotifier;
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.infinispan.logging.InfinispanWebLogger;
import org.wildfly.clustering.web.infinispan.session.InfinispanSessionAttributesFactoryConfiguration;
import org.wildfly.clustering.web.infinispan.session.SessionCreationMetaDataKey;
import org.wildfly.clustering.web.session.HttpSessionActivationListenerProvider;
import org.wildfly.clustering.web.session.ImmutableSessionAttributes;
import org.wildfly.clustering.web.session.ImmutableSessionMetaData;
/**
* {@link SessionAttributesFactory} for coarse granularity sessions, where all session attributes are stored in a single cache entry.
* @author Paul Ferraro
*/
public class CoarseSessionAttributesFactory<S, C, L, V> implements SessionAttributesFactory<C, Map<String, Object>> {
private final Cache<SessionAttributesKey, V> cache;
private final Cache<SessionAttributesKey, V> writeCache;
private final Cache<SessionAttributesKey, V> silentCache;
private final Marshaller<Map<String, Object>, V> marshaller;
private final CacheProperties properties;
private final Immutability immutability;
private final MutatorFactory<SessionAttributesKey, V> mutatorFactory;
private final HttpSessionActivationListenerProvider<S, C, L> provider;
private final Function<String, SessionAttributeActivationNotifier> notifierFactory;
private final ListenerRegistration evictListenerRegistration;
private final ListenerRegistration prePassivateListenerRegistration;
private final ListenerRegistration postActivateListenerRegistration;
public CoarseSessionAttributesFactory(InfinispanSessionAttributesFactoryConfiguration<S, C, L, Map<String, Object>, V> configuration) {
this.cache = configuration.getCache();
this.writeCache = configuration.getWriteOnlyCache();
this.silentCache = configuration.getSilentWriteCache();
this.marshaller = configuration.getMarshaller();
this.immutability = configuration.getImmutability();
this.properties = configuration.getCacheProperties();
this.mutatorFactory = new InfinispanMutatorFactory<>(this.cache, this.properties);
this.provider = configuration.getHttpSessionActivationListenerProvider();
this.notifierFactory = configuration.getActivationNotifierFactory();
this.prePassivateListenerRegistration = !this.properties.isPersistent() ? new PrePassivateBlockingListener<>(this.cache, this::prePassivate).register(SessionAttributesKey.class) : null;
this.postActivateListenerRegistration = !this.properties.isPersistent() ? new PostActivateBlockingListener<>(this.cache, this::postActivate).register(SessionAttributesKey.class) : null;
this.evictListenerRegistration = new PostPassivateBlockingListener<>(configuration.getCache(), this::cascadeEvict).register(SessionCreationMetaDataKey.class);
}
@Override
public void close() {
this.evictListenerRegistration.close();
if (this.prePassivateListenerRegistration != null) {
this.prePassivateListenerRegistration.close();
}
if (this.postActivateListenerRegistration != null) {
this.postActivateListenerRegistration.close();
}
}
@Override
public Map<String, Object> createValue(String id, Void context) {
Map<String, Object> attributes = new ConcurrentHashMap<>();
try {
V value = this.marshaller.write(attributes);
this.writeCache.put(new SessionAttributesKey(id), value);
return attributes;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public Map<String, Object> findValue(String id) {
return this.getValue(id, true);
}
@Override
public Map<String, Object> tryValue(String id) {
return this.getValue(id, false);
}
private Map<String, Object> getValue(String id, boolean purgeIfInvalid) {
V value = this.cache.get(new SessionAttributesKey(id));
if (value != null) {
try {
return this.marshaller.read(value);
} catch (IOException e) {
InfinispanWebLogger.ROOT_LOGGER.failedToActivateSession(e, id);
if (purgeIfInvalid) {
this.purge(id);
}
}
}
return null;
}
@Override
public boolean remove(String id) {
return this.delete(this.writeCache, id);
}
@Override
public boolean purge(String id) {
return this.delete(this.silentCache, id);
}
private boolean delete(Cache<SessionAttributesKey, V> cache, String id) {
cache.remove(new SessionAttributesKey(id));
return true;
}
@Override
public SessionAttributes createSessionAttributes(String id, Map<String, Object> attributes, ImmutableSessionMetaData metaData, C context) {
try {
Mutator mutator = (this.properties.isTransactional() && metaData.isNew()) ? Mutator.PASSIVE : 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);
}
private void cascadeEvict(SessionCreationMetaDataKey key) {
this.cache.evict(new SessionAttributesKey(key.getId()));
}
private void prePassivate(SessionAttributesKey key, V value) {
this.notify(key, value, SessionAttributeActivationNotifier.PRE_PASSIVATE);
}
private void postActivate(SessionAttributesKey key, V value) {
this.notify(key, value, SessionAttributeActivationNotifier.POST_ACTIVATE);
}
private void notify(SessionAttributesKey key, V value, BiConsumer<SessionAttributeActivationNotifier, Object> notification) {
String sessionId = key.getId();
try (SessionAttributeActivationNotifier notifier = this.notifierFactory.apply(sessionId)) {
Map<String, Object> attributes = this.marshaller.read(value);
for (Object attributeValue : attributes.values()) {
notification.accept(notifier, attributeValue);
}
} catch (IOException e) {
InfinispanWebLogger.ROOT_LOGGER.failedToActivateSession(e, sessionId);
}
}
}
| 9,417
| 47.546392
| 254
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/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.infinispan.session.coarse;
import org.wildfly.clustering.ee.infinispan.GroupedKey;
/**
* Cache key for session attributes.
* @author Paul Ferraro
*/
public class SessionAttributesKey extends GroupedKey<String> {
public SessionAttributesKey(String id) {
super(id);
}
}
| 1,348
| 36.472222
| 70
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/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.infinispan.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,819
| 42.333333
| 118
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/routing/PrimaryOwnerRouteLocator.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 java.util.Map;
import java.util.function.Function;
import org.wildfly.clustering.ee.infinispan.GroupedKey;
import org.wildfly.clustering.ee.infinispan.PrimaryOwnerLocator;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.registry.Registry;
import org.wildfly.clustering.web.routing.RouteLocator;
/**
* @author Paul Ferraro
*/
public class PrimaryOwnerRouteLocator implements RouteLocator {
private final Function<GroupedKey<String>, Node> primaryOwnerLocator;
private final Registry<String, Void> registry;
private final String localRoute;
public PrimaryOwnerRouteLocator(PrimaryOwnerRouteLocatorConfiguration config) {
this(new PrimaryOwnerLocator<>(config.getCache(), config.getMemberFactory()), config.getRegistry());
}
PrimaryOwnerRouteLocator(Function<GroupedKey<String>, Node> primaryOwnerLocator, Registry<String, Void> registry) {
this.primaryOwnerLocator = primaryOwnerLocator;
this.registry = registry;
this.localRoute = this.registry.getEntry(this.registry.getGroup().getLocalMember()).getKey();
}
@Override
public String locate(String sessionId) {
Node primaryMember = this.primaryOwnerLocator.apply(new GroupedKey<>(sessionId));
Map.Entry<String, Void> entry = this.registry.getEntry(primaryMember);
return (entry != null) ? entry.getKey() : this.localRoute;
}
}
| 2,490
| 40.516667
| 119
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/routing/RankedRoutingConfiguration.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;
/**
* @author Paul Ferraro
*/
public interface RankedRoutingConfiguration {
String getDelimiter();
int getMaxRoutes();
}
| 1,213
| 34.705882
| 70
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/routing/RankedRouteLocatorConfiguration.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;
/**
* Configurator for a ranked route locator.
* @author Paul Ferraro
*/
public interface RankedRouteLocatorConfiguration extends PrimaryOwnerRouteLocatorConfiguration, RankedRoutingConfiguration {
}
| 1,283
| 40.419355
| 124
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/routing/InfinispanRoutingSerializationContextInitializer.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.infinispan.routing;
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.FunctionalScalarMarshaller;
import org.wildfly.clustering.marshalling.protostream.Scalar;
/**
* {@link SerializationContextInitializer} for this package.
* @author Paul Ferraro
*/
@MetaInfServices(SerializationContextInitializer.class)
public class InfinispanRoutingSerializationContextInitializer extends AbstractSerializationContextInitializer {
@Override
public void registerMarshallers(SerializationContext context) {
context.registerMarshaller(new FunctionalScalarMarshaller<>(RouteRegistryEntry.class, Scalar.STRING.cast(String.class), RouteRegistryEntry::getKey, RouteRegistryEntry::new));
}
}
| 2,014
| 44.795455
| 182
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/routing/PrimaryOwnerRouteLocatorConfiguration.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 org.infinispan.Cache;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.ee.infinispan.GroupedKey;
import org.wildfly.clustering.registry.Registry;
import org.wildfly.clustering.server.NodeFactory;
/**
* @author Paul Ferraro
*/
public interface PrimaryOwnerRouteLocatorConfiguration {
Registry<String, Void> getRegistry();
Cache<GroupedKey<String>, ?> getCache();
NodeFactory<Address> getMemberFactory();
}
| 1,541
| 35.714286
| 70
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/routing/RankedRouteLocator.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 java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.infinispan.Cache;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.ee.infinispan.GroupedKey;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.infinispan.distribution.CacheKeyDistribution;
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 RankedRouteLocator implements RouteLocator {
private final KeyDistribution distribution;
private final Registry<String, Void> registry;
private final NodeFactory<Address> factory;
private final String localRoute;
private final String delimiter;
private final int maxRoutes;
public RankedRouteLocator(RankedRouteLocatorConfiguration config) {
this(config.getCache(), config.getRegistry(), config.getMemberFactory(), config.getDelimiter(), config.getMaxRoutes());
}
private RankedRouteLocator(Cache<GroupedKey<String>, ?> cache, Registry<String, Void> registry, NodeFactory<Address> factory, String delimiter, int maxRoutes) {
this(new CacheKeyDistribution(cache), registry, factory, delimiter, maxRoutes);
}
RankedRouteLocator(KeyDistribution distribution, Registry<String, Void> registry, NodeFactory<Address> factory, String delimiter, int maxRoutes) {
this.distribution = distribution;
this.registry = registry;
this.factory = factory;
this.localRoute = this.registry.getEntry(this.registry.getGroup().getLocalMember()).getKey();
this.delimiter = delimiter;
this.maxRoutes = maxRoutes;
}
@Override
public String locate(String sessionId) {
List<Address> owners = this.distribution.getOwners(new GroupedKey<>(sessionId));
List<String> routes = new ArrayList<>(this.maxRoutes);
boolean localIsOwner = false;
Node localMember = this.registry.getGroup().getLocalMember();
Iterator<Address> addresses = owners.iterator();
while (addresses.hasNext() && (routes.size() < this.maxRoutes)) {
Address address = addresses.next();
Node member = this.factory.createNode(address);
if (member != null) {
if (member.equals(localMember)) {
localIsOwner = true;
}
Map.Entry<String, Void> entry = this.registry.getEntry(member);
if (entry != null) {
routes.add(entry.getKey());
}
}
}
if (!localIsOwner && (routes.size() < this.maxRoutes)) {
routes.add(this.localRoute);
}
return !routes.isEmpty() ? String.join(this.delimiter, routes) : this.localRoute;
}
}
| 4,035
| 41.484211
| 164
|
java
|
null |
wildfly-main/clustering/web/infinispan/src/main/java/org/wildfly/clustering/web/infinispan/routing/RouteRegistryEntry.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.infinispan.routing;
import java.util.AbstractMap.SimpleImmutableEntry;
/**
* Registry entry for the Infinispan routing provider.
* @author Paul Ferraro
*/
public class RouteRegistryEntry extends SimpleImmutableEntry<String, Void> {
private static final long serialVersionUID = 6829830614436225931L;
public RouteRegistryEntry(String route) {
super(route, null);
}
}
| 1,450
| 37.184211
| 76
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/ExternalizerNetTestCase.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.marshalling.spi;
import org.wildfly.clustering.marshalling.AbstractNetTestCase;
import org.wildfly.clustering.marshalling.ExternalizerTesterFactory;
import org.wildfly.clustering.marshalling.spi.net.NetExternalizerProvider;
/**
* Externalizer tests for java.net.* classes.
* @author Paul Ferraro
*/
public class ExternalizerNetTestCase extends AbstractNetTestCase {
public ExternalizerNetTestCase() {
super(new ExternalizerTesterFactory(NetExternalizerProvider.class));
}
}
| 1,551
| 38.794872
| 76
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/IndexSerializerTestCase.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.marshalling.spi;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.stream.IntStream;
import org.junit.Test;
/**
* Unit test for {@link IndexSerializer}.
* @author Paul Ferraro
*/
public class IndexSerializerTestCase {
@Test
public void test() throws IOException {
// Test marshalling of incrementing powers of 2
for (int i = 0; i < Integer.SIZE - 2; ++i) {
int index = 2 << i;
test(index - 1);
test(index);
}
test(Integer.MAX_VALUE);
}
private static void test(int index) throws IOException {
IntStream.Builder builder = IntStream.builder();
try {
builder.add(size(IndexSerializer.UNSIGNED_BYTE, index));
} catch (IndexOutOfBoundsException e) {
assertTrue(index > Byte.MAX_VALUE - Byte.MIN_VALUE);
}
try {
builder.add(size(IndexSerializer.UNSIGNED_SHORT, index));
} catch (IndexOutOfBoundsException e) {
assertTrue(index > Short.MAX_VALUE - Short.MIN_VALUE);
}
builder.add(size(IndexSerializer.VARIABLE, index));
builder.add(size(IndexSerializer.INTEGER, index));
// Ensure that our IndexExternalizer.select(...) chooses the optimal externalizer
assertEquals(builder.build().min().getAsInt(), size(IndexSerializer.select(index), index));
}
public static int size(IntSerializer externalizer, int index) throws IOException {
ByteArrayOutputStream externalizedOutput = new ByteArrayOutputStream();
try (DataOutputStream output = new DataOutputStream(externalizedOutput)) {
externalizer.writeInt(output, index);
}
byte[] externalizedBytes = externalizedOutput.toByteArray();
try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(externalizedBytes))) {
int result = externalizer.readInt(input);
assertEquals(index, result);
}
return externalizedBytes.length;
}
}
| 3,245
| 33.903226
| 104
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/ExternalizerSQLTestCase.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.marshalling.spi;
import org.wildfly.clustering.marshalling.AbstractSQLTestCase;
import org.wildfly.clustering.marshalling.ExternalizerTesterFactory;
import org.wildfly.clustering.marshalling.spi.sql.SQLExternalizerProvider;
/**
* Externalizer tests for java.sql.* classes.
* @author Paul Ferraro
*/
public class ExternalizerSQLTestCase extends AbstractSQLTestCase {
public ExternalizerSQLTestCase() {
super(new ExternalizerTesterFactory(SQLExternalizerProvider.class));
}
}
| 1,551
| 38.794872
| 76
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/ExternalizerConcurrentTestCase.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.marshalling.spi;
import org.wildfly.clustering.marshalling.AbstractConcurrentTestCase;
import org.wildfly.clustering.marshalling.ExternalizerTesterFactory;
import org.wildfly.clustering.marshalling.spi.util.concurrent.ConcurrentExternalizerProvider;
/**
* Externalizer tests for java.util.concurrent.* classes.
* @author Paul Ferraro
*/
public class ExternalizerConcurrentTestCase extends AbstractConcurrentTestCase {
public ExternalizerConcurrentTestCase() {
super(new ExternalizerTesterFactory(ConcurrentExternalizerProvider.class));
}
}
| 1,617
| 40.487179
| 93
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/ExternalizerTimeTestCase.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.marshalling.spi;
import org.wildfly.clustering.marshalling.AbstractTimeTestCase;
import org.wildfly.clustering.marshalling.ExternalizerTesterFactory;
import org.wildfly.clustering.marshalling.spi.time.TimeExternalizerProvider;
/**
* Externalizer tests for java.time.* classes.
* @author Paul Ferraro
*/
public class ExternalizerTimeTestCase extends AbstractTimeTestCase {
public ExternalizerTimeTestCase() {
super(new ExternalizerTesterFactory(TimeExternalizerProvider.class));
}
}
| 1,559
| 39
| 77
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/FormatterTester.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.marshalling.spi;
import static org.junit.Assert.assertTrue;
import java.util.function.BiConsumer;
import org.junit.Assert;
import org.wildfly.clustering.marshalling.Tester;
/**
* Tester for a {@link Formatter}.
* @author Paul Ferraro
*/
public class FormatterTester<K> implements Tester<K> {
private final Formatter<K> format;
public FormatterTester(Formatter<K> format) {
this.format = format;
}
@Override
public void test(K key) {
this.test(key, Assert::assertEquals);
}
@Override
public void test(K subject, BiConsumer<K, K> assertion) {
assertTrue(this.format.getTargetClass().isInstance(subject));
String formatted = this.format.format(subject);
K result = this.format.parse(formatted);
assertion.accept(subject, result);
}
}
| 1,884
| 30.416667
| 70
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/ExternalizerUtilTestCase.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.marshalling.spi;
import org.wildfly.clustering.marshalling.AbstractUtilTestCase;
import org.wildfly.clustering.marshalling.ExternalizerTesterFactory;
import org.wildfly.clustering.marshalling.spi.util.UtilExternalizerProvider;
/**
* Externalizer tests for java.util.* classes.
* @author Paul Ferraro
*/
public class ExternalizerUtilTestCase extends AbstractUtilTestCase {
public ExternalizerUtilTestCase() {
super(new ExternalizerTesterFactory(UtilExternalizerProvider.class));
}
}
| 1,559
| 39
| 77
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/JavaByteBufferMarshaller.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.marshalling.spi;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
/**
* A {@ByteBufferMarshaller} that uses Java serialization.
* @author Paul Ferraro
*/
public enum JavaByteBufferMarshaller implements ByteBufferMarshaller {
INSTANCE;
@Override
public boolean isMarshallable(Object object) {
return object instanceof Serializable;
}
@Override
public Object readFrom(InputStream input) throws IOException {
try {
return new ObjectInputStream(input).readObject();
} catch (ClassNotFoundException e) {
InvalidClassException exception = new InvalidClassException(e.getMessage());
exception.initCause(e);
throw exception;
}
}
@Override
public void writeTo(OutputStream output, Object value) throws IOException {
new ObjectOutputStream(output).writeObject(value);
}
}
| 2,125
| 33.852459
| 88
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/ByteBufferTestMarshaller.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.marshalling.spi;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.OptionalInt;
import org.junit.Assert;
import org.wildfly.clustering.marshalling.TestMarshaller;
/**
* A {@link ByteBufferMarshaller} based {@link TestMarshaller}.
* @author Paul Ferraro
*/
public class ByteBufferTestMarshaller<T> implements TestMarshaller<T> {
private final ByteBufferMarshaller marshaller;
public ByteBufferTestMarshaller(ByteBufferMarshaller marshaller) {
this.marshaller = marshaller;
}
@SuppressWarnings("unchecked")
@Override
public T read(ByteBuffer buffer) throws IOException {
return (T) this.marshaller.read(buffer);
}
@Override
public ByteBuffer write(T object) throws IOException {
ByteBuffer buffer = this.marshaller.write(object);
OptionalInt size = this.marshaller.size(object);
if (size.isPresent()) {
Assert.assertEquals(buffer.remaining(), size.getAsInt());
}
return buffer;
}
}
| 2,076
| 33.616667
| 71
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/ExternalizerAtomicTestCase.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.marshalling.spi;
import org.wildfly.clustering.marshalling.AbstractAtomicTestCase;
import org.wildfly.clustering.marshalling.ExternalizerTesterFactory;
import org.wildfly.clustering.marshalling.spi.util.concurrent.atomic.AtomicExternalizerProvider;
/**
* Externalizer tests for java.util.concurrent.atomic.* classes.
* @author Paul Ferraro
*/
public class ExternalizerAtomicTestCase extends AbstractAtomicTestCase {
public ExternalizerAtomicTestCase() {
super(new ExternalizerTesterFactory(AtomicExternalizerProvider.class));
}
}
| 1,607
| 40.230769
| 96
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/ByteBufferMarshalledKeyFactoryTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, 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.marshalling.spi;
import static org.junit.Assert.assertEquals;
import java.util.UUID;
/**
* Unit tests for {@link ByteBufferMarshalledValue}.
*
* @author Brian Stansberry
* @author Paul Ferraro
*/
public class ByteBufferMarshalledKeyFactoryTestCase extends ByteBufferMarshalledValueFactoryTestCase {
private final ByteBufferMarshalledKeyFactory factory;
public ByteBufferMarshalledKeyFactoryTestCase() {
this(JavaByteBufferMarshaller.INSTANCE);
}
protected ByteBufferMarshalledKeyFactoryTestCase(ByteBufferMarshaller marshaller) {
this(marshaller, new ByteBufferMarshalledKeyFactory(marshaller));
}
private ByteBufferMarshalledKeyFactoryTestCase(ByteBufferMarshaller marshaller, ByteBufferMarshalledKeyFactory factory) {
super(marshaller, factory);
this.factory = factory;
}
@Override
public void testHashCode() throws Exception {
UUID uuid = UUID.randomUUID();
int expected = uuid.hashCode();
ByteBufferMarshalledValue<UUID> mv = this.factory.createMarshalledValue(uuid);
assertEquals(expected, mv.hashCode());
ByteBufferMarshalledValue<UUID> copy = replicate(mv);
assertEquals(expected, copy.hashCode());
mv = this.factory.createMarshalledValue(null);
assertEquals(0, mv.hashCode());
}
}
| 2,403
| 35.984615
| 125
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/SimpleFormatterTestCase.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.marshalling.spi;
import static org.mockito.Mockito.*;
import java.util.function.Function;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Paul Ferraro
*/
public class SimpleFormatterTestCase {
@Test
public void test() {
Function<String, Object> parser = mock(Function.class);
Function<Object, String> formatter = mock(Function.class);
Formatter<Object> format = new SimpleFormatter<>(Object.class, parser, formatter);
Object object = new Object();
String result = "foo";
when(formatter.apply(object)).thenReturn(result);
when(parser.apply(result)).thenReturn(object);
new FormatterTester<>(format).test(object, Assert::assertSame);
}
}
| 1,790
| 34.117647
| 90
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/test/java/org/wildfly/clustering/marshalling/spi/ByteBufferMarshalledValueFactoryTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, 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.marshalling.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.OptionalInt;
import java.util.UUID;
import org.junit.Test;
/**
* Unit tests for {@link ByteBufferMarshalledValue}.
*
* @author Brian Stansberry
* @author Paul Ferraro
*/
public class ByteBufferMarshalledValueFactoryTestCase {
private final ByteBufferMarshaller marshaller;
private final ByteBufferMarshalledValueFactory factory;
public ByteBufferMarshalledValueFactoryTestCase() {
this(JavaByteBufferMarshaller.INSTANCE);
}
protected ByteBufferMarshalledValueFactoryTestCase(ByteBufferMarshaller marshaller) {
this(marshaller, new ByteBufferMarshalledValueFactory(marshaller));
}
ByteBufferMarshalledValueFactoryTestCase(ByteBufferMarshaller marshaller, ByteBufferMarshalledValueFactory factory) {
this.marshaller = marshaller;
this.factory = factory;
}
@Test
public void get() throws Exception {
UUID uuid = UUID.randomUUID();
ByteBufferMarshalledValue<UUID> mv = this.factory.createMarshalledValue(uuid);
assertNotNull(mv.peek());
assertSame(uuid, mv.peek());
assertSame(uuid, mv.get(this.marshaller));
ByteBufferMarshalledValue<UUID> copy = replicate(mv);
assertNull(copy.peek());
UUID uuid2 = copy.get(this.marshaller);
assertNotSame(uuid, uuid2);
assertEquals(uuid, uuid2);
copy = replicate(copy);
uuid2 = copy.get(this.marshaller);
assertEquals(uuid, uuid2);
mv = this.factory.createMarshalledValue(null);
assertNull(mv.peek());
assertNull(mv.getBuffer());
assertNull(mv.get(this.marshaller));
}
@Test
public void equals() throws Exception {
UUID uuid = UUID.randomUUID();
ByteBufferMarshalledValue<UUID> mv = this.factory.createMarshalledValue(uuid);
assertTrue(mv.equals(mv));
assertFalse(mv.equals(null));
ByteBufferMarshalledValue<UUID> dup = this.factory.createMarshalledValue(uuid);
assertTrue(mv.equals(dup));
assertTrue(dup.equals(mv));
ByteBufferMarshalledValue<UUID> replica = replicate(mv);
assertTrue(mv.equals(replica));
assertTrue(replica.equals(mv));
ByteBufferMarshalledValue<UUID> nulled = this.factory.createMarshalledValue(null);
assertFalse(mv.equals(nulled));
assertFalse(nulled.equals(mv));
assertFalse(replica.equals(nulled));
assertFalse(nulled.equals(replica));
assertTrue(nulled.equals(nulled));
assertFalse(nulled.equals(null));
assertTrue(nulled.equals(this.factory.createMarshalledValue(null)));
}
@Test
public void testHashCode() throws Exception {
UUID uuid = UUID.randomUUID();
ByteBufferMarshalledValue<UUID> mv = this.factory.createMarshalledValue(uuid);
assertEquals(uuid.hashCode(), mv.hashCode());
ByteBufferMarshalledValue<UUID> copy = replicate(mv);
assertEquals(0, copy.hashCode());
mv = this.factory.createMarshalledValue(null);
assertEquals(0, mv.hashCode());
}
@SuppressWarnings("unchecked")
<V> ByteBufferMarshalledValue<V> replicate(ByteBufferMarshalledValue<V> value) throws IOException {
OptionalInt size = this.marshaller.size(value);
ByteBuffer buffer = this.marshaller.write(value);
if (size.isPresent()) {
// Verify that computed size equals actual size
assertEquals(size.getAsInt(), buffer.remaining());
}
ByteBufferMarshalledValue<V> result = (ByteBufferMarshalledValue<V>) this.marshaller.read(buffer);
OptionalInt resultSize = this.marshaller.size(result);
if (size.isPresent() && resultSize.isPresent()) {
// Verify that computed size equals actual size
assertEquals(size.getAsInt(), resultSize.getAsInt());
}
return result;
}
}
| 5,351
| 35.657534
| 121
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ByteBufferMarshalledValueFactory.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.marshalling.spi;
/**
* Factory for creating a {@link ByteBufferMarshalledValue}.
* @author Paul Ferraro
*/
public class ByteBufferMarshalledValueFactory implements MarshalledValueFactory<ByteBufferMarshaller> {
private final ByteBufferMarshaller marshaller;
public ByteBufferMarshalledValueFactory(ByteBufferMarshaller marshaller) {
this.marshaller = marshaller;
}
@Override
public boolean isMarshallable(Object object) {
return this.marshaller.isMarshallable(object);
}
@Override
public <T> ByteBufferMarshalledValue<T> createMarshalledValue(T object) {
return new ByteBufferMarshalledValue<>(object, this.marshaller);
}
@Override
public ByteBufferMarshaller getMarshallingContext() {
return this.marshaller;
}
}
| 1,858
| 34.75
| 103
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/Formatter.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.marshalling.spi;
/**
* Formats a cache key to a string representation and back again.
* @author Paul Ferraro
*/
public interface Formatter<K> {
/**
* The implementation class of the target key of this format.
* @return an implementation class
*/
Class<K> getTargetClass();
/**
* Parses the key from the specified string.
* @param value a string representation of the key
* @return the parsed key
*/
K parse(String value);
/**
* Formats the specified key to a string representation.
* @param key a key to format
* @return a string representation of the specified key.
*/
String format(K key);
}
| 1,734
| 33.7
| 70
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/MarshalledValueMarshaller.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.marshalling.spi;
import java.io.IOException;
/**
* Marshaller that stores attribute values using marshalled values.
* @author Paul Ferraro
*/
public class MarshalledValueMarshaller<V, C> implements Marshaller<V, MarshalledValue<V, C>> {
private final MarshalledValueFactory<C> factory;
public MarshalledValueMarshaller(MarshalledValueFactory<C> factory) {
this.factory = factory;
}
@Override
public V read(MarshalledValue<V, C> value) throws IOException {
if (value == null) return null;
return value.get(this.factory.getMarshallingContext());
}
@Override
public MarshalledValue<V, C> write(V object) {
if (object == null) return null;
return this.factory.createMarshalledValue(object);
}
@Override
public boolean isMarshallable(Object object) {
return this.factory.isMarshallable(object);
}
}
| 1,953
| 35.185185
| 94
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/DelimitedFormatter.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.marshalling.spi;
import java.util.function.Function;
import java.util.regex.Pattern;
/**
* {@link Formatter} for keys with multiple string fields.
* @author Paul Ferraro
*/
public class DelimitedFormatter<K> extends SimpleFormatter<K> {
public DelimitedFormatter(Class<K> targetClass, String delimiter, Function<String[], K> parser, Function<K, String[]> formatter) {
super(targetClass, value -> parser.apply(value.split(Pattern.quote(delimiter))), key -> String.join(delimiter, formatter.apply(key)));
}
}
| 1,584
| 40.710526
| 142
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/StringExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.OptionalInt;
import java.util.function.Function;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Base {@link Externalizer} for string-based externalization.
* @author Paul Ferraro
*/
public class StringExternalizer<T> implements Externalizer<T> {
private final Formatter<T> formatter;
public StringExternalizer(Formatter<T> formatter) {
this.formatter = formatter;
}
public StringExternalizer(Class<T> targetClass, Function<String, T> reader) {
this.formatter = new SimpleFormatter<>(targetClass, reader);
}
public StringExternalizer(Class<T> targetClass, Function<String, T> reader, Function<T, String> writer) {
this.formatter = new SimpleFormatter<>(targetClass, reader, writer);
}
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
output.writeUTF(this.formatter.format(object));
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return this.formatter.parse(input.readUTF());
}
@Override
public OptionalInt size(T object) {
return OptionalInt.of(this.formatter.format(object).length() + 1);
}
@Override
public Class<T> getTargetClass() {
return this.formatter.getTargetClass();
}
}
| 2,500
| 33.736111
| 109
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/SerializerExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.OptionalInt;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* {@link Externalizer} based on a {@link Serializer}.
* @author Paul Ferraro
*/
public class SerializerExternalizer<T> implements Externalizer<T> {
private final Class<T> targetClass;
private final Serializer<T> serializer;
public SerializerExternalizer(Class<T> targetClass, Serializer<T> serializer) {
this.targetClass = targetClass;
this.serializer = serializer;
}
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
this.serializer.write(output, object);
}
@Override
public T readObject(ObjectInput input) throws IOException {
return this.serializer.read(input);
}
@Override
public Class<T> getTargetClass() {
return this.targetClass;
}
@Override
public OptionalInt size(T object) {
return this.serializer.size(object);
}
}
| 2,133
| 31.333333
| 83
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/BinaryFormatter.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.marshalling.spi;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Base64;
/**
* {@link Formatter} implementation for binary keys.
* @author Paul Ferraro
*/
public class BinaryFormatter<K> implements Formatter<K> {
private final Class<K> targetClass;
private final Serializer<K> serializer;
public BinaryFormatter(Class<K> targetClass, Serializer<K> serializer) {
this.targetClass = targetClass;
this.serializer = serializer;
}
@Override
public Class<K> getTargetClass() {
return this.targetClass;
}
@Override
public K parse(String value) {
byte[] bytes = Base64.getDecoder().decode(value);
try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(bytes))) {
return this.serializer.read(input);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public String format(K key) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream output = new DataOutputStream(bytes)) {
this.serializer.write(output, key);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
return Base64.getEncoder().encodeToString(bytes.toByteArray());
}
}
| 2,509
| 33.861111
| 92
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ByteBufferMarshalledKeyExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Externalizer for a {@link ByteBufferMarshalledKey}.
* @author Paul Ferraro
*/
public class ByteBufferMarshalledKeyExternalizer implements Externalizer<ByteBufferMarshalledKey<Object>> {
@Override
public void writeObject(ObjectOutput output, ByteBufferMarshalledKey<Object> value) throws IOException {
ByteBufferMarshalledValueExternalizer.writeBuffer(output, value.getBuffer());
output.writeInt(value.hashCode());
}
@Override
public ByteBufferMarshalledKey<Object> readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new ByteBufferMarshalledKey<>(ByteBufferMarshalledValueExternalizer.readBuffer(input), input.readInt());
}
@SuppressWarnings("unchecked")
@Override
public Class<ByteBufferMarshalledKey<Object>> getTargetClass() {
return (Class<ByteBufferMarshalledKey<Object>>) (Class<?>) ByteBufferMarshalledKey.class;
}
}
| 2,154
| 38.907407
| 119
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/SupplierFunction.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.marshalling.spi;
import java.util.function.DoubleFunction;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.LongFunction;
import java.util.function.Supplier;
/**
* Adapts a Supplier to a Function ignoring it's parameter.
* @author Paul Ferraro
*/
public class SupplierFunction<R> implements Function<Void, R>, IntFunction<R>, LongFunction<R>, DoubleFunction<R> {
private final Supplier<R> supplier;
public SupplierFunction(Supplier<R> supplier) {
this.supplier = supplier;
}
@Override
public R apply(Void ignored) {
return this.supplier.get();
}
@Override
public R apply(int value) {
return this.supplier.get();
}
@Override
public R apply(long value) {
return this.supplier.get();
}
@Override
public R apply(double value) {
return this.supplier.get();
}
}
| 1,974
| 30.349206
| 115
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/BinaryExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.OptionalInt;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Generic {@link Externalizer} for an object composed of 2 externalizable components.
* @author Paul Ferraro
*/
public class BinaryExternalizer<T, X, Y> implements Externalizer<T> {
private final Class<T> targetClass;
private final Externalizer<X> externalizer1;
private final Externalizer<Y> externalizer2;
private final Function<T, X> accessor1;
private final Function<T, Y> accessor2;
private final BiFunction<X, Y, T> factory;
public BinaryExternalizer(Class<T> targetClass, Externalizer<X> externalizer1, Externalizer<Y> externalizer2, Function<T, X> accessor1, Function<T, Y> accessor2, BiFunction<X, Y, T> factory) {
this.targetClass = targetClass;
this.externalizer1 = externalizer1;
this.externalizer2 = externalizer2;
this.accessor1 = accessor1;
this.accessor2 = accessor2;
this.factory = factory;
}
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
this.externalizer1.writeObject(output, this.accessor1.apply(object));
this.externalizer2.writeObject(output, this.accessor2.apply(object));
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return this.factory.apply(this.externalizer1.readObject(input), this.externalizer2.readObject(input));
}
@Override
public Class<T> getTargetClass() {
return this.targetClass;
}
@Override
public OptionalInt size(T object) {
OptionalInt size1 = this.externalizer1.size(this.accessor1.apply(object));
if (size1.isPresent()) {
OptionalInt size2 = this.externalizer2.size(this.accessor2.apply(object));
if (size2.isPresent()) {
return OptionalInt.of(size1.getAsInt() + size2.getAsInt());
}
}
return OptionalInt.empty();
}
}
| 3,228
| 37.440476
| 196
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ByteBufferMarshalledValueExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.ByteBuffer;
import java.util.OptionalInt;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Externalizer for a {@link ByteBufferMarshalledValue}.
* @author Paul Ferraro
*/
public class ByteBufferMarshalledValueExternalizer implements Externalizer<ByteBufferMarshalledValue<Object>> {
static ByteBuffer readBuffer(ObjectInput input) throws IOException {
int size = IndexSerializer.VARIABLE.readInt(input);
byte[] bytes = (size > 0) ? new byte[size] : null;
if (bytes != null) {
input.readFully(bytes);
}
return (bytes != null) ? ByteBuffer.wrap(bytes) : null;
}
static void writeBuffer(ObjectOutput output, ByteBuffer buffer) throws IOException {
int length = (buffer != null) ? buffer.limit() - buffer.arrayOffset() : 0;
IndexSerializer.VARIABLE.writeInt(output, length);
if (length > 0) {
output.write(buffer.array(), buffer.arrayOffset(), length);
}
}
@Override
public ByteBufferMarshalledValue<Object> readObject(ObjectInput input) throws IOException {
return new ByteBufferMarshalledValue<>(readBuffer(input));
}
@Override
public void writeObject(ObjectOutput output, ByteBufferMarshalledValue<Object> object) throws IOException {
writeBuffer(output, object.getBuffer());
}
@SuppressWarnings("unchecked")
@Override
public Class<ByteBufferMarshalledValue<Object>> getTargetClass() {
return (Class<ByteBufferMarshalledValue<Object>>) (Class<?>) ByteBufferMarshalledValue.class;
}
@Override
public OptionalInt size(ByteBufferMarshalledValue<Object> value) {
return value.size();
}
}
| 2,877
| 36.376623
| 111
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ExternalizerProvider.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.OptionalInt;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* @author Paul Ferraro
*/
public interface ExternalizerProvider extends Externalizer<Object> {
Externalizer<?> getExternalizer();
@Override
default void writeObject(ObjectOutput output, Object object) throws IOException {
this.cast(Object.class).writeObject(output, object);
}
@Override
default Object readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return this.getExternalizer().readObject(input);
}
@Override
default Class<Object> getTargetClass() {
return this.cast(Object.class).getTargetClass();
}
@Override
default OptionalInt size(Object object) {
return this.cast(Object.class).size(object);
}
@SuppressWarnings("unchecked")
default <T> Externalizer<T> cast(Class<T> type) {
if (!type.isAssignableFrom(this.getExternalizer().getTargetClass())) {
throw new IllegalArgumentException(type.getName());
}
return (Externalizer<T>) this.getExternalizer();
}
}
| 2,278
| 33.014925
| 93
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/LongExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.OptionalInt;
import java.util.function.LongFunction;
import java.util.function.ToLongFunction;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Base {@link Externalizer} for long-based externalization.
* @author Paul Ferraro
*/
public class LongExternalizer<T> implements Externalizer<T> {
private final LongFunction<T> reader;
private final ToLongFunction<T> writer;
private final Class<T> targetClass;
public LongExternalizer(Class<T> targetClass, LongFunction<T> reader, ToLongFunction<T> writer) {
this.reader = reader;
this.writer = writer;
this.targetClass = targetClass;
}
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
output.writeLong(this.writer.applyAsLong(object));
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return this.reader.apply(input.readLong());
}
@Override
public Class<T> getTargetClass() {
return this.targetClass;
}
@Override
public OptionalInt size(T object) {
return OptionalInt.of(Long.BYTES);
}
}
| 2,338
| 32.898551
| 101
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ObjectExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.function.Function;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Base {@link Externalizer} for object wrapper externalization.
* @author Paul Ferraro
*/
public class ObjectExternalizer<T> implements Externalizer<T> {
private final Function<Object, T> reader;
private final Function<T, Object> writer;
private final Class<T> targetClass;
public ObjectExternalizer(Class<T> targetClass, Function<Object, T> reader, Function<T, Object> writer) {
this.targetClass = targetClass;
this.reader = reader;
this.writer = writer;
}
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
output.writeObject(this.writer.apply(object));
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return this.reader.apply(input.readObject());
}
@Override
public Class<T> getTargetClass() {
return this.targetClass;
}
}
| 2,176
| 34.112903
| 109
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/IdentityFunction.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.marshalling.spi;
import java.util.function.Function;
/**
* Behaves the same as {@link Function#identity()}, where the return type is a superclass of the function parameter.
* @author Paul Ferraro
*/
public enum IdentityFunction implements Function<Object, Object> {
INSTANCE;
@Override
public Object apply(Object value) {
return value;
}
/**
* Returns a function that returns its parameter.
* @param <T> the parameter type
* @param <R> the return type
* @return a function that return its parameter
*/
@SuppressWarnings("unchecked")
public static <T extends R, R> Function<T, R> getInstance() {
return (Function<T, R>) INSTANCE;
}
}
| 1,768
| 34.38
| 116
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ByteBufferInputStream.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.marshalling.spi;
import java.io.ByteArrayInputStream;
import java.nio.ByteBuffer;
/**
* @author Paul Ferraro
*/
public class ByteBufferInputStream extends ByteArrayInputStream {
public ByteBufferInputStream(ByteBuffer buffer) {
super(buffer.array(), buffer.arrayOffset(), buffer.limit() - buffer.arrayOffset());
}
}
| 1,392
| 36.648649
| 91
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/Marshaller.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.marshalling.spi;
import java.io.IOException;
/**
* Marshals an object to and from its serialized form.
* @author Paul Ferraro
* @param V the value type
* @param S the serialized form type
*/
public interface Marshaller<V, S> extends Marshallability {
/**
* Reads a value from its marshalled form.
* @param value the marshalled form
* @return an unmarshalled value/
*/
V read(S value) throws IOException;
/**
* Writes a value to its serialized form
* @param a value to marshal.
* @return the serialized form of the value
*/
S write(V value) throws IOException;
}
| 1,681
| 34.041667
| 70
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/MarshalledValue.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.marshalling.spi;
import java.io.IOException;
/**
* Offers semantics similar to a {@link java.rmi.MarshalledObject#get()}, but supports an independent marshalling context.s
* @author Paul Ferraro
* @param <T> value type
* @param <C> marshalling context type
*/
public interface MarshalledValue<T, C> {
T get(C context) throws IOException;
}
| 1,406
| 38.083333
| 123
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ValueFunction.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.marshalling.spi;
import java.util.function.DoubleFunction;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.LongFunction;
/**
* A function that always results a constant value, ignoring its parameter.
* @author Paul Ferraro
*/
public class ValueFunction<T, R> implements Function<T, R>, IntFunction<R>, LongFunction<R>, DoubleFunction<R> {
private static final ValueFunction<Object, Void> VOID = new ValueFunction<>(null);
/**
* Returns a function that always returns a null result, regardless of input.
* @param <T> the function parameter type
* @return a function that always returns null
*/
@SuppressWarnings("unchecked")
public static <T> ValueFunction<T, Void> voidFunction() {
return (ValueFunction<T, Void>) VOID;
}
private final R result;
public ValueFunction(R result) {
this.result = result;
}
@Override
public R apply(T ignored) {
return this.result;
}
@Override
public R apply(double value) {
return this.result;
}
@Override
public R apply(long value) {
return this.result;
}
@Override
public R apply(int value) {
return this.result;
}
}
| 2,317
| 30.753425
| 112
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/IndexSerializer.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.marshalling.spi;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* Various strategies for marshalling an array/collection index (i.e. an unsigned integer).
* @author Paul Ferraro
*/
public enum IndexSerializer implements IntSerializer {
UNSIGNED_BYTE() {
@Override
public int readInt(DataInput input) throws IOException {
return input.readUnsignedByte();
}
@Override
public void writeInt(DataOutput output, int index) throws IOException {
if (index > (Byte.MAX_VALUE - Byte.MIN_VALUE)) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
output.writeByte(index);
}
@Override
public int size(int value) {
return Byte.BYTES;
}
},
UNSIGNED_SHORT() {
@Override
public int readInt(DataInput input) throws IOException {
return input.readUnsignedShort();
}
@Override
public void writeInt(DataOutput output, int index) throws IOException {
if (index > (Short.MAX_VALUE - Short.MIN_VALUE)) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
output.writeShort(index);
}
@Override
public int size(int value) {
return Short.BYTES;
}
},
INTEGER(),
/**
* Reads/write an unsigned integer using a variable-length format.
* Format requires between 1 and 5 bytes, depending on the index size.
* Smaller values require fewer bytes.
* Logic lifted directly from org.infinispan.commons.io.UnsignedNumeric.
* @author Manik Surtani
*/
VARIABLE() {
@Override
public int readInt(DataInput input) throws IOException {
byte b = input.readByte();
int i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = input.readByte();
i |= (b & 0x7FL) << shift;
}
return i;
}
@Override
public void writeInt(DataOutput output, int index) throws IOException {
int i = index;
while ((i & ~0x7F) != 0) {
output.writeByte((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
output.writeByte((byte) i);
}
@Override
public int size(int index) {
int size = 1;
int i = index;
while ((i & ~0x7F) != 0) {
size += 1;
i >>>= 7;
}
return size;
}
},
;
/**
* Returns the most efficient externalizer for a given index size.
* @param size the size of the index
* @return an index externalizer
*/
public static IntSerializer select(int size) {
if (size < 256) return UNSIGNED_BYTE;
if (size < 65536) return UNSIGNED_SHORT;
if (size < 268435456) return VARIABLE;
return INTEGER;
}
}
| 4,123
| 31.21875
| 91
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/EnumExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.OptionalInt;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Base {@link Externalizer} for enumerations.
* @author Paul Ferraro
*/
public class EnumExternalizer<E extends Enum<E>> implements Externalizer<E> {
private final IntSerializer ordinalSerializer;
private final Class<E> enumClass;
private final E[] values;
public EnumExternalizer(Class<E> enumClass) {
this.ordinalSerializer = IndexSerializer.select(enumClass.getEnumConstants().length);
this.enumClass = enumClass;
this.values = enumClass.getEnumConstants();
}
@Override
public void writeObject(ObjectOutput output, E value) throws IOException {
this.ordinalSerializer.writeInt(output, value.ordinal());
}
@Override
public E readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return this.values[this.ordinalSerializer.readInt(input)];
}
@Override
public Class<E> getTargetClass() {
return this.enumClass;
}
@Override
public OptionalInt size(E value) {
return OptionalInt.of(this.ordinalSerializer.size(value.ordinal()));
}
}
| 2,334
| 33.338235
| 93
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/MarshalledValueFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.marshalling.spi;
/**
* @author Paul Ferraro
*/
public interface MarshalledValueFactory<C> extends Marshallability {
<T> MarshalledValue<T, C> createMarshalledValue(T object);
C getMarshallingContext();
}
| 1,270
| 38.71875
| 70
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ValueExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.OptionalInt;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Trivial {@link Externalizer} for a constant value.
* @author Paul Ferraro
*/
public class ValueExternalizer<T> implements Externalizer<T> {
public static final Externalizer<Void> VOID = new ValueExternalizer<>(null);
private final T value;
public ValueExternalizer(T value) {
this.value = value;
}
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
// Nothing to write
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return this.value;
}
@SuppressWarnings("unchecked")
@Override
public Class<T> getTargetClass() {
return (Class<T>) this.value.getClass();
}
@Override
public OptionalInt size(T object) {
return OptionalInt.of(0);
}
}
| 2,085
| 30.606061
| 87
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/Serializer.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.marshalling.spi;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.OptionalInt;
/**
* Writes/reads an object to/from a binary stream.
* @author Paul Ferraro
*/
public interface Serializer<T> {
/**
* Writes the specified object to the specified output stream
* @param output the data output stream
* @param value an object to serialize
* @throws IOException if an I/O error occurs
*/
void write(DataOutput output, T value) throws IOException;
/**
* Reads an object from the specified input stream.
* @param input a data input stream
* @return the deserialized object
* @throws IOException if an I/O error occurs
*/
T read(DataInput input) throws IOException;
/**
* Returns the size of the buffer to use for marshalling the specified object, if known.
* @return the buffer size (in bytes), or empty if unknown.
*/
default OptionalInt size(T object) {
return OptionalInt.empty();
}
}
| 2,093
| 33.9
| 92
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/IntExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.OptionalInt;
import java.util.function.IntFunction;
import java.util.function.ToIntFunction;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Base {@link Externalizer} for int-based externalization.
* @author Paul Ferraro
*/
public class IntExternalizer<T> implements Externalizer<T> {
private final IntFunction<T> reader;
private final ToIntFunction<T> writer;
private final Class<T> targetClass;
public IntExternalizer(Class<T> targetClass, IntFunction<T> reader, ToIntFunction<T> writer) {
this.reader = reader;
this.writer = writer;
this.targetClass = targetClass;
}
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
output.writeInt(this.writer.applyAsInt(object));
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return this.reader.apply(input.readInt());
}
@Override
public Class<T> getTargetClass() {
return this.targetClass;
}
@Override
public OptionalInt size(T object) {
return OptionalInt.of(Integer.BYTES);
}
}
| 2,329
| 32.768116
| 98
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ByteBufferMarshalledKeyFactory.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.marshalling.spi;
/**
* Factory for creating a {@link ByteBufferMarshalledKey}.
* @author Paul Ferraro
*/
public class ByteBufferMarshalledKeyFactory extends ByteBufferMarshalledValueFactory {
private final ByteBufferMarshaller marshaller;
public ByteBufferMarshalledKeyFactory(ByteBufferMarshaller marshaller) {
super(marshaller);
this.marshaller = marshaller;
}
@Override
public <T> ByteBufferMarshalledKey<T> createMarshalledValue(T object) {
return new ByteBufferMarshalledKey<>(object, this.marshaller);
}
}
| 1,622
| 36.744186
| 86
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/BooleanExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.OptionalInt;
import java.util.function.Function;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Base {@link Externalizer} for boolean-based externalization.
* @author Paul Ferraro
*/
public class BooleanExternalizer<T> implements Externalizer<T> {
private final Class<T> targetClass;
private final Function<Boolean, T> reader;
private final Function<T, Boolean> writer;
public BooleanExternalizer(Class<T> targetClass, Function<Boolean, T> reader, Function<T, Boolean> writer) {
this.targetClass = targetClass;
this.reader = reader;
this.writer = writer;
}
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
output.writeBoolean(this.writer.apply(object));
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return this.reader.apply(input.readBoolean());
}
@Override
public Class<T> getTargetClass() {
return this.targetClass;
}
@Override
public OptionalInt size(T object) {
return OptionalInt.of(Byte.BYTES);
}
}
| 2,318
| 32.608696
| 112
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/DecoratorExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Field;
import java.security.PrivilegedAction;
import java.util.function.UnaryOperator;
import org.wildfly.clustering.marshalling.Externalizer;
import org.wildfly.security.ParametricPrivilegedAction;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Marshaller for a decorator that does not provide public access to its decorated object.
* @author Paul Ferraro
*/
public class DecoratorExternalizer<T> implements Externalizer<T>, ParametricPrivilegedAction<T, T> {
private final Class<T> decoratorClass;
private final UnaryOperator<T> decorator;
private final Field field;
/**
* Constructs a decorator externalizer.
* @param decoratedClass the generalized type of the decorated object
* @param decorator the decoration function
* @param sample a sample object used to determine the type of the decorated object
*/
@SuppressWarnings("unchecked")
public DecoratorExternalizer(Class<T> decoratedClass, UnaryOperator<T> decorator, T sample) {
this.decorator = decorator;
Class<?> decoratorClass = decorator.apply(sample).getClass();
this.decoratorClass = (Class<T>) decoratorClass;
this.field = WildFlySecurityManager.doUnchecked(new PrivilegedAction<Field>() {
@Override
public Field run() {
Field field = findDecoratedField(decoratorClass, decoratedClass);
field.setAccessible(true);
return field;
}
});
}
static Field findDecoratedField(Class<?> decoratorClass, Class<?> decoratedClass) {
for (Field field : decoratorClass.getDeclaredFields()) {
if (field.getType().isAssignableFrom(decoratedClass)) {
return field;
}
}
Class<?> superClass = decoratorClass.getSuperclass();
if (superClass == null) {
throw new IllegalStateException();
}
return findDecoratedField(superClass, decoratedClass);
}
@Override
public Class<T> getTargetClass() {
return this.decoratorClass;
}
@Override
public void writeObject(ObjectOutput output, T value) throws IOException {
T decorated = WildFlySecurityManager.doUnchecked(value, this);
output.writeObject(decorated);
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
@SuppressWarnings("unchecked")
T decorated = (T) input.readObject();
return this.decorator.apply(decorated);
}
@SuppressWarnings("unchecked")
@Override
public T run(T value) {
try {
return (T) this.field.get(value);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
| 3,981
| 35.87037
| 100
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ByteBufferMarshaller.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.marshalling.spi;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.OptionalInt;
import org.jboss.logging.Logger;
/**
* Marshals an object to and from a {@link ByteBuffer}.
* @author Paul Ferraro
*/
public interface ByteBufferMarshaller extends Marshaller<Object, ByteBuffer> {
Logger LOGGER = Logger.getLogger(ByteBufferMarshaller.class);
/**
* Reads an object from the specified input stream.
* @param input an input stream
* @return the unmarshalled object
* @throws IOException if the object could not be read
*/
Object readFrom(InputStream input) throws IOException;
/**
* Writes the specified object to the specified output stream.
* @param output an output stream
* @param object an object to marshal
* @throws IOException if the object could not be written
*/
void writeTo(OutputStream output, Object object) throws IOException;
@Override
default Object read(ByteBuffer buffer) throws IOException {
try (InputStream input = new ByteBufferInputStream(buffer)) {
return this.readFrom(input);
}
}
@Override
default ByteBuffer write(Object object) throws IOException {
OptionalInt size = this.size(object);
try (ByteBufferOutputStream output = new ByteBufferOutputStream(size)) {
this.writeTo(output, object);
ByteBuffer buffer = output.getBuffer();
if (size.isPresent()) {
int predictedSize = size.getAsInt();
int actualSize = buffer.limit() - buffer.arrayOffset();
if (predictedSize < actualSize) {
LOGGER.debugf("Buffer size prediction too small for %s (%s), predicted = %d, actual = %d", object, (object != null) ? object.getClass().getCanonicalName() : null, predictedSize, actualSize);
}
} else {
LOGGER.tracef("Buffer size prediction missing for %s (%s)", object, (object != null) ? object.getClass().getCanonicalName() : null);
}
return buffer;
}
}
/**
* Returns the marshalled size of the specified object.
* @param buffer a byte buffer
* @return the marshalled size of the specified object.
*/
default OptionalInt size(Object object) {
return OptionalInt.empty();
}
}
| 3,485
| 37.307692
| 210
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/MarshallingExternalizerProvider.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.marshalling.spi;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* @author Paul Ferraro
*/
public enum MarshallingExternalizerProvider implements ExternalizerProvider {
MARSHALLED_KEY(new ByteBufferMarshalledKeyExternalizer()),
MARSHALLED_VALUE(new ByteBufferMarshalledValueExternalizer()),
;
private final Externalizer<?> externalizer;
MarshallingExternalizerProvider(Externalizer<?> externalizer) {
this.externalizer = externalizer;
}
@Override
public Externalizer<?> getExternalizer() {
return this.externalizer;
}
}
| 1,645
| 35.577778
| 77
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/IntSerializer.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.marshalling.spi;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* Writes/reads an integer to/from a binary stream.
* @author Paul Ferraro
*/
public interface IntSerializer {
/**
* Writes the specified integer to the specified output stream
* @param output the data output stream
* @param value an integer value
* @throws IOException if an I/O error occurs
*/
default void writeInt(DataOutput output, int value) throws IOException {
output.writeInt(value);
}
/**
* Read an integer from the specified input stream.
* @param input a data input stream
* @return the integer value
* @throws IOException if an I/O error occurs
*/
default int readInt(DataInput input) throws IOException {
return input.readInt();
}
default int size(int value) {
return Integer.BYTES;
}
}
| 1,970
| 32.982759
| 76
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/SynchronizedDecoratorExternalizer.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectOutput;
import java.util.function.UnaryOperator;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* A decorator marshaller that writes the decorated object while holding its monitor lock.
* e.g. to enable iteration over a decorated collection without the risk of a ConcurrentModificationException.
* @author Paul Ferraro
*/
public class SynchronizedDecoratorExternalizer<T> extends DecoratorExternalizer<T> {
/**
* Constructs a decorator externalizer.
* @param decoratedClass the generalized type of the decorated object
* @param decorator the decoration function
* @param sample a sample object used to determine the type of the decorated object
*/
public SynchronizedDecoratorExternalizer(Class<T> decoratedClass, UnaryOperator<T> decorator, T sample) {
super(decoratedClass, decorator, sample);
}
@Override
public void writeObject(ObjectOutput output, T value) throws IOException {
T decorated = WildFlySecurityManager.doUnchecked(value, this);
synchronized (decorated) {
output.writeObject(decorated);
}
}
}
| 2,250
| 39.196429
| 110
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ByteBufferMarshalledValue.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.OptionalInt;
import org.jboss.logging.Logger;
/**
* {@link MarshalledValue} implementation that uses a {@link ByteBufferMarshaller}.
* @author Paul Ferraro
* @param <T> the type wrapped by this marshalled value
*/
public class ByteBufferMarshalledValue<T> implements MarshalledValue<T, ByteBufferMarshaller>, Serializable {
private static final long serialVersionUID = -8419893544424515905L;
private static final Logger LOGGER = Logger.getLogger(ByteBufferMarshalledValue.class);
private transient volatile ByteBufferMarshaller marshaller;
private transient volatile T object;
private transient volatile ByteBuffer buffer;
/**
* Constructs a marshalled value from the specified object and marshaller.
* @param object the wrapped object
* @param marshaller a marshaller suitable for marshalling the specified object
*/
public ByteBufferMarshalledValue(T object, ByteBufferMarshaller marshaller) {
this.marshaller = marshaller;
this.object = object;
}
/**
* Constructs a marshalled value from the specified byte buffer.
* This constructor is only public to facilitate marshallers of this object (from other packages).
* The byte buffer parameter must not be read outside the context of this object.
* @param buffer a byte buffer
*/
public ByteBufferMarshalledValue(ByteBuffer buffer) {
// Normally, we would create a defensive ByteBuffer.asReadOnlyBuffer()
// but this would preclude the use of operations on the backing array.
this.buffer = buffer;
}
// Used for testing purposes only
T peek() {
return this.object;
}
public synchronized boolean isEmpty() {
return (this.buffer == null) && (this.object == null);
}
public synchronized ByteBuffer getBuffer() throws IOException {
ByteBuffer buffer = this.buffer;
if ((buffer == null) && (this.object != null)) {
// Since the wrapped object is likely mutable, we cannot cache the generated buffer
buffer = this.marshaller.write(this.object);
// N.B. Refrain from logging wrapped object
// If wrapped object contains an EJB proxy, toString() will trigger an EJB invocation!
LOGGER.debugf("Marshalled size of %s object = %d bytes", this.object.getClass().getCanonicalName(), buffer.limit() - buffer.arrayOffset());
}
return buffer;
}
public synchronized OptionalInt size() {
// N.B. Buffer position is guarded by synchronization on this object
// We invalidate buffer upon reading it, ensuring that ByteBuffer.remaining() returns the effective buffer size
return (this.buffer != null) ? OptionalInt.of(this.buffer.remaining()) : this.marshaller.size(this.object);
}
@SuppressWarnings("unchecked")
@Override
public synchronized T get(ByteBufferMarshaller marshaller) throws IOException {
if (this.object == null) {
this.marshaller = marshaller;
if (this.buffer != null) {
// Invalidate buffer after reading object
this.object = (T) this.marshaller.read(this.buffer);
this.buffer = null;
}
}
return this.object;
}
@Override
public int hashCode() {
return Objects.hashCode(this.object);
}
@Override
public boolean equals(Object object) {
if ((object == null) || !(object instanceof ByteBufferMarshalledValue)) return false;
@SuppressWarnings("unchecked")
ByteBufferMarshalledValue<T> value = (ByteBufferMarshalledValue<T>) object;
Object ourObject = this.object;
Object theirObject = value.object;
if ((ourObject != null) && (theirObject != null)) {
return ourObject.equals(theirObject);
}
try {
ByteBuffer us = this.getBuffer();
ByteBuffer them = value.getBuffer();
return ((us != null) && (them != null)) ? us.equals(them) : (us == them);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public String toString() {
// N.B. Refrain from logging wrapped object
// If wrapped object contains an EJB proxy, toString() will trigger an EJB invocation!
return String.format("%s [%s]", this.getClass().getName(), (this.object != null) ? this.object.getClass().getName() : "<serialized>");
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
ByteBufferMarshalledValueExternalizer.writeBuffer(out, this.getBuffer());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
this.buffer = ByteBufferMarshalledValueExternalizer.readBuffer(in);
}
}
| 6,179
| 39.657895
| 151
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/SimpleFormatter.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.marshalling.spi;
import java.util.function.Function;
/**
* {@link Formatter} for keys with a simple string representation.
* @author Paul Ferraro
*/
public class SimpleFormatter<K> implements Formatter<K> {
private final Class<K> targetClass;
private final Function<String, K> parser;
private final Function<K, String> formatter;
public SimpleFormatter(Class<K> targetClass, Function<String, K> parser) {
this(targetClass, parser, Object::toString);
}
public SimpleFormatter(Class<K> targetClass, Function<String, K> parser, Function<K, String> formatter) {
this.targetClass = targetClass;
this.parser = parser;
this.formatter = formatter;
}
@Override
public Class<K> getTargetClass() {
return this.targetClass;
}
@Override
public K parse(String value) {
return this.parser.apply(value);
}
@Override
public String format(K key) {
return this.formatter.apply(key);
}
}
| 2,054
| 32.145161
| 109
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/Marshallability.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.marshalling.spi;
/**
* @author Paul Ferraro
*/
public interface Marshallability {
/**
* Indicates whether the specified object can be marshalled.
* @param object an object to be marshalled
* @return true, if the specified object can be marshalled, false otherwise
*/
boolean isMarshallable(Object object);
}
| 1,394
| 37.75
| 79
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ByteBufferOutputStream.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.marshalling.spi;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.OptionalInt;
/**
* A specialized ByteArrayOutputStream that exposes the internal buffer.
* @author Paul Ferraro
*/
public final class ByteBufferOutputStream extends ByteArrayOutputStream {
public ByteBufferOutputStream() {
this(OptionalInt.empty());
}
public ByteBufferOutputStream(OptionalInt size) {
this(size.orElse(512));
}
public ByteBufferOutputStream(int size) {
super(size);
}
/**
* Returns the internal buffer of this output stream.
* @return the internal byte buffer.
*/
public ByteBuffer getBuffer() {
return ByteBuffer.wrap(this.buf, 0, this.count);
}
}
| 1,813
| 31.981818
| 73
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/ByteBufferMarshalledKey.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.marshalling.spi;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.util.Objects;
/**
* {@link MarshalledValue} implementation suitable for map keys that uses a {@link ByteBufferMarshaller}.
* @author Paul Ferraro
*/
public class ByteBufferMarshalledKey<T> extends ByteBufferMarshalledValue<T> {
private static final long serialVersionUID = 7317347779979133897L;
private transient volatile int hashCode;
public ByteBufferMarshalledKey(T object, ByteBufferMarshaller marshaller) {
super(object, marshaller);
this.hashCode = Objects.hashCode(object);
}
public ByteBufferMarshalledKey(ByteBuffer buffer, int hashCode) {
super(buffer);
this.hashCode = hashCode;
}
@Override
public int hashCode() {
return this.hashCode;
}
@Override
public boolean equals(Object object) {
// Optimize by verifying equality of hash code first
if ((object == null) || !(object instanceof ByteBufferMarshalledKey) || (this.hashCode != object.hashCode())) return false;
return super.equals(object);
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeInt(this.hashCode);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
this.hashCode = in.readInt();
}
}
| 2,564
| 34.625
| 131
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/io/ExternalizableExternalizer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.marshalling.spi.io;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.InvocationTargetException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import org.wildfly.clustering.marshalling.Externalizer;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Externalizer for Externalizable objects.
* @author Paul Ferraro
*/
public class ExternalizableExternalizer<T extends Externalizable> implements Externalizer<T> {
private final Class<T> targetClass;
public ExternalizableExternalizer(Class<T> targetClass) {
this.targetClass = targetClass;
}
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
object.writeExternal(output);
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
PrivilegedExceptionAction<T> action = new PrivilegedExceptionAction<>() {
@Override
public T run() throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return ExternalizableExternalizer.this.getTargetClass().getConstructor().newInstance();
}
};
try {
T object = WildFlySecurityManager.doChecked(action);
object.readExternal(input);
return object;
} catch (PrivilegedActionException e) {
throw new IOException(e.getCause());
}
}
@Override
public Class<T> getTargetClass() {
return this.targetClass;
}
}
| 2,740
| 36.040541
| 132
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/sql/SQLExternalizerProvider.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.marshalling.spi.sql;
import java.sql.Date;
import java.sql.Time;
import org.wildfly.clustering.marshalling.Externalizer;
import org.wildfly.clustering.marshalling.spi.ExternalizerProvider;
import org.wildfly.clustering.marshalling.spi.util.DateExternalizer;
/**
* @author Paul Ferraro
*/
public enum SQLExternalizerProvider implements ExternalizerProvider {
SQL_DATE(new DateExternalizer<>(Date.class, Date::new)),
SQL_TIME(new DateExternalizer<>(Time.class, Time::new)),
SQL_TIMESTAMP(new TimestampExternalizer()),
;
private final Externalizer<?> externalizer;
SQLExternalizerProvider(Externalizer<?> externalizer) {
this.externalizer = externalizer;
}
@Override
public Externalizer<?> getExternalizer() {
return this.externalizer;
}
}
| 1,856
| 34.711538
| 70
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/sql/TimestampExternalizer.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.marshalling.spi.sql;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.sql.Timestamp;
import java.util.OptionalInt;
import org.wildfly.clustering.marshalling.spi.util.DateExternalizer;
/**
* Externalizer for a {@link Timestamp}.
* @author Radoslav Husar
*/
public class TimestampExternalizer extends DateExternalizer<Timestamp> {
public TimestampExternalizer() {
super(Timestamp.class, Timestamp::new);
}
@Override
public void writeObject(ObjectOutput output, Timestamp timestamp) throws IOException {
super.writeObject(output, timestamp);
output.writeInt(timestamp.getNanos());
}
@Override
public Timestamp readObject(ObjectInput input) throws IOException, ClassNotFoundException {
Timestamp timestamp = super.readObject(input);
timestamp.setNanos(input.readInt());
return timestamp;
}
@Override
public OptionalInt size(Timestamp object) {
return OptionalInt.of(Long.BYTES + Integer.BYTES);
}
}
| 2,106
| 34.711864
| 95
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/util/OptionalDoubleExternalizer.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.marshalling.spi.util;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Externalizer for an {@link OptionalDouble}.
* @author Paul Ferraro
*/
public class OptionalDoubleExternalizer implements Externalizer<OptionalDouble> {
@Override
public void writeObject(ObjectOutput output, OptionalDouble value) throws IOException {
boolean present = value.isPresent();
output.writeBoolean(present);
if (present) {
output.writeDouble(value.getAsDouble());
}
}
@Override
public OptionalDouble readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return (input.readBoolean()) ? OptionalDouble.of(input.readDouble()) : OptionalDouble.empty();
}
@Override
public OptionalInt size(OptionalDouble value) {
return OptionalInt.of(value.isPresent() ? Double.BYTES + Byte.BYTES : Byte.BYTES);
}
@Override
public Class<OptionalDouble> getTargetClass() {
return OptionalDouble.class;
}
}
| 2,228
| 34.380952
| 102
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/util/UtilExternalizerProvider.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.marshalling.spi.util;
import java.util.AbstractMap;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import org.wildfly.clustering.marshalling.Externalizer;
import org.wildfly.clustering.marshalling.spi.DecoratorExternalizer;
import org.wildfly.clustering.marshalling.spi.ExternalizerProvider;
import org.wildfly.clustering.marshalling.spi.ObjectExternalizer;
import org.wildfly.clustering.marshalling.spi.StringExternalizer;
import org.wildfly.clustering.marshalling.spi.SynchronizedDecoratorExternalizer;
import org.wildfly.clustering.marshalling.spi.ValueExternalizer;
/**
* Externalizers for the java.util package
* @author Paul Ferraro
*/
public enum UtilExternalizerProvider implements ExternalizerProvider {
ARRAY_DEQUE(new BoundedCollectionExternalizer<>(ArrayDeque.class, ArrayDeque::new)),
ARRAY_LIST(new BoundedCollectionExternalizer<>(ArrayList.class, ArrayList::new)),
BIT_SET(new BitSetExternalizer()),
CALENDAR(new CalendarExternalizer()),
CURRENCY(new StringExternalizer<>(Currency.class, Currency::getInstance, Currency::getCurrencyCode)),
DATE(new DateExternalizer<>(Date.class, Date::new)),
EMPTY_LIST(new ValueExternalizer<>(Collections.emptyList())),
EMPTY_MAP(new ValueExternalizer<>(Collections.emptyMap())),
EMPTY_NAVIGABLE_MAP(new ValueExternalizer<>(Collections.emptyNavigableMap())),
EMPTY_NAVIGABLE_SET(new ValueExternalizer<>(Collections.emptyNavigableSet())),
EMPTY_SET(new ValueExternalizer<>(Collections.emptySet())),
EMPTY_SORTED_MAP(new ValueExternalizer<>(Collections.emptySortedMap())),
EMPTY_SORTED_SET(new ValueExternalizer<>(Collections.emptySortedSet())),
ENUM_MAP(new EnumMapExternalizer<>()),
ENUM_SET(new EnumSetExternalizer<>()),
HASH_MAP(new HashMapExternalizer<>(HashMap.class, HashMap::new)),
HASH_SET(new HashSetExternalizer<>(HashSet.class, HashSet::new)),
LINKED_HASH_MAP(new LinkedHashMapExternalizer()),
LINKED_HASH_SET(new HashSetExternalizer<>(LinkedHashSet.class, LinkedHashSet::new)),
LINKED_LIST(new UnboundedCollectionExternalizer<>(LinkedList.class, LinkedList::new)),
LIST12(new UnmodifiableCollectionExternalizer<>(List.of(Boolean.TRUE).getClass().asSubclass(List.class), List::of)),
LISTN(new UnmodifiableCollectionExternalizer<>(List.of().getClass().asSubclass(List.class), List::of)),
LOCALE(new StringExternalizer<>(Locale.class, Locale::forLanguageTag, Locale::toLanguageTag)),
MAP1(new UnmodifiableMapExternalizer<>(Map.of(Boolean.TRUE, Boolean.FALSE).getClass().asSubclass(Map.class), Map::ofEntries)),
MAPN(new UnmodifiableMapExternalizer<>(Map.of().getClass().asSubclass(Map.class), Map::ofEntries)),
NATURAL_ORDER_COMPARATOR(new ValueExternalizer<>(Comparator.naturalOrder())),
@SuppressWarnings({ "unchecked", "rawtypes" })
OPTIONAL(new ObjectExternalizer<Optional>(Optional.class, Optional::ofNullable, optional -> optional.orElse(null)) {
@Override
public OptionalInt size(Optional optional) {
return optional.isPresent() ? OptionalInt.empty() : OptionalInt.of(Byte.BYTES);
}
}),
OPTIONAL_DOUBLE(new OptionalDoubleExternalizer()),
OPTIONAL_INT(new OptionalIntExternalizer()),
OPTIONAL_LONG(new OptionalLongExternalizer()),
REVERSE_ORDER_COMPARATOR(new ValueExternalizer<>(Collections.reverseOrder())),
SET12(new UnmodifiableCollectionExternalizer<>(Set.of(Boolean.TRUE).getClass().asSubclass(Set.class), Set::of)),
SETN(new UnmodifiableCollectionExternalizer<>(Set.of().getClass().asSubclass(Set.class), Set::of)),
SIMPLE_ENTRY(new MapEntryExternalizer<>(AbstractMap.SimpleEntry.class, AbstractMap.SimpleEntry::new)),
SIMPLE_IMMUTABLE_ENTRY(new MapEntryExternalizer<>(AbstractMap.SimpleImmutableEntry.class, AbstractMap.SimpleImmutableEntry::new)),
SINGLETON_LIST(new SingletonCollectionExternalizer<>(Collections::singletonList)),
SINGLETON_MAP(new SingletonMapExternalizer()),
SINGLETON_SET(new SingletonCollectionExternalizer<>(Collections::singleton)),
SYNCHRONIZED_COLLECTION(new SynchronizedDecoratorExternalizer<>(Collection.class, Collections::synchronizedCollection, Collections.emptyList())),
SYNCHRONIZED_LIST(new SynchronizedDecoratorExternalizer<>(List.class, Collections::synchronizedList, new LinkedList<>())),
SYNCHRONIZED_MAP(new SynchronizedDecoratorExternalizer<>(Map.class, Collections::synchronizedMap, Collections.emptyMap())),
SYNCHRONIZED_NAVIGABLE_MAP(new SynchronizedDecoratorExternalizer<>(NavigableMap.class, Collections::synchronizedNavigableMap, Collections.emptyNavigableMap())),
SYNCHRONIZED_NAVIGABLE_SET(new SynchronizedDecoratorExternalizer<>(NavigableSet.class, Collections::synchronizedNavigableSet, Collections.emptyNavigableSet())),
SYNCHRONIZED_RANDOM_ACCESS_LIST(new SynchronizedDecoratorExternalizer<>(List.class, Collections::synchronizedList, Collections.emptyList())),
SYNCHRONIZED_SET(new SynchronizedDecoratorExternalizer<>(Set.class, Collections::synchronizedSet, Collections.emptySet())),
SYNCHRONIZED_SORTED_MAP(new SynchronizedDecoratorExternalizer<>(SortedMap.class, Collections::synchronizedSortedMap, Collections.emptySortedMap())),
SYNCHRONIZED_SORTED_SET(new SynchronizedDecoratorExternalizer<>(SortedSet.class, Collections::synchronizedSortedSet, Collections.emptySortedSet())),
TIME_ZONE(new StringExternalizer<>(TimeZone.class, TimeZone::getTimeZone, TimeZone::getID)),
TREE_MAP(new SortedMapExternalizer<>(TreeMap.class, TreeMap::new)),
TREE_SET(new SortedSetExternalizer<>(TreeSet.class, TreeSet::new)),
UNMODIFIABLE_COLLECTION(new DecoratorExternalizer<>(Collection.class, Collections::unmodifiableCollection, Collections.emptyList())),
UNMODIFIABLE_LIST(new DecoratorExternalizer<>(List.class, Collections::unmodifiableList, new LinkedList<>())),
UNMODIFIABLE_MAP(new DecoratorExternalizer<>(Map.class, Collections::unmodifiableMap, Collections.emptyMap())),
UNMODIFIABLE_NAVIGABLE_MAP(new DecoratorExternalizer<>(NavigableMap.class, Collections::unmodifiableNavigableMap, Collections.emptyNavigableMap())),
UNMODIFIABLE_NAVIGABLE_SET(new DecoratorExternalizer<>(NavigableSet.class, Collections::unmodifiableNavigableSet, Collections.emptyNavigableSet())),
UNMODIFIABLE_RANDOM_ACCESS_LIST(new DecoratorExternalizer<>(List.class, Collections::unmodifiableList, Collections.emptyList())),
UNMODIFIABLE_SET(new DecoratorExternalizer<>(Set.class, Collections::unmodifiableSet, Collections.emptySet())),
UNMODIFIABLE_SORTED_MAP(new DecoratorExternalizer<>(SortedMap.class, Collections::unmodifiableSortedMap, Collections.emptySortedMap())),
UNMODIFIABLE_SORTED_SET(new DecoratorExternalizer<>(SortedSet.class, Collections::unmodifiableSortedSet, Collections.emptySortedSet())),
UUID(new UUIDExternalizer()),
;
private final Externalizer<?> externalizer;
UtilExternalizerProvider(Externalizer<?> externalizer) {
this.externalizer = externalizer;
}
@Override
public Externalizer<?> getExternalizer() {
return this.externalizer;
}
}
| 8,759
| 60.258741
| 164
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/util/BitSetExternalizer.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.marshalling.spi.util;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.BitSet;
import java.util.OptionalInt;
import org.wildfly.clustering.marshalling.Externalizer;
import org.wildfly.clustering.marshalling.spi.IndexSerializer;
/**
* @author Paul Ferraro
*/
public class BitSetExternalizer implements Externalizer<BitSet> {
@Override
public void writeObject(ObjectOutput output, BitSet set) throws IOException {
byte[] bytes = set.toByteArray();
IndexSerializer.VARIABLE.writeInt(output, bytes.length);
output.write(bytes);
}
@Override
public BitSet readObject(ObjectInput input) throws IOException, ClassNotFoundException {
byte[] bytes = new byte[IndexSerializer.VARIABLE.readInt(input)];
input.readFully(bytes);
return BitSet.valueOf(bytes);
}
@Override
public OptionalInt size(BitSet set) {
int size = set.size();
int bytes = size / Byte.SIZE;
if (size % Byte.SIZE > 0) {
bytes += 1;
}
return OptionalInt.of(IndexSerializer.VARIABLE.size(bytes) + bytes);
}
@Override
public Class<BitSet> getTargetClass() {
return BitSet.class;
}
}
| 2,309
| 32.970588
| 92
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/util/LinkedHashMapExternalizer.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.marshalling.spi.util;
import static org.wildfly.clustering.marshalling.spi.util.HashSetExternalizer.DEFAULT_LOAD_FACTOR;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import org.wildfly.clustering.marshalling.spi.BooleanExternalizer;
/**
* @author Paul Ferraro
*/
public class LinkedHashMapExternalizer extends MapExternalizer<LinkedHashMap<Object, Object>, Boolean, Map.Entry<Boolean, Integer>> {
public static final Function<Map.Entry<Boolean, Integer>, LinkedHashMap<Object, Object>> FACTORY = new Function<>() {
@Override
public LinkedHashMap<Object, Object> apply(Map.Entry<Boolean, Integer> entry) {
int size = entry.getValue();
int capacity = HashSetExternalizer.CAPACITY.applyAsInt(size);
return new LinkedHashMap<>(capacity, DEFAULT_LOAD_FACTOR, entry.getKey());
}
};
public static final Function<LinkedHashMap<Object, Object>, Boolean> ACCESS_ORDER = new Function<>() {
@Override
public Boolean apply(LinkedHashMap<Object, Object> map) {
Object insertOrder = new Object();
Object accessOrder = new Object();
map.put(insertOrder, null);
map.put(accessOrder, null);
// Access first inserted entry
// If map uses access order, this element will move to the tail of the map
map.get(insertOrder);
Iterator<Object> keys = map.keySet().iterator();
Object element = keys.next();
while ((element != insertOrder) && (element != accessOrder)) {
element = keys.next();
}
map.remove(insertOrder);
map.remove(accessOrder);
return element == accessOrder;
}
};
@SuppressWarnings("unchecked")
public LinkedHashMapExternalizer() {
super((Class<LinkedHashMap<Object, Object>>) (Class<?>) LinkedHashMap.class, FACTORY, Function.identity(), ACCESS_ORDER, new BooleanExternalizer<>(Boolean.class, Function.identity(), Function.identity()));
}
}
| 3,172
| 41.878378
| 213
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/util/CopyOnWriteCollectionExternalizer.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.marshalling.spi.util;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.OptionalInt;
import java.util.function.Function;
import org.wildfly.clustering.marshalling.Externalizer;
/**
* Externalizer for copy-on-write implementations of {@link Collection}.
* @author Paul Ferraro
*/
public class CopyOnWriteCollectionExternalizer<T extends Collection<Object>> implements Externalizer<T> {
@SuppressWarnings("unchecked")
private static final Externalizer<Collection<Object>> COLLECTION_EXTERNALIZER = new BoundedCollectionExternalizer<>((Class<Collection<Object>>) (Class<?>) ArrayList.class, ArrayList::new);
private final Class<T> targetClass;
private final Function<Collection<Object>, T> factory;
@SuppressWarnings("unchecked")
public CopyOnWriteCollectionExternalizer(Class<?> targetClass, Function<Collection<Object>, T> factory) {
this.targetClass = (Class<T>) targetClass;
this.factory = factory;
}
@Override
public OptionalInt size(T collection) {
return COLLECTION_EXTERNALIZER.size(collection);
}
@Override
public void writeObject(ObjectOutput output, T collection) throws IOException {
COLLECTION_EXTERNALIZER.writeObject(output, collection);
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
// Collect all elements first to avoid COW costs per element.
return this.factory.apply(COLLECTION_EXTERNALIZER.readObject(input));
}
@Override
public Class<T> getTargetClass() {
return this.targetClass;
}
}
| 2,762
| 36.849315
| 192
|
java
|
null |
wildfly-main/clustering/marshalling/spi/src/main/java/org/wildfly/clustering/marshalling/spi/util/EnumMapExternalizer.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.marshalling.spi.util;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Field;
import java.security.PrivilegedAction;
import java.util.BitSet;
import java.util.EnumMap;
import java.util.Iterator;
import org.wildfly.clustering.marshalling.Externalizer;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Externalizer for an {@link EnumMap}.
* @author Paul Ferraro
*/
public class EnumMapExternalizer<E extends Enum<E>> implements Externalizer<EnumMap<E, Object>> {
static final Field ENUM_MAP_KEY_CLASS_FIELD = WildFlySecurityManager.doUnchecked(new PrivilegedAction<Field>() {
@Override
public Field run() {
for (Field field : EnumMap.class.getDeclaredFields()) {
if (field.getType() == Class.class) {
field.setAccessible(true);
return field;
}
}
throw new IllegalStateException();
}
});
@Override
public void writeObject(ObjectOutput output, EnumMap<E, Object> map) throws IOException {
Class<?> enumClass = this.findEnumClass(map);
output.writeObject(enumClass);
Object[] enumValues = enumClass.getEnumConstants();
// Represent EnumMap keys as a BitSet
BitSet keys = new BitSet(enumValues.length);
for (int i = 0; i < enumValues.length; ++i) {
keys.set(i, map.containsKey(enumValues[i]));
}
UtilExternalizerProvider.BIT_SET.writeObject(output, keys);
for (Object value : map.values()) {
output.writeObject(value);
}
}
@SuppressWarnings("unchecked")
@Override
public EnumMap<E, Object> readObject(ObjectInput input) throws IOException, ClassNotFoundException {
Class<E> enumClass = (Class<E>) input.readObject();
BitSet keys = UtilExternalizerProvider.BIT_SET.cast(BitSet.class).readObject(input);
EnumMap<E, Object> map = new EnumMap<>(enumClass);
Object[] enumValues = enumClass.getEnumConstants();
for (int i = 0; i < enumValues.length; ++i) {
if (keys.get(i)) {
map.put((E) enumValues[i], input.readObject());
}
}
return map;
}
@SuppressWarnings("unchecked")
@Override
public Class<EnumMap<E, Object>> getTargetClass() {
return (Class<EnumMap<E, Object>>) (Class<?>) EnumMap.class;
}
private Class<?> findEnumClass(EnumMap<E, Object> map) {
Iterator<E> values = map.keySet().iterator();
if (values.hasNext()) {
return values.next().getDeclaringClass();
}
// If EnumMap is empty, we need to resort to reflection to obtain the enum type
return WildFlySecurityManager.doUnchecked(new PrivilegedAction<Class<?>>() {
@Override
public Class<?> run() {
try {
return (Class<?>) ENUM_MAP_KEY_CLASS_FIELD.get(map);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
});
}
}
| 4,220
| 37.027027
| 116
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.