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/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/group/UUIDMarshaller.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.server.infinispan.group;
import java.io.IOException;
import org.jgroups.util.UUID;
import org.wildfly.clustering.marshalling.protostream.FunctionalMarshaller;
import org.wildfly.common.function.ExceptionFunction;
/**
* Marshaller for a {@link UUID} address.
* @author Paul Ferraro
*/
public class UUIDMarshaller extends FunctionalMarshaller<UUID, java.util.UUID> {
private static final ExceptionFunction<UUID, java.util.UUID, IOException> FUNCTION = new ExceptionFunction<>() {
@Override
public java.util.UUID apply(UUID uuid) throws IOException {
return new java.util.UUID(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits());
}
};
private static final ExceptionFunction<java.util.UUID, UUID, IOException> FACTORY = new ExceptionFunction<>() {
@Override
public UUID apply(java.util.UUID uuid) throws IOException {
return new UUID(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits());
}
};
public UUIDMarshaller() {
super(UUID.class, java.util.UUID.class, FUNCTION, FACTORY);
}
}
| 2,167
| 39.148148
| 116
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/group/LocalNodeFormatter.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.server.infinispan.group;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.Externalizer;
import org.wildfly.clustering.marshalling.spi.Formatter;
import org.wildfly.clustering.marshalling.spi.StringExternalizer;
/**
* Resolver for a {@link LocalNode}.
* @author Paul Ferraro
*/
@MetaInfServices(Formatter.class)
public class LocalNodeFormatter implements Formatter<LocalNode> {
@Override
public Class<LocalNode> getTargetClass() {
return LocalNode.class;
}
@Override
public LocalNode parse(String name) {
return new LocalNode(name);
}
@Override
public String format(LocalNode node) {
return node.getName();
}
@MetaInfServices(Externalizer.class)
public static class LocalNodeExternalizer extends StringExternalizer<LocalNode> {
public LocalNodeExternalizer() {
super(new LocalNodeFormatter());
}
}
}
| 1,992
| 32.779661
| 85
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/group/LocalAddressSerializer.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.server.infinispan.group;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.LocalModeAddress;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.Externalizer;
import org.wildfly.clustering.marshalling.spi.BinaryFormatter;
import org.wildfly.clustering.marshalling.spi.Formatter;
import org.wildfly.clustering.marshalling.spi.Serializer;
import org.wildfly.clustering.marshalling.spi.SerializerExternalizer;
/**
* Serializer for a local {@link Address}.
* @author Paul Ferraro
*/
public enum LocalAddressSerializer implements Serializer<Address> {
INSTANCE;
@Override
public void write(DataOutput output, Address value) throws IOException {
}
@Override
public Address read(DataInput input) throws IOException {
return LocalModeAddress.INSTANCE;
}
@MetaInfServices(Externalizer.class)
public static class LocalAddressExternalizer extends SerializerExternalizer<Address> {
@SuppressWarnings("unchecked")
public LocalAddressExternalizer() {
super((Class<Address>) (Class<?>) LocalModeAddress.class, INSTANCE);
}
}
@MetaInfServices(Formatter.class)
public static class LocalAddressFormatter extends BinaryFormatter<Address> {
@SuppressWarnings("unchecked")
public LocalAddressFormatter() {
super((Class<Address>) (Class<?>) LocalModeAddress.class, INSTANCE);
}
}
}
| 2,605
| 36.228571
| 90
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/group/InfinispanTransportMarshallerProvider.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.server.infinispan.group;
import org.infinispan.remoting.transport.LocalModeAddress;
import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller;
import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshallerProvider;
import org.wildfly.clustering.marshalling.protostream.ValueMarshaller;
/**
* Provider of marshallers for the org.infinispan.remoting.transport package.
* @author Paul Ferraro
*/
public enum InfinispanTransportMarshallerProvider implements ProtoStreamMarshallerProvider {
LOCAL_ADDRESS(new ValueMarshaller<>(LocalModeAddress.INSTANCE)),
;
private final ProtoStreamMarshaller<?> marshaller;
InfinispanTransportMarshallerProvider(ProtoStreamMarshaller<?> marshaller) {
this.marshaller = marshaller;
}
@Override
public ProtoStreamMarshaller<?> getMarshaller() {
return this.marshaller;
}
}
| 1,942
| 39.479167
| 92
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/group/AddressSerializer.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.server.infinispan.group;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.jgroups.Address;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.UUID;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.Externalizer;
import org.wildfly.clustering.marshalling.spi.Serializer;
import org.wildfly.clustering.marshalling.spi.SerializerExternalizer;
/**
* Serializer for a JGroups {@link Address}.
* @author Paul Ferraro
*/
public enum AddressSerializer implements Serializer<Address> {
INSTANCE;
@Override
public void write(DataOutput output, Address address) throws IOException {
org.jgroups.util.Util.writeAddress(address, output);
}
@Override
public Address read(DataInput input) throws IOException {
try {
return org.jgroups.util.Util.readAddress(input);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
@MetaInfServices(Externalizer.class)
public static class UUIDExternalizer extends SerializerExternalizer<Address> {
@SuppressWarnings("unchecked")
public UUIDExternalizer() {
super((Class<Address>) (Class<?>) UUID.class, INSTANCE);
}
}
@MetaInfServices(Externalizer.class)
public static class IpAddressExternalizer extends SerializerExternalizer<Address> {
@SuppressWarnings("unchecked")
public IpAddressExternalizer() {
super((Class<Address>) (Class<?>) IpAddress.class, INSTANCE);
}
}
}
| 2,641
| 34.702703
| 87
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/group/GroupListenerNotificationTask.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.server.infinispan.group;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Consumer;
import org.wildfly.clustering.group.GroupListener;
import org.wildfly.clustering.group.Membership;
import org.wildfly.clustering.server.infinispan.ClusteringServerLogger;
/**
* A task that notifies a set of {@link GroupListener} instances.
* @author Paul Ferraro
*/
public class GroupListenerNotificationTask implements Runnable, Consumer<GroupListener> {
private final Iterable<Map.Entry<GroupListener, ExecutorService>> listeners;
private final Membership previous;
private final Membership current;
private final boolean merged;
public GroupListenerNotificationTask(Iterable<Map.Entry<GroupListener, ExecutorService>> listeners, Membership previous, Membership current, boolean merged) {
this.listeners = listeners;
this.previous = previous;
this.current = current;
this.merged = merged;
}
@Override
public void run() {
for (Map.Entry<GroupListener, ExecutorService> entry : this.listeners) {
GroupListener listener = entry.getKey();
ExecutorService executor = entry.getValue();
try {
executor.execute(() -> this.accept(listener));
} catch (RejectedExecutionException e) {
// Listener was unregistered
}
}
}
@Override
public void accept(GroupListener listener) {
try {
listener.membershipChanged(this.previous, this.current, this.merged);
} catch (Throwable e) {
ClusteringServerLogger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e);
}
}
}
| 2,824
| 38.236111
| 162
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/group/CacheGroup.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.server.infinispan.group;
import java.util.Collections;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.infinispan.Cache;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.TransportConfiguration;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener.Observation;
import org.infinispan.notifications.cachelistener.annotation.TopologyChanged;
import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent;
import org.infinispan.notifications.cachemanagerlistener.annotation.Merged;
import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged;
import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.jgroups.JGroupsAddress;
import org.infinispan.util.concurrent.BlockingManager;
import org.wildfly.clustering.Registration;
import org.wildfly.clustering.context.DefaultExecutorService;
import org.wildfly.clustering.context.ExecutorServiceFactory;
import org.wildfly.clustering.group.GroupListener;
import org.wildfly.clustering.group.Membership;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.server.NodeFactory;
import org.wildfly.clustering.server.group.Group;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* {@link Group} implementation based on the topology of a cache.
* @author Paul Ferraro
*/
@org.infinispan.notifications.Listener(observation = Observation.POST)
public class CacheGroup implements AutoCloseableGroup<Address>, AutoCloseable, Function<GroupListener, ExecutorService> {
private final Map<GroupListener, ExecutorService> listeners = new ConcurrentHashMap<>();
private final Cache<?, ?> cache;
private final NodeFactory<org.jgroups.Address> nodeFactory;
private final SortedMap<Integer, Boolean> views = Collections.synchronizedSortedMap(new TreeMap<>());
private final BlockingManager blocking;
private final Executor executor;
public CacheGroup(CacheGroupConfiguration config) {
this.cache = config.getCache();
this.nodeFactory = config.getMemberFactory();
this.blocking = config.getBlockingManager();
this.executor = this.blocking.asExecutor(this.getClass().getName());
this.cache.getCacheManager().addListener(this);
this.cache.addListener(this);
}
@Override
public void close() {
this.cache.removeListener(this);
this.cache.getCacheManager().removeListener(this);
// Cleanup any unregistered listeners
for (ExecutorService executor : this.listeners.values()) {
this.shutdown(executor);
}
this.listeners.clear();
}
private void shutdown(ExecutorService executor) {
WildFlySecurityManager.doUnchecked(executor, DefaultExecutorService.SHUTDOWN_NOW_ACTION);
try {
executor.awaitTermination(this.cache.getCacheConfiguration().transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public String getName() {
GlobalConfiguration global = this.cache.getCacheManager().getCacheManagerConfiguration();
TransportConfiguration transport = global.transport();
return transport.transport() != null ? transport.clusterName() : global.cacheManagerName();
}
@Override
public Node getLocalMember() {
return this.createNode(this.cache.getCacheManager().getAddress());
}
@Override
public Membership getMembership() {
EmbeddedCacheManager manager = this.cache.getCacheManager();
DistributionManager dist = this.cache.getAdvancedCache().getDistributionManager();
return (dist != null) ? new CacheMembership(manager.getAddress(), dist.getCacheTopology(), this) : new CacheMembership(manager, this);
}
@Override
public boolean isSingleton() {
return false;
}
@Override
public Node createNode(Address address) {
if (!(address instanceof JGroupsAddress)) {
throw new IllegalArgumentException(address.toString());
}
return this.nodeFactory.createNode(((JGroupsAddress) address).getJGroupsAddress());
}
@Merged
@ViewChanged
public CompletionStage<Void> viewChanged(ViewChangedEvent event) {
if (this.cache.getAdvancedCache().getDistributionManager() != null) {
// Record view status for use by @TopologyChanged event
return this.blocking.runBlocking(() -> this.views.put(event.getViewId(), event.isMergeView()), event.getViewId());
}
Membership previousMembership = new CacheMembership(event.getLocalAddress(), event.getOldMembers(), this);
Membership membership = new CacheMembership(event.getLocalAddress(), event.getNewMembers(), this);
if (!this.listeners.isEmpty()) {
this.executor.execute(new GroupListenerNotificationTask(this.listeners.entrySet(), previousMembership, membership, event.isMergeView()));
}
return CompletableFuture.completedStage(null);
}
@TopologyChanged
public CompletionStage<Void> topologyChanged(TopologyChangedEvent<?, ?> event) {
int viewId = event.getCache().getAdvancedCache().getRpcManager().getTransport().getViewId();
Address localAddress = event.getCache().getCacheManager().getAddress();
Membership previousMembership = new CacheMembership(localAddress, event.getWriteConsistentHashAtStart(), this);
Membership membership = new CacheMembership(localAddress, event.getWriteConsistentHashAtEnd(), this);
this.executor.execute(() -> {
Boolean status = this.views.get(viewId);
boolean merged = (status != null) ? status : false;
new GroupListenerNotificationTask(this.listeners.entrySet(), previousMembership, membership, merged).run();
// Purge obsolete views
this.views.headMap(viewId).clear();
});
return CompletableFuture.completedStage(null);
}
@Override
public Registration register(GroupListener listener) {
this.listeners.computeIfAbsent(listener, this);
return () -> this.unregister(listener);
}
@Override
public ExecutorService apply(GroupListener listener) {
return new DefaultExecutorService(listener.getClass(), ExecutorServiceFactory.SINGLE_THREAD);
}
private void unregister(GroupListener listener) {
ExecutorService executor = this.listeners.remove(listener);
if (executor != null) {
this.shutdown(executor);
}
}
}
| 8,211
| 43.150538
| 149
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/CommandMarshaller.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.server.infinispan.dispatcher;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.wildfly.clustering.dispatcher.Command;
/**
* Marshalling strategy for a command.
* @author Paul Ferraro
*
* @param <C> command execution context
*/
public interface CommandMarshaller<C> {
/**
* Marshals the specified command to a byte[].
* @param command a command
* @return a serialized command.
* @throws IOException if marshalling fails.
*/
<R> ByteBuffer marshal(Command<R, ? super C> command) throws IOException;
}
| 1,612
| 35.659091
| 77
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/ViewMembership.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.server.infinispan.dispatcher;
import java.util.ArrayList;
import java.util.List;
import org.jgroups.Address;
import org.jgroups.View;
import org.wildfly.clustering.group.Membership;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.server.NodeFactory;
/**
* A group membership based on a JGroups view.
* @author Paul Ferraro
*/
public class ViewMembership implements Membership {
private final Address localAddress;
private final View view;
private final NodeFactory<Address> factory;
public ViewMembership(Address localAddress, View view, NodeFactory<Address> factory) {
this.localAddress = localAddress;
this.view = view;
this.factory = factory;
}
@Override
public boolean isCoordinator() {
return this.localAddress.equals(this.view.getCoord());
}
@Override
public Node getCoordinator() {
return this.factory.createNode(this.view.getCoord());
}
@Override
public List<Node> getMembers() {
List<Node> members = new ArrayList<>(this.view.size());
for (Address address : this.view.getMembersRaw()) {
Node member = this.factory.createNode(address);
if (member != null) {
members.add(member);
}
}
return members;
}
@Override
public int hashCode() {
return this.view.hashCode();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof ViewMembership)) return false;
ViewMembership membership = (ViewMembership) object;
return this.view.equals(membership.view);
}
@Override
public String toString() {
return this.view.toString();
}
}
| 2,794
| 30.404494
| 90
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/AutoCloseableCommandDispatcherFactory.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.server.infinispan.dispatcher;
import org.wildfly.clustering.server.dispatcher.CommandDispatcherFactory;
/**
* A command dispatcher factory with a specific lifecycle (i.e. that must be closed).
* @author Paul Ferraro
*/
public interface AutoCloseableCommandDispatcherFactory extends CommandDispatcherFactory, AutoCloseable {
@Override
void close();
}
| 1,418
| 39.542857
| 104
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/ChannelCommandDispatcherFactory.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.server.infinispan.dispatcher;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.JChannel;
import org.jgroups.MergeView;
import org.jgroups.Message;
import org.jgroups.Receiver;
import org.jgroups.View;
import org.jgroups.blocks.MessageDispatcher;
import org.jgroups.blocks.RequestCorrelator;
import org.jgroups.blocks.RequestHandler;
import org.jgroups.blocks.Response;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.NameCache;
import org.wildfly.clustering.Registration;
import org.wildfly.clustering.context.Contextualizer;
import org.wildfly.clustering.context.DefaultContextualizerFactory;
import org.wildfly.clustering.context.DefaultExecutorService;
import org.wildfly.clustering.context.DefaultThreadFactory;
import org.wildfly.clustering.context.ExecutorServiceFactory;
import org.wildfly.clustering.dispatcher.Command;
import org.wildfly.clustering.dispatcher.CommandDispatcher;
import org.wildfly.clustering.ee.cache.concurrent.StampedLockServiceExecutor;
import org.wildfly.clustering.ee.concurrent.ServiceExecutor;
import org.wildfly.clustering.group.Group;
import org.wildfly.clustering.group.GroupListener;
import org.wildfly.clustering.group.Membership;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.marshalling.spi.ByteBufferMarshalledValueFactory;
import org.wildfly.clustering.marshalling.spi.ByteBufferMarshaller;
import org.wildfly.clustering.marshalling.spi.MarshalledValue;
import org.wildfly.clustering.marshalling.spi.MarshalledValueFactory;
import org.wildfly.clustering.server.infinispan.ClusteringServerLogger;
import org.wildfly.clustering.server.infinispan.group.AddressableNode;
import org.wildfly.clustering.server.infinispan.group.GroupListenerNotificationTask;
import org.wildfly.common.function.ExceptionSupplier;
import org.wildfly.common.function.Functions;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* {@link MessageDispatcher} based {@link CommandDispatcherFactory}.
* This factory can produce multiple {@link CommandDispatcher} instances,
* all of which will share the same {@link MessageDispatcher} instance.
* @author Paul Ferraro
*/
public class ChannelCommandDispatcherFactory implements AutoCloseableCommandDispatcherFactory, RequestHandler, org.wildfly.clustering.server.group.Group<Address>, Receiver, Runnable, Function<GroupListener, ExecutorService> {
static final Optional<Object> NO_SUCH_SERVICE = Optional.of(NoSuchService.INSTANCE);
static final ExceptionSupplier<Object, Exception> NO_SUCH_SERVICE_SUPPLIER = Functions.constantExceptionSupplier(NoSuchService.INSTANCE);
private final ConcurrentMap<Address, Node> members = new ConcurrentHashMap<>();
private final Map<Object, CommandDispatcherContext<?, ?>> contexts = new ConcurrentHashMap<>();
private final ExecutorService executorService = Executors.newCachedThreadPool(new DefaultThreadFactory(this.getClass()));
private final ServiceExecutor executor = new StampedLockServiceExecutor();
private final Map<GroupListener, ExecutorService> listeners = new ConcurrentHashMap<>();
private final AtomicReference<View> view = new AtomicReference<>();
private final ByteBufferMarshaller marshaller;
private final MessageDispatcher dispatcher;
private final Duration timeout;
private final Function<ClassLoader, ByteBufferMarshaller> marshallerFactory;
@SuppressWarnings("resource")
public ChannelCommandDispatcherFactory(ChannelCommandDispatcherFactoryConfiguration config) {
this.marshaller = config.getMarshaller();
this.timeout = config.getTimeout();
this.marshallerFactory = config.getMarshallerFactory();
JChannel channel = config.getChannel();
RequestCorrelator correlator = new CommandDispatcherRequestCorrelator(channel, this, config);
this.dispatcher = new MessageDispatcher()
.setChannel(channel)
.setRequestHandler(this)
.setReceiver(this)
.asyncDispatching(true)
// Setting the request correlator starts the dispatcher
.correlator(correlator)
;
this.view.compareAndSet(null, channel.getView());
}
@Override
public void run() {
this.shutdown(this.executorService);
this.dispatcher.stop();
this.dispatcher.getChannel().setUpHandler(null);
// Cleanup any stray listeners
for (ExecutorService executor : this.listeners.values()) {
this.shutdown(executor);
}
this.listeners.clear();
}
@Override
public void close() {
this.executor.close(this);
}
private void shutdown(ExecutorService executor) {
WildFlySecurityManager.doUnchecked(executor, DefaultExecutorService.SHUTDOWN_NOW_ACTION);
try {
executor.awaitTermination(this.timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public Object handle(Message request) throws Exception {
return this.read(request).get();
}
@Override
public void handle(Message request, Response response) throws Exception {
ExceptionSupplier<Object, Exception> commandTask = this.read(request);
Runnable responseTask = new Runnable() {
@Override
public void run() {
try {
response.send(commandTask.get(), false);
} catch (Throwable e) {
response.send(e, true);
}
}
};
try {
this.executorService.submit(responseTask);
} catch (RejectedExecutionException e) {
response.send(NoSuchService.INSTANCE, false);
}
}
private ExceptionSupplier<Object, Exception> read(Message message) throws IOException {
ByteBuffer buffer = ByteBuffer.wrap(message.getArray(), message.getOffset(), message.getLength());
@SuppressWarnings("unchecked")
Map.Entry<Object, MarshalledValue<Command<Object, Object>, Object>> entry = (Map.Entry<Object, MarshalledValue<Command<Object, Object>, Object>>) this.marshaller.read(buffer);
Object clientId = entry.getKey();
CommandDispatcherContext<?, ?> context = this.contexts.get(clientId);
if (context == null) return NO_SUCH_SERVICE_SUPPLIER;
Object commandContext = context.getCommandContext();
Contextualizer contextualizer = context.getContextualizer();
MarshalledValue<Command<Object, Object>, Object> value = entry.getValue();
Command<Object, Object> command = value.get(context.getMarshalledValueFactory().getMarshallingContext());
ExceptionSupplier<Object, Exception> commandExecutionTask = new ExceptionSupplier<>() {
@Override
public Object get() throws Exception {
return context.getMarshalledValueFactory().createMarshalledValue(command.execute(commandContext));
}
};
ServiceExecutor executor = this.executor;
return new ExceptionSupplier<>() {
@Override
public Object get() throws Exception {
return executor.execute(contextualizer.contextualize(commandExecutionTask)).orElse(NO_SUCH_SERVICE);
}
};
}
@Override
public Group getGroup() {
return this;
}
@Override
public <C> CommandDispatcher<C> createCommandDispatcher(Object id, C commandContext, ClassLoader loader) {
ByteBufferMarshaller dispatcherMarshaller = this.marshallerFactory.apply(loader);
MarshalledValueFactory<ByteBufferMarshaller> factory = new ByteBufferMarshalledValueFactory(dispatcherMarshaller);
Contextualizer contextualizer = DefaultContextualizerFactory.INSTANCE.createContextualizer(loader);
CommandDispatcherContext<C, ByteBufferMarshaller> context = new CommandDispatcherContext<>() {
@Override
public C getCommandContext() {
return commandContext;
}
@Override
public Contextualizer getContextualizer() {
return contextualizer;
}
@Override
public MarshalledValueFactory<ByteBufferMarshaller> getMarshalledValueFactory() {
return factory;
}
};
if (this.contexts.putIfAbsent(id, context) != null) {
throw ClusteringServerLogger.ROOT_LOGGER.commandDispatcherAlreadyExists(id);
}
CommandMarshaller<C> marshaller = new CommandDispatcherMarshaller<>(this.marshaller, id, factory);
CommandDispatcher<C> localDispatcher = new LocalCommandDispatcher<>(this.getLocalMember(), commandContext);
return new ChannelCommandDispatcher<>(this.dispatcher, marshaller, dispatcherMarshaller, this, this.timeout, localDispatcher, () -> {
localDispatcher.close();
this.contexts.remove(id);
});
}
@Override
public Registration register(GroupListener listener) {
this.listeners.computeIfAbsent(listener, this);
return () -> this.unregister(listener);
}
@Override
public ExecutorService apply(GroupListener listener) {
return new DefaultExecutorService(listener.getClass(), ExecutorServiceFactory.SINGLE_THREAD);
}
private void unregister(GroupListener listener) {
ExecutorService executor = this.listeners.remove(listener);
if (executor != null) {
this.shutdown(executor);
}
}
@Override
public String getName() {
return this.dispatcher.getChannel().getClusterName();
}
@Override
public Membership getMembership() {
return new ViewMembership(this.dispatcher.getChannel().getAddress(), this.view.get(), this);
}
@Override
public Node getLocalMember() {
return this.createNode(this.dispatcher.getChannel().getAddress());
}
@Override
public boolean isSingleton() {
return false;
}
@Override
public Node createNode(Address address) {
return this.members.computeIfAbsent(address, key -> {
IpAddress ipAddress = (IpAddress) this.dispatcher.getChannel().down(new Event(Event.GET_PHYSICAL_ADDRESS, address));
// Physical address might be null if node is no longer a member of the cluster
if (ipAddress == null) return null;
InetSocketAddress socketAddress = new InetSocketAddress(ipAddress.getIpAddress(), ipAddress.getPort());
String name = NameCache.get(address);
if (name == null) {
// If no logical name exists, create one using physical address
name = String.format("%s:%s", socketAddress.getHostString(), socketAddress.getPort());
}
return new AddressableNode(address, name, socketAddress);
});
}
@Override
public void viewAccepted(View view) {
View oldView = this.view.getAndSet(view);
if (oldView != null) {
List<Address> leftMembers = View.leftMembers(oldView, view);
if (leftMembers != null) {
this.members.keySet().removeAll(leftMembers);
}
if (!this.listeners.isEmpty()) {
Address localAddress = this.dispatcher.getChannel().getAddress();
ViewMembership oldMembership = new ViewMembership(localAddress, oldView, this);
ViewMembership membership = new ViewMembership(localAddress, view, this);
this.executorService.execute(new GroupListenerNotificationTask(this.listeners.entrySet(), oldMembership, membership, view instanceof MergeView));
}
}
}
}
| 13,426
| 43.167763
| 225
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/ChannelCommandDispatcher.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.server.infinispan.dispatcher;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import org.jgroups.Address;
import org.jgroups.BytesMessage;
import org.jgroups.Message;
import org.jgroups.blocks.MessageDispatcher;
import org.jgroups.blocks.RequestOptions;
import org.jgroups.blocks.ResponseMode;
import org.jgroups.blocks.RspFilter;
import org.wildfly.clustering.dispatcher.Command;
import org.wildfly.clustering.dispatcher.CommandDispatcher;
import org.wildfly.clustering.dispatcher.CommandDispatcherException;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.server.group.Group;
import org.wildfly.clustering.server.infinispan.group.JGroupsAddressResolver;
/**
* MessageDispatcher-based command dispatcher.
* @author Paul Ferraro
*
* @param <CC> command execution context
*/
public class ChannelCommandDispatcher<CC, MC> implements CommandDispatcher<CC> {
private static final RspFilter FILTER = new RspFilter() {
@Override
public boolean isAcceptable(Object response, Address sender) {
return !(response instanceof NoSuchService);
}
@Override
public boolean needMoreResponses() {
return true;
}
};
private final MessageDispatcher dispatcher;
private final CommandMarshaller<CC> marshaller;
private final MC context;
private final Group<Address> group;
private final Duration timeout;
private final CommandDispatcher<CC> localDispatcher;
private final Runnable closeTask;
private final Address localAddress;
private final RequestOptions options;
public ChannelCommandDispatcher(MessageDispatcher dispatcher, CommandMarshaller<CC> marshaller, MC context, Group<Address> group, Duration timeout, CommandDispatcher<CC> localDispatcher, Runnable closeTask) {
this.dispatcher = dispatcher;
this.marshaller = marshaller;
this.context = context;
this.group = group;
this.timeout = timeout;
this.localDispatcher = localDispatcher;
this.closeTask = closeTask;
this.localAddress = dispatcher.getChannel().getAddress();
this.options = new RequestOptions(ResponseMode.GET_ALL, this.timeout.toMillis(), false, FILTER, Message.Flag.DONT_BUNDLE, Message.Flag.OOB);
}
@Override
public CC getContext() {
return this.localDispatcher.getContext();
}
@Override
public void close() {
this.closeTask.run();
}
@Override
public <R> CompletionStage<R> executeOnMember(Command<R, ? super CC> command, Node member) throws CommandDispatcherException {
// Bypass MessageDispatcher if target node is local
Address address = JGroupsAddressResolver.INSTANCE.apply(member);
if (this.localAddress.equals(address)) {
return this.localDispatcher.executeOnMember(command, member);
}
ByteBuffer buffer = this.createBuffer(command);
Message message = this.createMessage(buffer, address);
ServiceRequest<R, MC> request = new ServiceRequest<>(this.dispatcher.getCorrelator(), address, this.options, this.context);
return request.send(message);
}
@Override
public <R> Map<Node, CompletionStage<R>> executeOnGroup(Command<R, ? super CC> command, Node... excludedMembers) throws CommandDispatcherException {
Set<Node> excluded = (excludedMembers != null) ? new HashSet<>(Arrays.asList(excludedMembers)) : Collections.emptySet();
Map<Node, CompletionStage<R>> results = new ConcurrentHashMap<>();
ByteBuffer buffer = this.createBuffer(command);
for (Node member : this.group.getMembership().getMembers()) {
if (!excluded.contains(member)) {
Address address = JGroupsAddressResolver.INSTANCE.apply(member);
if (this.localAddress.equals(address)) {
results.put(member, this.localDispatcher.executeOnMember(command, member));
} else {
try {
ServiceRequest<R, MC> request = new ServiceRequest<>(this.dispatcher.getCorrelator(), address, this.options, this.context);
Message message = this.createMessage(buffer, address);
CompletionStage<R> future = request.send(message);
results.put(member, future);
future.whenComplete(new PruneCancellationTask<>(results, member));
} catch (CommandDispatcherException e) {
// Cancel previously dispatched messages
for (CompletionStage<R> result : results.values()) {
result.toCompletableFuture().cancel(true);
}
throw e;
}
}
}
}
return results;
}
private <R> ByteBuffer createBuffer(Command<R, ? super CC> command) {
try {
return this.marshaller.marshal(command);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
private Message createMessage(ByteBuffer buffer, Address destination) {
return new BytesMessage().setArray(buffer.array(), buffer.arrayOffset(), buffer.limit() - buffer.arrayOffset()).src(this.localAddress).dest(destination);
}
private static class PruneCancellationTask<T> implements BiConsumer<T, Throwable> {
private final Map<Node, CompletionStage<T>> results;
private final Node member;
PruneCancellationTask(Map<Node, CompletionStage<T>> results, Node member) {
this.results = results;
this.member = member;
}
@Override
public void accept(T result, Throwable exception) {
if (exception instanceof CancellationException) {
this.results.remove(this.member);
}
}
}
}
| 7,325
| 40.862857
| 212
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/ServiceRequest.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.server.infinispan.dispatcher;
import java.io.IOException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jgroups.Address;
import org.jgroups.Message;
import org.jgroups.SuspectedException;
import org.jgroups.blocks.RequestCorrelator;
import org.jgroups.blocks.RequestOptions;
import org.jgroups.blocks.UnicastRequest;
import org.wildfly.clustering.dispatcher.CommandDispatcherException;
import org.wildfly.clustering.marshalling.spi.MarshalledValue;
/**
* Translates a {@link NoSuchService} response to a {@link CancellationException}.
* @author Paul Ferraro
*/
public class ServiceRequest<T, C> extends UnicastRequest<T> {
private final C context;
public ServiceRequest(RequestCorrelator correlator, Address target, RequestOptions options, C context) {
super(correlator, target, options);
this.context = context;
}
public CompletionStage<T> send(Message message) throws CommandDispatcherException {
try {
this.sendRequest(message);
return this;
} catch (Exception e) {
throw new CommandDispatcherException(e);
}
}
@SuppressWarnings("unchecked")
@Override
public void receiveResponse(Object value, Address sender, boolean exceptional) {
if (this.isDone()) return;
if (exceptional) {
this.completeExceptionally((Throwable) value);
} else if (value instanceof NoSuchService) {
this.completeExceptionally(new CancellationException());
} else {
MarshalledValue<T, C> marshalledValue = (MarshalledValue<T, C>) value;
try {
this.complete(marshalledValue.get(this.context));
} catch (IOException e) {
this.completeExceptionally(e);
}
}
this.corrDone();
}
@Override
public boolean completeExceptionally(Throwable exception) {
return super.completeExceptionally((exception instanceof SuspectedException) ? new CancellationException() : exception);
}
@Override
public T get() throws InterruptedException, ExecutionException {
try {
// Wait at most for the configured timeout
// If the message was dropped by the receiver, this would otherwise block forever
return super.get(super.options.timeout(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
// Auto-cancel on timeout
this.cancel(true);
throw new CancellationException(e.getLocalizedMessage());
}
}
@Override
public T join() {
try {
return this.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CompletionException(e);
} catch (ExecutionException e) {
throw new CompletionException(e.getCause());
}
}
}
| 4,187
| 35.736842
| 128
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/NoSuchService.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.server.infinispan.dispatcher;
/**
* Simple object that indicates that no service is registered on the remote node for which to execute the remote command.
* @author Paul Ferraro
*/
public enum NoSuchService {
INSTANCE;
}
| 1,282
| 41.766667
| 121
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/LocalCommandDispatcher.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.server.infinispan.dispatcher;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.wildfly.clustering.dispatcher.Command;
import org.wildfly.clustering.dispatcher.CommandDispatcher;
import org.wildfly.clustering.dispatcher.CommandDispatcherException;
import org.wildfly.clustering.group.Node;
/**
* Non-clustered {@link CommandDispatcher} implementation
* @author Paul Ferraro
* @param <C> command context
*/
public class LocalCommandDispatcher<C> implements CommandDispatcher<C> {
private final C context;
private final Node node;
public LocalCommandDispatcher(Node node, C context) {
this.node = node;
this.context = context;
}
@Override
public C getContext() {
return this.context;
}
@Override
public <R> CompletionStage<R> executeOnMember(Command<R, ? super C> command, Node member) throws CommandDispatcherException {
if (!this.node.equals(member)) {
throw new IllegalArgumentException(member.getName());
}
try {
R result = command.execute(this.context);
return CompletableFuture.completedFuture(result);
} catch (Exception e) {
CompletableFuture<R> future = new CompletableFuture<>();
future.completeExceptionally(e);
return future;
}
}
@Override
public <R> Map<Node, CompletionStage<R>> executeOnGroup(Command<R, ? super C> command, Node... excludedMembers) throws CommandDispatcherException {
if ((excludedMembers != null) && Arrays.asList(excludedMembers).contains(this.node)) return Collections.emptyMap();
return Collections.singletonMap(this.node, this.executeOnMember(command, this.node));
}
@Override
public void close() {
// Do nothing
}
}
| 2,973
| 35.716049
| 151
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/CommandDispatcherContext.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.server.infinispan.dispatcher;
import org.wildfly.clustering.context.Contextualizer;
import org.wildfly.clustering.marshalling.spi.MarshalledValueFactory;
/**
* @author Paul Ferraro
*/
public interface CommandDispatcherContext<CC, MC> {
CC getCommandContext();
Contextualizer getContextualizer();
MarshalledValueFactory<MC> getMarshalledValueFactory();
}
| 1,425
| 38.611111
| 70
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/CommandDispatcherSerializationContextInitializer.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.server.infinispan.dispatcher;
import org.infinispan.protostream.SerializationContext;
import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer;
import org.wildfly.clustering.marshalling.protostream.EnumMarshaller;
/**
* {@link org.infinispan.protostream.SerializationContextInitializer} for this package.
* @author Paul Ferraro
*/
public class CommandDispatcherSerializationContextInitializer extends AbstractSerializationContextInitializer {
@Override
public void registerMarshallers(SerializationContext context) {
context.registerMarshaller(new EnumMarshaller<>(NoSuchService.class));
}
}
| 1,710
| 41.775
| 111
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/CommandDispatcherClassTableContributor.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.server.infinispan.dispatcher;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.dispatcher.Command;
import org.wildfly.clustering.marshalling.jboss.ClassTableContributor;
/**
* ClassTable contributor for the marshaller of a {@link org.wildfly.clustering.dispatcher.CommandDispatcher}.
* @author Paul Ferraro
*/
@MetaInfServices(ClassTableContributor.class)
public class CommandDispatcherClassTableContributor implements ClassTableContributor {
@Override
public List<Class<?>> getKnownClasses() {
return Arrays.<Class<?>>asList(Command.class, NoSuchService.class, ExecutionException.class);
}
}
| 1,787
| 39.636364
| 110
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/CommandDispatcherRequestCorrelator.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.server.infinispan.dispatcher;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.function.Predicate;
import org.jgroups.BytesMessage;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.blocks.Request;
import org.jgroups.blocks.RequestCorrelator;
import org.jgroups.blocks.RequestHandler;
import org.jgroups.conf.ClassConfigurator;
import org.wildfly.clustering.marshalling.spi.ByteBufferMarshaller;
import org.wildfly.clustering.server.infinispan.ClusteringServerLogger;
/**
* @author Paul Ferraro
*/
public class CommandDispatcherRequestCorrelator extends RequestCorrelator {
private final ByteBufferMarshaller marshaller;
private final Predicate<Message> unknownForkPredicate;
public CommandDispatcherRequestCorrelator(JChannel channel, RequestHandler handler, ChannelCommandDispatcherFactoryConfiguration config) {
super(channel.getProtocolStack(), handler, channel.getAddress());
this.marshaller = config.getMarshaller();
this.unknownForkPredicate = config.getUnknownForkPredicate();
this.corr_id = ClassConfigurator.getProtocolId(RequestCorrelator.class);
}
@Override
protected void dispatch(Message message, Header header) {
boolean exception = false;
switch (header.type) {
case Header.REQ:
this.handleRequest(message, header);
break;
case Header.EXC_RSP:
exception = true;
// Fall through
case Header.RSP:
Request<?> request = this.requests.get(header.req_id);
if (request != null) {
try {
Object response = this.readPayload(message);
request.receiveResponse(response, message.getSrc(), exception);
} catch (IOException e) {
ClusteringServerLogger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e);
request.receiveResponse(e, message.getSrc(), true);
}
}
break;
default:
throw new IllegalArgumentException(header.toString());
}
}
private Object readPayload(Message message) throws IOException {
if (this.unknownForkPredicate.test(message)) {
return NoSuchService.INSTANCE;
}
if (message.isFlagSet(Message.Flag.SERIALIZED)) {
return message.getObject();
}
ByteBuffer buffer = ByteBuffer.wrap(message.getArray(), message.getOffset(), message.getLength());
return this.marshaller.read(buffer);
}
@Override
protected void sendReply(Message request, long requestId, Object reply, boolean exception) {
Message response = new BytesMessage(request.getSrc()).setFlag(request.getFlags(false), false).clearFlag(Message.Flag.RSVP);
if (request.getDest() != null) {
response.setSrc(request.getDest());
}
try {
ByteBuffer buffer = this.marshaller.write(reply);
response.setArray(buffer.array(), buffer.arrayOffset(), buffer.limit() - buffer.arrayOffset());
} catch (IOException e) {
ClusteringServerLogger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e);
response.setObject(e);
}
this.sendResponse(response, requestId, exception);
}
}
| 4,473
| 40.425926
| 142
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/ChannelCommandDispatcherFactoryConfiguration.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.server.infinispan.dispatcher;
import java.time.Duration;
import java.util.function.Function;
import java.util.function.Predicate;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.wildfly.clustering.marshalling.spi.ByteBufferMarshaller;
/**
* Configuration for a {@link ChannelCommandDispatcherFactory}.
* @author Paul Ferraro
*/
public interface ChannelCommandDispatcherFactoryConfiguration {
Predicate<Message> getUnknownForkPredicate();
JChannel getChannel();
ByteBufferMarshaller getMarshaller();
Duration getTimeout();
Function<ClassLoader, ByteBufferMarshaller> getMarshallerFactory();
}
| 1,692
| 38.372093
| 71
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/LocalCommandDispatcherFactory.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.server.infinispan.dispatcher;
import org.wildfly.clustering.dispatcher.CommandDispatcher;
import org.wildfly.clustering.group.Group;
import org.wildfly.clustering.server.dispatcher.CommandDispatcherFactory;
/**
* Non-clustered {@link CommandDispatcherFactory} implementation
* @author Paul Ferraro
*/
public class LocalCommandDispatcherFactory implements CommandDispatcherFactory {
private final Group group;
public LocalCommandDispatcherFactory(Group group) {
this.group = group;
}
@Override
public Group getGroup() {
return this.group;
}
@Override
public <C> CommandDispatcher<C> createCommandDispatcher(Object id, C context, ClassLoader loader) {
return new LocalCommandDispatcher<>(this.group.getLocalMember(), context);
}
}
| 1,852
| 36.06
| 103
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/dispatcher/CommandDispatcherMarshaller.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.server.infinispan.dispatcher;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.AbstractMap;
import java.util.Map;
import org.wildfly.clustering.dispatcher.Command;
import org.wildfly.clustering.marshalling.spi.MarshalledValue;
import org.wildfly.clustering.marshalling.spi.MarshalledValueFactory;
import org.wildfly.clustering.marshalling.spi.ByteBufferMarshaller;
/**
* @author Paul Ferraro
*/
public class CommandDispatcherMarshaller<C, MC> implements CommandMarshaller<C> {
private final ByteBufferMarshaller marshaller;
private final Object id;
private final MarshalledValueFactory<MC> factory;
public CommandDispatcherMarshaller(ByteBufferMarshaller marshaller, Object id, MarshalledValueFactory<MC> factory) {
this.marshaller = marshaller;
this.id = id;
this.factory = factory;
}
@Override
public <R> ByteBuffer marshal(Command<R, ? super C> command) throws IOException {
MarshalledValue<Command<R, ? super C>, MC> value = this.factory.createMarshalledValue(command);
Map.Entry<Object, MarshalledValue<Command<R, ? super C>, MC>> entry = new AbstractMap.SimpleImmutableEntry<>(this.id, value);
return this.marshaller.write(entry);
}
}
| 2,308
| 39.508772
| 133
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/registry/CacheRegistryConfiguration.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.server.infinispan.registry;
import org.wildfly.clustering.ee.infinispan.InfinispanConfiguration;
import org.wildfly.clustering.group.Group;
/**
* Configuration for a {@link CacheRegistryFactory}.
* @author Paul Ferraro
*/
public interface CacheRegistryConfiguration<K, V> extends InfinispanConfiguration {
Group getGroup();
}
| 1,389
| 39.882353
| 83
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/registry/LocalRegistry.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.server.infinispan.registry;
import java.util.Collections;
import java.util.Map;
import org.wildfly.clustering.Registration;
import org.wildfly.clustering.group.Group;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.registry.Registry;
import org.wildfly.clustering.registry.RegistryListener;
/**
* Non-clustered {@link Registry} implementation.
* @author Paul Ferraro
* @param <K> key type
* @param <V> value type
*/
public class LocalRegistry<K, V> implements Registry<K, V> {
private final Group group;
private final Runnable closeTask;
private volatile Map.Entry<K, V> entry;
public LocalRegistry(Group group, Map.Entry<K, V> entry, Runnable closeTask) {
this.group = group;
this.closeTask = closeTask;
this.entry = entry;
}
@Override
public Group getGroup() {
return this.group;
}
@Override
public Registration register(RegistryListener<K, V> object) {
// if there are no remote nodes, any registered listener would never get triggered
return () -> {};
}
@Override
public Map<K, V> getEntries() {
Map.Entry<K, V> entry = this.entry;
return (entry != null) ? Collections.singletonMap(entry.getKey(), entry.getValue()) : Collections.emptyMap();
}
@Override
public Map.Entry<K, V> getEntry(Node node) {
return this.entry;
}
@Override
public void close() {
this.entry = null;
this.closeTask.run();
}
}
| 2,562
| 31.443038
| 117
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/registry/CacheRegistry.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.server.infinispan.registry;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.context.Flag;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.Listener.Observation;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.annotation.TopologyChanged;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent;
import org.infinispan.notifications.cachelistener.event.Event;
import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.Registration;
import org.wildfly.clustering.context.DefaultExecutorService;
import org.wildfly.clustering.context.ExecutorServiceFactory;
import org.wildfly.clustering.ee.Batch;
import org.wildfly.clustering.ee.Batcher;
import org.wildfly.clustering.ee.Invoker;
import org.wildfly.clustering.ee.infinispan.retry.RetryingInvoker;
import org.wildfly.clustering.group.Group;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.infinispan.distribution.ConsistentHashLocality;
import org.wildfly.clustering.infinispan.distribution.Locality;
import org.wildfly.clustering.infinispan.listener.KeyFilter;
import org.wildfly.clustering.registry.Registry;
import org.wildfly.clustering.registry.RegistryListener;
import org.wildfly.clustering.server.infinispan.ClusteringServerLogger;
import org.wildfly.clustering.server.infinispan.group.InfinispanAddressResolver;
import org.wildfly.common.function.ExceptionRunnable;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Clustered {@link Registry} backed by an Infinispan cache.
* @author Paul Ferraro
* @param <K> key type
* @param <V> value type
*/
@Listener(observation = Observation.POST)
public class CacheRegistry<K, V> implements Registry<K, V>, ExceptionRunnable<CacheException>, Function<RegistryListener<K, V>, ExecutorService> {
private final Map<RegistryListener<K, V>, ExecutorService> listeners = new ConcurrentHashMap<>();
private final Cache<Address, Map.Entry<K, V>> cache;
private final Batcher<? extends Batch> batcher;
private final Group group;
private final Runnable closeTask;
private final Map.Entry<K, V> entry;
private final Invoker invoker;
private final KeyPartitioner partitioner;
private final Executor executor;
@SuppressWarnings("deprecation")
public CacheRegistry(CacheRegistryConfiguration<K, V> config, Map.Entry<K, V> entry, Runnable closeTask) {
this.cache = config.getCache();
this.batcher = config.getBatcher();
this.group = config.getGroup();
this.closeTask = closeTask;
this.executor = config.getBlockingManager().asExecutor(this.getClass().getName());
this.partitioner = this.cache.getAdvancedCache().getComponentRegistry().getLocalComponent(KeyPartitioner.class);
this.entry = new AbstractMap.SimpleImmutableEntry<>(entry);
this.invoker = new RetryingInvoker(this.cache);
this.invoker.invoke(this);
this.cache.addListener(this, new KeyFilter<>(Address.class), null);
}
@Override
public void run() {
try (Batch batch = this.batcher.createBatch()) {
this.cache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).put(InfinispanAddressResolver.INSTANCE.apply(this.group.getLocalMember()), this.entry);
}
}
@Override
public void close() {
this.cache.removeListener(this);
try (Batch batch = this.batcher.createBatch()) {
// If this remove fails, the entry will be auto-removed on topology change by the new primary owner
this.cache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES, Flag.FAIL_SILENTLY).remove(InfinispanAddressResolver.INSTANCE.apply(this.group.getLocalMember()));
} catch (CacheException e) {
ClusteringServerLogger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e);
} finally {
// Cleanup any unregistered listeners
for (ExecutorService executor : this.listeners.values()) {
this.shutdown(executor);
}
this.listeners.clear();
this.closeTask.run();
}
}
@Override
public Registration register(RegistryListener<K, V> listener) {
this.listeners.computeIfAbsent(listener, this);
return () -> this.unregister(listener);
}
@Override
public ExecutorService apply(RegistryListener<K, V> listener) {
return new DefaultExecutorService(listener.getClass(), ExecutorServiceFactory.SINGLE_THREAD);
}
private void unregister(RegistryListener<K, V> listener) {
ExecutorService executor = this.listeners.remove(listener);
if (executor != null) {
this.shutdown(executor);
}
}
@Override
public Group getGroup() {
return this.group;
}
@Override
public Map<K, V> getEntries() {
Set<Address> addresses = new TreeSet<>();
for (Node member : this.group.getMembership().getMembers()) {
addresses.add(InfinispanAddressResolver.INSTANCE.apply(member));
}
Map<K, V> result = new HashMap<>();
for (Map.Entry<K, V> entry : this.cache.getAdvancedCache().getAll(addresses).values()) {
if (entry != null) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
@Override
public Map.Entry<K, V> getEntry(Node node) {
Address address = InfinispanAddressResolver.INSTANCE.apply(node);
return this.cache.get(address);
}
@TopologyChanged
public CompletionStage<Void> topologyChanged(TopologyChangedEvent<Address, Map.Entry<K, V>> event) {
ConsistentHash previousHash = event.getWriteConsistentHashAtStart();
List<Address> previousMembers = previousHash.getMembers();
ConsistentHash hash = event.getWriteConsistentHashAtEnd();
List<Address> members = hash.getMembers();
if (!members.equals(previousMembers)) {
Cache<Address, Map.Entry<K, V>> cache = event.getCache().getAdvancedCache().withFlags(Flag.FORCE_SYNCHRONOUS);
EmbeddedCacheManager container = cache.getCacheManager();
Address localAddress = container.getAddress();
// Determine which nodes have left the cache view
Set<Address> leftMembers = new HashSet<>(previousMembers);
leftMembers.removeAll(members);
if (!leftMembers.isEmpty()) {
Locality locality = new ConsistentHashLocality(this.partitioner, hash, localAddress);
// We're only interested in the entries for which we are the primary owner
Iterator<Address> addresses = leftMembers.iterator();
while (addresses.hasNext()) {
if (!locality.isLocal(addresses.next())) {
addresses.remove();
}
}
}
// If this is a merge after cluster split: re-populate the cache registry with lost registry entries
boolean restoreLocalEntry = !previousMembers.contains(localAddress);
if (!leftMembers.isEmpty() || restoreLocalEntry) {
this.executor.execute(() -> {
if (!leftMembers.isEmpty()) {
Map<K, V> removed = new HashMap<>();
try {
for (Address leftMember: leftMembers) {
Map.Entry<K, V> old = cache.remove(leftMember);
if (old != null) {
removed.put(old.getKey(), old.getValue());
}
}
} catch (CacheException e) {
ClusteringServerLogger.ROOT_LOGGER.registryPurgeFailed(e, container.toString(), cache.getName(), leftMembers);
}
if (!removed.isEmpty()) {
this.notifyListeners(Event.Type.CACHE_ENTRY_REMOVED, removed);
}
}
if (restoreLocalEntry) {
// If this node is not a member at merge start, its mapping may have been lost and need to be recreated
try {
if (cache.put(localAddress, this.entry) == null) {
// Local cache events do not trigger notifications
this.notifyListeners(Event.Type.CACHE_ENTRY_CREATED, this.entry);
}
} catch (CacheException e) {
ClusteringServerLogger.ROOT_LOGGER.failedToRestoreLocalRegistryEntry(e, container.toString(), cache.getName());
}
}
});
}
}
return CompletableFuture.completedStage(null);
}
@CacheEntryCreated
@CacheEntryModified
public CompletionStage<Void> event(CacheEntryEvent<Address, Map.Entry<K, V>> event) {
if (!event.isOriginLocal()) {
Map.Entry<K, V> entry = event.getValue();
if (entry != null) {
this.executor.execute(() -> this.notifyListeners(event.getType(), entry));
}
}
return CompletableFuture.completedStage(null);
}
@CacheEntryRemoved
public CompletionStage<Void> removed(CacheEntryRemovedEvent<Address, Map.Entry<K, V>> event) {
if (!event.isOriginLocal()) {
Map.Entry<K, V> entry = event.getOldValue();
// WFLY-4938 For some reason, the old value can be null
if (entry != null) {
this.executor.execute(() -> this.notifyListeners(event.getType(), entry));
}
}
return CompletableFuture.completedStage(null);
}
private void notifyListeners(Event.Type type, Map.Entry<K, V> entry) {
this.notifyListeners(type, Collections.singletonMap(entry.getKey(), entry.getValue()));
}
private void notifyListeners(Event.Type type, Map<K, V> entries) {
for (Map.Entry<RegistryListener<K, V>, ExecutorService> entry: this.listeners.entrySet()) {
RegistryListener<K, V> listener = entry.getKey();
ExecutorService executor = entry.getValue();
try {
executor.submit(() -> {
try {
switch (type) {
case CACHE_ENTRY_CREATED: {
listener.addedEntries(entries);
break;
}
case CACHE_ENTRY_MODIFIED: {
listener.updatedEntries(entries);
break;
}
case CACHE_ENTRY_REMOVED: {
listener.removedEntries(entries);
break;
}
default: {
throw new IllegalStateException(type.name());
}
}
} catch (Throwable e) {
ClusteringServerLogger.ROOT_LOGGER.registryListenerFailed(e, this.cache.getCacheManager().getCacheManagerConfiguration().cacheManagerName(), this.cache.getName(), type, entries);
}
});
} catch (RejectedExecutionException e) {
// Executor was shutdown
}
}
}
private void shutdown(ExecutorService executor) {
WildFlySecurityManager.doUnchecked(executor, DefaultExecutorService.SHUTDOWN_ACTION);
try {
executor.awaitTermination(this.cache.getCacheConfiguration().transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
| 14,280
| 44.193038
| 202
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/registry/FunctionalRegistryFactory.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.server.infinispan.registry;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import org.wildfly.clustering.registry.Registry;
import org.wildfly.clustering.registry.RegistryFactory;
/**
* @author Paul Ferraro
*/
public class FunctionalRegistryFactory<K, V> implements RegistryFactory<K, V>, Runnable {
private final AtomicReference<Map.Entry<K, V>> entry = new AtomicReference<>();
private final BiFunction<Map.Entry<K, V>, Runnable, Registry<K, V>> factory;
public FunctionalRegistryFactory(BiFunction<Map.Entry<K, V>, Runnable, Registry<K, V>> factory) {
this.factory = factory;
}
@Override
public void run() {
this.entry.set(null);
}
@Override
public Registry<K, V> createRegistry(Map.Entry<K, V> entry) {
// Ensure only one registry is created at a time
if (!this.entry.compareAndSet(null, entry)) {
throw new IllegalStateException();
}
return this.factory.apply(entry, this);
}
}
| 2,112
| 35.431034
| 101
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/provider/CacheServiceProviderRegistryConfiguration.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.server.infinispan.provider;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.ee.infinispan.InfinispanConfiguration;
import org.wildfly.clustering.server.dispatcher.CommandDispatcherFactory;
import org.wildfly.clustering.server.group.Group;
/**
* Configuration for a {@link CacheServiceProviderRegistry}.
* @author Paul Ferraro
*/
public interface CacheServiceProviderRegistryConfiguration<T> extends InfinispanConfiguration {
Object getId();
Group<Address> getGroup();
CommandDispatcherFactory getCommandDispatcherFactory();
}
| 1,629
| 41.894737
| 95
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/provider/AutoCloseableServiceProviderRegistry.java
|
package org.wildfly.clustering.server.infinispan.provider;
import org.wildfly.clustering.provider.ServiceProviderRegistry;
import org.wildfly.clustering.server.group.Group;
/**
* A {@link Group} with a specific lifecycle (i.e. that must be closed).
* @author Paul Ferraro
* @param <T> the service type
*/
public interface AutoCloseableServiceProviderRegistry<T> extends ServiceProviderRegistry<T>, AutoCloseable {
@Override
void close();
}
| 454
| 29.333333
| 108
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/provider/ConcurrentAddressSetRemoveFunction.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.server.infinispan.provider;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.ee.cache.function.ConcurrentSetRemoveFunction;
/**
* Concurrent {@link java.util.Set#remove(Object)} function for an {@link Address}.
* @author Paul Ferraro
*/
public class ConcurrentAddressSetRemoveFunction extends ConcurrentSetRemoveFunction<Address> {
public ConcurrentAddressSetRemoveFunction(Address address) {
super(address);
}
}
| 1,521
| 39.052632
| 94
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/provider/CopyOnWriteAddressSetRemoveFunction.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.server.infinispan.provider;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.ee.cache.function.CopyOnWriteSetRemoveFunction;
/**
* Copy-on-write {@link java.util.Set#remove(Object)} function for an {@link Address}.
* @author Paul Ferraro
*/
public class CopyOnWriteAddressSetRemoveFunction extends CopyOnWriteSetRemoveFunction<Address> {
public CopyOnWriteAddressSetRemoveFunction(Address address) {
super(address);
}
}
| 1,528
| 39.236842
| 96
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/provider/CopyOnWriteAddressSetAddFunction.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.server.infinispan.provider;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.ee.cache.function.CopyOnWriteSetAddFunction;
/**
* Copy-on-write {@link java.util.Set#add(Object)} function for an {@link Address}.
* @author Paul Ferraro
*/
public class CopyOnWriteAddressSetAddFunction extends CopyOnWriteSetAddFunction<Address> {
public CopyOnWriteAddressSetAddFunction(Address address) {
super(address);
}
}
| 1,513
| 38.842105
| 90
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/provider/CacheServiceProviderRegistry.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.server.infinispan.provider;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.context.Flag;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.notifications.Listener.Observation;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.TopologyChanged;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.context.DefaultExecutorService;
import org.wildfly.clustering.context.ExecutorServiceFactory;
import org.wildfly.clustering.ee.Batch;
import org.wildfly.clustering.ee.Batcher;
import org.wildfly.clustering.ee.Invoker;
import org.wildfly.clustering.ee.cache.CacheProperties;
import org.wildfly.clustering.ee.infinispan.InfinispanCacheProperties;
import org.wildfly.clustering.ee.infinispan.retry.RetryingInvoker;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.infinispan.distribution.ConsistentHashLocality;
import org.wildfly.clustering.infinispan.distribution.Locality;
import org.wildfly.clustering.provider.ServiceProviderRegistration;
import org.wildfly.clustering.provider.ServiceProviderRegistration.Listener;
import org.wildfly.clustering.provider.ServiceProviderRegistry;
import org.wildfly.clustering.server.group.Group;
import org.wildfly.clustering.server.infinispan.ClusteringServerLogger;
import org.wildfly.clustering.server.infinispan.group.InfinispanAddressResolver;
import org.wildfly.common.function.ExceptionRunnable;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Infinispan {@link Cache} based {@link ServiceProviderRegistry}.
* This factory can create multiple {@link ServiceProviderRegistration} instance,
* all of which share the same {@link Cache} instance.
* @author Paul Ferraro
* @param <T> the service identifier type
*/
@org.infinispan.notifications.Listener(observation = Observation.POST)
public class CacheServiceProviderRegistry<T> implements AutoCloseableServiceProviderRegistry<T>, AutoCloseable {
private final Batcher<? extends Batch> batcher;
private final ConcurrentMap<T, Map.Entry<Listener, ExecutorService>> listeners = new ConcurrentHashMap<>();
private final Cache<T, Set<Address>> cache;
private final Group<Address> group;
private final Invoker invoker;
private final CacheProperties properties;
private final Executor executor;
public CacheServiceProviderRegistry(CacheServiceProviderRegistryConfiguration<T> config) {
this.group = config.getGroup();
this.cache = config.getCache();
this.batcher = config.getBatcher();
this.executor = config.getBlockingManager().asExecutor(this.getClass().getName());
this.cache.addListener(this);
this.invoker = new RetryingInvoker(this.cache);
this.properties = new InfinispanCacheProperties(this.cache.getCacheConfiguration());
}
@Override
public void close() {
this.cache.removeListener(this);
// Cleanup any unclosed registrations
for (Map.Entry<Listener, ExecutorService> entry : this.listeners.values()) {
ExecutorService executor = entry.getValue();
if (executor != null) {
this.shutdown(executor);
}
}
this.listeners.clear();
}
private void shutdown(ExecutorService executor) {
WildFlySecurityManager.doUnchecked(executor, DefaultExecutorService.SHUTDOWN_ACTION);
try {
executor.awaitTermination(this.cache.getCacheConfiguration().transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public org.wildfly.clustering.group.Group getGroup() {
return this.group;
}
@Override
public ServiceProviderRegistration<T> register(T service) {
return this.register(service, null);
}
@Override
public ServiceProviderRegistration<T> register(T service, Listener listener) {
Map.Entry<Listener, ExecutorService> newEntry = new AbstractMap.SimpleEntry<>(listener, null);
// Only create executor for new registrations
Map.Entry<Listener, ExecutorService> entry = this.listeners.computeIfAbsent(service, key -> {
if (listener != null) {
newEntry.setValue(new DefaultExecutorService(listener.getClass(), ExecutorServiceFactory.SINGLE_THREAD));
}
return newEntry;
});
if (entry != newEntry) {
throw new IllegalArgumentException(service.toString());
}
this.invoker.invoke(new RegisterLocalServiceTask(service));
return new SimpleServiceProviderRegistration<>(service, this, () -> {
Address localAddress = InfinispanAddressResolver.INSTANCE.apply(this.group.getLocalMember());
try (Batch batch = this.batcher.createBatch()) {
this.cache.getAdvancedCache().withFlags(Flag.FORCE_SYNCHRONOUS, Flag.IGNORE_RETURN_VALUES).compute(service, this.properties.isTransactional() ? new CopyOnWriteAddressSetRemoveFunction(localAddress) : new ConcurrentAddressSetRemoveFunction(localAddress));
} finally {
Map.Entry<Listener, ExecutorService> oldEntry = this.listeners.remove(service);
if (oldEntry != null) {
ExecutorService executor = oldEntry.getValue();
if (executor != null) {
this.shutdown(executor);
}
}
}
});
}
void registerLocal(T service) {
try (Batch batch = this.batcher.createBatch()) {
this.register(InfinispanAddressResolver.INSTANCE.apply(this.group.getLocalMember()), service);
}
}
void register(Address address, T service) {
this.cache.getAdvancedCache().withFlags(Flag.FORCE_SYNCHRONOUS, Flag.IGNORE_RETURN_VALUES).compute(service, this.properties.isTransactional() ? new CopyOnWriteAddressSetAddFunction(address) : new ConcurrentAddressSetAddFunction(address));
}
@Override
public Set<Node> getProviders(final T service) {
Set<Address> addresses = this.cache.get(service);
if (addresses == null) return Collections.emptySet();
Set<Node> members = new TreeSet<>();
for (Address address : addresses) {
Node member = this.group.createNode(address);
if (member != null) {
members.add(member);
}
}
return Collections.unmodifiableSet(members);
}
@Override
public Set<T> getServices() {
return this.cache.keySet();
}
@TopologyChanged
public CompletionStage<Void> topologyChanged(TopologyChangedEvent<T, Set<Address>> event) {
ConsistentHash previousHash = event.getWriteConsistentHashAtStart();
List<Address> previousMembers = previousHash.getMembers();
ConsistentHash hash = event.getWriteConsistentHashAtEnd();
List<Address> members = hash.getMembers();
if (!members.equals(previousMembers)) {
Cache<T, Set<Address>> cache = event.getCache().getAdvancedCache().withFlags(Flag.FORCE_SYNCHRONOUS);
Address localAddress = cache.getCacheManager().getAddress();
// Determine which nodes have left the cache view
Set<Address> leftMembers = new HashSet<>(previousMembers);
leftMembers.removeAll(members);
if (!leftMembers.isEmpty()) {
Locality locality = new ConsistentHashLocality(cache, hash);
// We're only interested in the entries for which we are the primary owner
Iterator<Address> addresses = leftMembers.iterator();
while (addresses.hasNext()) {
if (!locality.isLocal(addresses.next())) {
addresses.remove();
}
}
}
// If this is a merge after cluster split: Re-assert services for local member
Set<T> localServices = !previousMembers.contains(localAddress) ? this.listeners.keySet() : Collections.emptySet();
if (!leftMembers.isEmpty() || !localServices.isEmpty()) {
Batcher<? extends Batch> batcher = this.batcher;
Invoker invoker = this.invoker;
this.executor.execute(() -> {
if (!leftMembers.isEmpty()) {
try (Batch batch = batcher.createBatch()) {
try (CloseableIterator<Map.Entry<T, Set<Address>>> entries = cache.getAdvancedCache().withFlags(Flag.FORCE_WRITE_LOCK).entrySet().iterator()) {
while (entries.hasNext()) {
Map.Entry<T, Set<Address>> entry = entries.next();
Set<Address> addresses = entry.getValue();
if (addresses.removeAll(leftMembers)) {
entry.setValue(addresses);
}
}
}
}
}
if (!localServices.isEmpty()) {
for (T localService : localServices) {
invoker.invoke(new RegisterLocalServiceTask(localService));
}
}
});
}
}
return CompletableFuture.completedStage(null);
}
@CacheEntryCreated
@CacheEntryModified
public CompletionStage<Void> modified(CacheEntryEvent<T, Set<Address>> event) {
Map.Entry<Listener, ExecutorService> entry = this.listeners.get(event.getKey());
if (entry != null) {
Listener listener = entry.getKey();
if (listener != null) {
this.executor.execute(() -> {
try {
entry.getValue().submit(() -> {
Set<Node> members = new TreeSet<>();
for (Address address : event.getValue()) {
Node member = this.group.createNode(address);
if (member != null) {
members.add(member);
}
}
try {
listener.providersChanged(members);
} catch (Throwable e) {
ClusteringServerLogger.ROOT_LOGGER.serviceProviderRegistrationListenerFailed(e, this.cache.getCacheManager().getCacheManagerConfiguration().cacheManagerName(), this.cache.getName(), members);
}
});
} catch (RejectedExecutionException e) {
// Executor was shutdown
}
});
}
}
return CompletableFuture.completedStage(null);
}
private class RegisterLocalServiceTask implements ExceptionRunnable<CacheException> {
private final T localService;
RegisterLocalServiceTask(T localService) {
this.localService = localService;
}
@Override
public void run() {
CacheServiceProviderRegistry.this.registerLocal(this.localService);
}
}
}
| 13,462
| 44.792517
| 270
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/provider/SimpleServiceProviderRegistration.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.server.infinispan.provider;
import java.util.Set;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.provider.ServiceProviderRegistration;
import org.wildfly.clustering.provider.ServiceProviderRegistry;
/**
* Simple {@link ServiceProviderRegistration} implementation that delegates {@link #getProviders()} back to the factory.
* @author Paul Ferraro
*/
public class SimpleServiceProviderRegistration<T> implements ServiceProviderRegistration<T> {
private final T service;
private final ServiceProviderRegistry<T> registry;
private final Runnable closeTask;
public SimpleServiceProviderRegistration(T service, ServiceProviderRegistry<T> registry, Runnable closeTask) {
this.service = service;
this.registry = registry;
this.closeTask = closeTask;
}
@Override
public T getService() {
return this.service;
}
@Override
public Set<Node> getProviders() {
return this.registry.getProviders(this.service);
}
@Override
public void close() {
this.closeTask.run();
}
}
| 2,148
| 34.229508
| 120
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/provider/ConcurrentAddressSetAddFunction.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.server.infinispan.provider;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.ee.cache.function.ConcurrentSetAddFunction;
/**
* Concurrent {@link java.util.Set#add(Object)} function for an {@link Address}.
* @author Paul Ferraro
*/
public class ConcurrentAddressSetAddFunction extends ConcurrentSetAddFunction<Address> {
public ConcurrentAddressSetAddFunction(Address address) {
super(address);
}
}
| 1,506
| 38.657895
| 88
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/provider/LocalServiceProviderRegistry.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.server.infinispan.provider;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.wildfly.clustering.group.Group;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.provider.ServiceProviderRegistration;
import org.wildfly.clustering.provider.ServiceProviderRegistration.Listener;
/**
* Factory that provides a non-clustered {@link ServiceProviderRegistrationFactory} implementation.
* @author Paul Ferraro
*/
public class LocalServiceProviderRegistry<T> implements AutoCloseableServiceProviderRegistry<T> {
private final Set<T> services = ConcurrentHashMap.newKeySet();
private final Group group;
public LocalServiceProviderRegistry(Group group) {
this.group = group;
}
@Override
public Group getGroup() {
return this.group;
}
@Override
public ServiceProviderRegistration<T> register(T service) {
this.services.add(service);
return new SimpleServiceProviderRegistration<>(service, this, () -> this.services.remove(service));
}
@Override
public ServiceProviderRegistration<T> register(T service, Listener listener) {
return this.register(service);
}
@Override
public Set<Node> getProviders(T service) {
return this.services.contains(service) ? Collections.singleton(this.getGroup().getLocalMember()) : Collections.emptySet();
}
@Override
public Set<T> getServices() {
return Collections.unmodifiableSet(this.services);
}
@Override
public void close() {
// Do nothing
}
}
| 2,667
| 33.649351
| 130
|
java
|
null |
wildfly-main/clustering/server/infinispan/src/main/java/org/wildfly/clustering/server/infinispan/provider/ServiceProviderRegistrySerializationContextInitializer.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.server.infinispan.provider;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer;
import org.wildfly.clustering.marshalling.protostream.FunctionalMarshaller;
import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller;
import org.wildfly.clustering.marshalling.protostream.SimpleFieldSetMarshaller;
import org.wildfly.clustering.server.infinispan.group.InfinispanAddressMarshaller;
/**
* {@link org.infinispan.protostream.SerializationContextInitializer} for this package.
* @author Paul Ferraro
*/
public class ServiceProviderRegistrySerializationContextInitializer extends AbstractSerializationContextInitializer {
@Override
public void registerMarshallers(SerializationContext context) {
ProtoStreamMarshaller<Address> addressMarshaller = new SimpleFieldSetMarshaller<>(Address.class, InfinispanAddressMarshaller.INSTANCE);
context.registerMarshaller(new FunctionalMarshaller<>(ConcurrentAddressSetAddFunction.class, addressMarshaller, ConcurrentAddressSetAddFunction::getOperand, ConcurrentAddressSetAddFunction::new));
context.registerMarshaller(new FunctionalMarshaller<>(ConcurrentAddressSetRemoveFunction.class, addressMarshaller, ConcurrentAddressSetRemoveFunction::getOperand, ConcurrentAddressSetRemoveFunction::new));
context.registerMarshaller(new FunctionalMarshaller<>(CopyOnWriteAddressSetAddFunction.class, addressMarshaller, CopyOnWriteAddressSetAddFunction::getOperand, CopyOnWriteAddressSetAddFunction::new));
context.registerMarshaller(new FunctionalMarshaller<>(CopyOnWriteAddressSetRemoveFunction.class, addressMarshaller, CopyOnWriteAddressSetRemoveFunction::getOperand, CopyOnWriteAddressSetRemoveFunction::new));
}
}
| 2,919
| 59.833333
| 216
|
java
|
null |
wildfly-main/clustering/ee/spi/src/test/java/org/wildfly/clustering/ee/ExpirationMetaDataTestCase.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.ee;
import java.time.Duration;
import java.time.Instant;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.clustering.ee.expiration.ExpirationMetaData;
/**
* Validates ExpirationMetaData logic.
* @author Paul Ferraro
*/
public class ExpirationMetaDataTestCase {
@Test
public void nullTimeout() {
ExpirationMetaData metaData = new ExpirationMetaData() {
@Override
public Duration getTimeout() {
return null;
}
@Override
public Instant getLastAccessTime() {
return Instant.now().plus(Duration.ofHours(1));
}
};
Assert.assertFalse(metaData.isExpired());
Assert.assertTrue(metaData.isImmortal());
}
@Test
public void negativeTimeout() {
ExpirationMetaData metaData = new ExpirationMetaData() {
@Override
public Duration getTimeout() {
return Duration.ofSeconds(-1);
}
@Override
public Instant getLastAccessTime() {
return Instant.now().plus(Duration.ofHours(1));
}
};
Assert.assertFalse(metaData.isExpired());
Assert.assertTrue(metaData.isImmortal());
}
@Test
public void zeroTimeout() {
ExpirationMetaData metaData = new ExpirationMetaData() {
@Override
public Duration getTimeout() {
return Duration.ZERO;
}
@Override
public Instant getLastAccessTime() {
return Instant.now().plus(Duration.ofHours(1));
}
};
Assert.assertFalse(metaData.isExpired());
Assert.assertTrue(metaData.isImmortal());
}
@Test
public void expired() {
ExpirationMetaData metaData = new ExpirationMetaData() {
@Override
public Duration getTimeout() {
return Duration.ofMinutes(1);
}
@Override
public Instant getLastAccessTime() {
return Instant.now().minus(Duration.ofHours(1));
}
};
Assert.assertTrue(metaData.isExpired());
Assert.assertFalse(metaData.isImmortal());
}
@Test
public void notYetExpired() {
ExpirationMetaData metaData = new ExpirationMetaData() {
@Override
public Duration getTimeout() {
return Duration.ofHours(1);
}
@Override
public Instant getLastAccessTime() {
return Instant.now();
}
};
Assert.assertFalse(metaData.isExpired());
Assert.assertFalse(metaData.isImmortal());
}
}
| 3,799
| 28.6875
| 70
|
java
|
null |
wildfly-main/clustering/ee/spi/src/test/java/org/wildfly/clustering/ee/immutable/DefaultImmutabilityTestCase.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.ee.immutable;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.file.FileSystems;
import java.security.AllPermission;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.MonthDay;
import java.time.Period;
import java.time.Year;
import java.time.YearMonth;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DecimalStyle;
import java.time.temporal.ValueRange;
import java.time.temporal.WeekFields;
import java.time.zone.ZoneOffsetTransitionRule;
import java.time.zone.ZoneOffsetTransitionRule.TimeDefinition;
import java.time.zone.ZoneRules;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collections;
import java.util.Currency;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Test;
import org.wildfly.clustering.ee.Immutability;
/**
* Unit test for {@link DefaultImmutability}
*
* @author Paul Ferraro
*/
public class DefaultImmutabilityTestCase {
@Test
public void test() throws Exception {
this.test(new CompositeImmutability(EnumSet.allOf(DefaultImmutability.class)));
}
protected void test(Immutability immutability) throws Exception {
assertFalse(immutability.test(new Object()));
assertFalse(immutability.test(new Date()));
assertFalse(immutability.test(new AtomicInteger()));
assertFalse(immutability.test(new AtomicLong()));
assertTrue(immutability.test(null));
assertTrue(immutability.test(Collections.emptyEnumeration()));
assertTrue(immutability.test(Collections.emptyIterator()));
assertTrue(immutability.test(Collections.emptyList()));
assertTrue(immutability.test(Collections.emptyListIterator()));
assertTrue(immutability.test(Collections.emptyMap()));
assertTrue(immutability.test(Collections.emptyNavigableMap()));
assertTrue(immutability.test(Collections.emptyNavigableSet()));
assertTrue(immutability.test(Collections.emptySet()));
assertTrue(immutability.test(Collections.emptySortedMap()));
assertTrue(immutability.test(Collections.emptySortedSet()));
assertTrue(immutability.test(Boolean.TRUE));
assertTrue(immutability.test('a'));
assertTrue(immutability.test(this.getClass()));
assertTrue(immutability.test(Currency.getInstance(Locale.US)));
assertTrue(immutability.test(Locale.getDefault()));
assertTrue(immutability.test(Integer.valueOf(1).byteValue()));
assertTrue(immutability.test(Integer.valueOf(1).shortValue()));
assertTrue(immutability.test(1));
assertTrue(immutability.test(1L));
assertTrue(immutability.test(1F));
assertTrue(immutability.test(1.0));
assertTrue(immutability.test(BigInteger.valueOf(1)));
assertTrue(immutability.test(BigDecimal.valueOf(1)));
assertTrue(immutability.test(InetAddress.getLocalHost()));
assertTrue(immutability.test(new InetSocketAddress(InetAddress.getLocalHost(), 80)));
assertTrue(immutability.test(MathContext.UNLIMITED));
assertTrue(immutability.test("test"));
assertTrue(immutability.test(TimeZone.getDefault()));
assertTrue(immutability.test(UUID.randomUUID()));
assertTrue(immutability.test(TimeUnit.DAYS));
File file = new File(System.getProperty("user.home"));
assertTrue(immutability.test(file));
assertTrue(immutability.test(file.toURI()));
assertTrue(immutability.test(file.toURI().toURL()));
assertTrue(immutability.test(FileSystems.getDefault().getRootDirectories().iterator().next()));
assertTrue(immutability.test(new AllPermission()));
assertTrue(immutability.test(DateTimeFormatter.BASIC_ISO_DATE));
assertTrue(immutability.test(DecimalStyle.STANDARD));
assertTrue(immutability.test(Duration.ZERO));
assertTrue(immutability.test(Instant.now()));
assertTrue(immutability.test(LocalDate.now()));
assertTrue(immutability.test(LocalDateTime.now()));
assertTrue(immutability.test(LocalTime.now()));
assertTrue(immutability.test(MonthDay.now()));
assertTrue(immutability.test(Period.ZERO));
assertTrue(immutability.test(ValueRange.of(0L, 10L)));
assertTrue(immutability.test(WeekFields.ISO));
assertTrue(immutability.test(Year.now()));
assertTrue(immutability.test(YearMonth.now()));
assertTrue(immutability.test(ZoneOffset.UTC));
assertTrue(immutability.test(ZoneRules.of(ZoneOffset.UTC).nextTransition(Instant.now())));
assertTrue(immutability.test(ZoneOffsetTransitionRule.of(Month.JANUARY, 1, DayOfWeek.SUNDAY, LocalTime.MIDNIGHT, true, TimeDefinition.STANDARD, ZoneOffset.UTC, ZoneOffset.ofHours(1), ZoneOffset.ofHours(2))));
assertTrue(immutability.test(ZoneRules.of(ZoneOffset.UTC)));
assertTrue(immutability.test(ZonedDateTime.now()));
assertTrue(immutability.test(new JCIPImmutableObject()));
assertTrue(immutability.test(Collections.singleton("1")));
assertTrue(immutability.test(Collections.singletonList("1")));
assertTrue(immutability.test(Collections.singletonMap("1", "2")));
assertTrue(immutability.test(Collections.singleton(new JCIPImmutableObject())));
assertTrue(immutability.test(Collections.singletonList(new JCIPImmutableObject())));
assertTrue(immutability.test(Collections.singletonMap("1", new JCIPImmutableObject())));
assertTrue(immutability.test(new AbstractMap.SimpleImmutableEntry<>("1", new JCIPImmutableObject())));
assertTrue(immutability.test(Collections.unmodifiableCollection(Arrays.asList("1", "2"))));
assertTrue(immutability.test(Collections.unmodifiableList(Arrays.asList("1", "2"))));
assertTrue(immutability.test(Collections.unmodifiableMap(Collections.singletonMap("1", "2"))));
assertTrue(immutability.test(Collections.unmodifiableNavigableMap(new TreeMap<>(Collections.singletonMap("1", "2")))));
assertTrue(immutability.test(Collections.unmodifiableNavigableSet(new TreeSet<>(Collections.singleton("1")))));
assertTrue(immutability.test(Collections.unmodifiableSet(Collections.singleton("1"))));
assertTrue(immutability.test(Collections.unmodifiableSortedMap(new TreeMap<>(Collections.singletonMap("1", "2")))));
assertTrue(immutability.test(Collections.unmodifiableSortedSet(new TreeSet<>(Collections.singleton("1")))));
assertTrue(immutability.test(List.of()));
assertTrue(immutability.test(List.of(1)));
assertTrue(immutability.test(List.of(1, 2)));
assertTrue(immutability.test(List.of(1, 2, 3)));
assertTrue(immutability.test(List.of(1, 2, 3, 4)));
assertTrue(immutability.test(List.of(1, 2, 3, 4, 5)));
assertTrue(immutability.test(List.of(1, 2, 3, 4, 5, 6)));
assertTrue(immutability.test(List.of(1, 2, 3, 4, 5, 6, 7)));
assertTrue(immutability.test(List.of(1, 2, 3, 4, 5, 6, 7, 8)));
assertTrue(immutability.test(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9)));
assertTrue(immutability.test(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)));
assertTrue(immutability.test(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)));
assertTrue(immutability.test(Set.of()));
assertTrue(immutability.test(Set.of(1)));
assertTrue(immutability.test(Set.of(1, 2)));
assertTrue(immutability.test(Set.of(1, 2, 3)));
assertTrue(immutability.test(Set.of(1, 2, 3, 4)));
assertTrue(immutability.test(Set.of(1, 2, 3, 4, 5)));
assertTrue(immutability.test(Set.of(1, 2, 3, 4, 5, 6)));
assertTrue(immutability.test(Set.of(1, 2, 3, 4, 5, 6, 7)));
assertTrue(immutability.test(Set.of(1, 2, 3, 4, 5, 6, 7, 8)));
assertTrue(immutability.test(Set.of(1, 2, 3, 4, 5, 6, 7, 8, 9)));
assertTrue(immutability.test(Set.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)));
assertTrue(immutability.test(Set.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)));
assertTrue(immutability.test(Map.of()));
assertTrue(immutability.test(Map.of(1, "1")));
assertTrue(immutability.test(Map.of(1, "1", 2, "2")));
assertTrue(immutability.test(Map.of(1, "1", 2, "2", 3, "3")));
assertTrue(immutability.test(Map.of(1, "1", 2, "2", 3, "3", 4, "4")));
assertTrue(immutability.test(Map.of(1, "1", 2, "2", 3, "3", 4, "4", 5, "5")));
assertTrue(immutability.test(Map.of(1, "1", 2, "2", 3, "3", 4, "4", 5, "5", 6, "6")));
assertTrue(immutability.test(Map.of(1, "1", 2, "2", 3, "3", 4, "4", 5, "5", 6, "6", 7, "7")));
assertTrue(immutability.test(Map.of(1, "1", 2, "2", 3, "3", 4, "4", 5, "5", 6, "6", 7, "7", 8, "8")));
assertTrue(immutability.test(Map.of(1, "1", 2, "2", 3, "3", 4, "4", 5, "5", 6, "6", 7, "7", 8, "8", 9, "9")));
assertTrue(immutability.test(Map.of(1, "1", 2, "2", 3, "3", 4, "4", 5, "5", 6, "6", 7, "7", 8, "8", 9, "9", 10, "10")));
assertTrue(immutability.test(Map.ofEntries()));
assertTrue(immutability.test(Map.ofEntries(Map.entry(1, "1"))));
assertTrue(immutability.test(Map.ofEntries(Map.entry(1, "1"), Map.entry(2, "2"))));
Object mutableObject = new AtomicInteger();
assertFalse(immutability.test(Collections.singletonList(mutableObject)));
assertFalse(immutability.test(Collections.singletonMap("1", mutableObject)));
assertFalse(immutability.test(new AbstractMap.SimpleImmutableEntry<>("1", mutableObject)));
}
@net.jcip.annotations.Immutable
static class JCIPImmutableObject {
}
}
| 11,412
| 51.353211
| 216
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Invoker.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.ee;
import org.wildfly.common.function.ExceptionRunnable;
import org.wildfly.common.function.ExceptionSupplier;
/**
* Defines a strategy for invoking a given action.
* @author Paul Ferraro
*/
public interface Invoker {
/**
* Invokes the specified action
* @param action an action to be invoked
* @return the result of the action
* @throws Exception if invocation fails
*/
<R, E extends Exception> R invoke(ExceptionSupplier<R, E> action) throws E;
/**
* Invokes the specified action
* @param action an action to be invoked
* @throws Exception if invocation fails
*/
<E extends Exception> void invoke(ExceptionRunnable<E> action) throws E;
}
| 1,762
| 36.510638
| 79
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Remover.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.ee;
/**
* Removes an entry from the cache
* @author Paul Ferraro
*/
public interface Remover<K> {
/**
* Removes the specified entry from the cache.
* @param id the cache entry identifier.
* @return true, if the entry was removed.
*/
boolean remove(K id);
/**
* Like {@link #remove(Object)}, but does not notify listeners.
* @param id the cache entry identifier.
* @return true, if the entry was removed.
*/
default boolean purge(K id) {
return this.remove(id);
}
}
| 1,592
| 34.4
| 70
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Restartable.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.ee;
/**
* Implemented by objects that can be restarted.
* @author Paul Ferraro
*/
public interface Restartable {
/**
* Starts this object.
*/
void start();
/**
* Stops this object.
*/
void stop();
}
| 1,296
| 30.634146
| 70
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Locator.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.ee;
/**
* Locates a value from the cache.
* @author Paul Ferraro
*/
public interface Locator<K, V> {
/**
* Locates the value in the cache with the specified identifier.
* @param id the cache entry identifier
* @return the value of the cache entry, or null if not found.
*/
V findValue(K id);
/**
* Returns the value for the specified key, if possible.
* @param key a cache key
* @return the value of the cache entry, or null if not found or unavailable.
*/
default V tryValue(K key) {
return this.findValue(key);
}
}
| 1,645
| 34.782609
| 81
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Mutator.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.ee;
/**
* Indicates that the value represented by this object has changed and needs to be replicated.
* @author Paul Ferraro
*/
public interface Mutator {
/**
* Ensure that this object replicates.
*/
void mutate();
/**
* Trivial {@link Mutator} implementation that does nothing.
* New cache entries, in particular, don't require mutation.
*/
Mutator PASSIVE = new Mutator() {
@Override
public void mutate() {
// Do nothing
}
};
}
| 1,570
| 33.911111
| 94
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Batch.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.ee;
/**
* Exposes a mechanism to close a batch, and potentially discard it.
* @author Paul Ferraro
*/
public interface Batch extends AutoCloseable {
/**
* The possible states of a batch.
*/
enum State {
/**
* The initial state of a batch.
* A batch remains active until it is discarded or closed.
*/
ACTIVE,
/**
* Indicates that an active batch was discarded, but not yet closed.
* An active batch moves to this state following {@link Batch#discard()}.
*/
DISCARDED,
/**
* The terminal state of a batch.
* A batch moves to this state following {@link Batch#close()}.
*/
CLOSED
}
/**
* Closes this batch. Batch may or may not have been discarded.
*/
@Override
void close();
/**
* Discards this batch. A discarded batch must still be closed.
*/
void discard();
/**
* Returns the state of this batch.
* @return the state of this batch.
*/
State getState();
}
| 2,134
| 30.397059
| 81
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Recordable.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.ee;
/**
* Records some other object.
* @author Paul Ferraro
*/
public interface Recordable<T> {
/**
* Records the specified object
* @param object an object to record
*/
void record(T object);
/**
* Resets any previously recorded objects
*/
void reset();
}
| 1,358
| 32.146341
| 70
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/ManagerFactory.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.ee;
import java.util.function.BiFunction;
import java.util.function.Consumer;
/**
* @author Paul Ferraro
*/
public interface ManagerFactory<K, V> extends BiFunction<Consumer<V>, Consumer<V>, Manager<K, V>> {
/**
* Creates a manager using the specified creation and close tasks.
* @param createTask a task to run on a newly created value
* @param closeTask a task to run on a value to be closed/dereferenced.
*/
@Override
Manager<K, V> apply(Consumer<V> createTask, Consumer<V> closeTask);
}
| 1,582
| 38.575
| 99
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/MutatorFactory.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.ee;
import java.util.Map;
/**
* Creates a mutator instance for a given cache entry.
* @author Paul Ferraro
*/
public interface MutatorFactory<K, V> {
/**
* Creates a mutator for the specified cache entry.
* @param entry a cache entry
* @return a mutator
*/
default Mutator createMutator(Map.Entry<K, V> entry) {
return this.createMutator(entry.getKey(), entry.getValue());
}
/**
* Creates a mutator for the specified cache entry.
* @param key a cache key
* @param value a cache value
* @return a mutator
*/
Mutator createMutator(K key, V value);
}
| 1,681
| 34.041667
| 70
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Manager.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.ee;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* Strategy for managing the creation and destruction of objects.
* @author Paul Ferraro
*/
public interface Manager<K, V> extends BiFunction<K, Function<Runnable, V>, V> {
/**
* Returns the value associated with the specified key, creating it from the specified factory, if necessary.
* @param key the key of the managed value
* @param factory a factory for creating the value from a close task
* @return a managed value
*/
@Override
V apply(K key, Function<Runnable, V> factory);
}
| 1,662
| 38.595238
| 113
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Batcher.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.ee;
/**
* Exposes a mechanism to handle batching.
* @author Paul Ferraro
*/
public interface Batcher<B extends Batch> {
/**
* Creates a batch.
* @return a batch.
*/
B createBatch();
/**
* Resumes a batch. Used if the specified batch was (or may have been) created by another thread.
* @param batch an existing batch
* @return the context of the resumed batch
*/
BatchContext resumeBatch(B batch);
/**
* Suspends a batch.
* @return the previously active batch, or null if there was no active batch
*/
B suspendBatch();
}
| 1,654
| 33.479167
| 101
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Scheduler.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.ee;
import java.util.stream.Stream;
/**
* A task scheduler.
* @author Paul Ferraro
*/
public interface Scheduler<I, M> extends AutoCloseable {
/**
* Schedules a task for the object with the specified identifier, using the specified metaData
* @param id an object identifier
* @param metaData the object meta-data
*/
void schedule(I id, M metaData);
/**
* Cancels a previously scheduled task for the object with the specified identifier.
* @param id an object identifier
*/
void cancel(I id);
/**
* Returns a stream of scheduled item identifiers.
* @return a stream of scheduled item identifiers.
*/
Stream<I> stream();
/**
* Indicates whether the object with the specified identifier is scheduled.
* @param id an object identifier
*/
default boolean contains(I id) {
return this.stream().anyMatch(id::equals);
}
/**
* Closes any resources used by this scheduler.
*/
@Override
void close();
}
| 2,087
| 31.123077
| 98
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/UUIDFactory.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.ee;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
/**
* UUID factory implementations.
* @author Paul Ferraro
*/
public enum UUIDFactory implements Supplier<UUID> {
/**
* UUID factory that uses a {@link ThreadLocalRandom}.
* UUIDs generated by this factory are <em>not</em> cryptographically secure.
*/
INSECURE() {
@Override
public java.util.UUID get() {
byte[] data = new byte[16];
ThreadLocalRandom.current().nextBytes(data);
data[6] &= 0x0f; /* clear version */
data[6] |= 0x40; /* set to version 4 */
data[8] &= 0x3f; /* clear variant */
data[8] |= 0x80; /* set to IETF variant */
long msb = 0;
long lsb = 0;
for (int i = 0; i < 8; i++) {
msb = (msb << 8) | (data[i] & 0xff);
}
for (int i = 8; i < 16; i++) {
lsb = (lsb << 8) | (data[i] & 0xff);
}
return new UUID(msb, lsb);
}
},
/**
* UUID factory that uses a {@link java.security.SecureRandom}.
* UUIDs generated by this factory are cryptographically secure.
*/
SECURE() {
@Override
public java.util.UUID get() {
return UUID.randomUUID();
}
},
;
}
| 2,428
| 33.7
| 81
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Creator.java
|
package org.wildfly.clustering.ee;
/**
* Creates a value in the cache.
* @author Paul Ferraro
*/
public interface Creator<K, V, C> {
/**
* Creates a value in the cache, if it does not already exist.
* @param id the cache entry identifier.
* @parem context the creation context
* @return the new value, or the existing value the cache entry already exists.
*/
V createValue(K id, C context);
}
| 431
| 24.411765
| 83
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/DeploymentConfiguration.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.ee;
/**
* Encapsulates the configuration of a deployment.
* @author Paul Ferraro
*/
public interface DeploymentConfiguration {
/**
* Returns the locally unique name of this deployment.
* @return a deployment name.
*/
String getDeploymentName();
}
| 1,330
| 34.972973
| 70
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Immutability.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.ee;
import java.util.function.Predicate;
/**
* Tests for immutability.
* @author Paul Ferraro
*/
public interface Immutability extends Predicate<Object> {
@Override
default Immutability and(Predicate<? super Object> immutability) {
return new Immutability() {
@Override
public boolean test(Object object) {
return Immutability.this.test(object) && immutability.test(object);
}
};
}
@Override
default Immutability negate() {
return new Immutability() {
@Override
public boolean test(Object object) {
return !Immutability.this.test(object);
}
};
}
@Override
default Immutability or(Predicate<? super Object> immutability) {
return new Immutability() {
@Override
public boolean test(Object object) {
return Immutability.this.test(object) || immutability.test(object);
}
};
}
}
| 2,077
| 31.984127
| 83
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/BatchContext.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.ee;
/**
* Handles batch context switching.
* @author Paul Ferraro
*/
public interface BatchContext extends AutoCloseable {
/**
* Closes this batch context.
*/
@Override
void close();
}
| 1,265
| 35.171429
| 70
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/Key.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.ee;
/**
* A cache key for a given identifier
* @author Paul Ferraro
*/
public interface Key<I> {
I getId();
}
| 1,173
| 35.6875
| 70
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/expiration/Expiration.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.ee.expiration;
import java.time.Duration;
/**
* Describes the expiration criteria for an object.
* @author Paul Ferraro
*/
public interface Expiration {
/**
* The duration of time, after which an idle object should expire.
* @return the object timeout
*/
Duration getTimeout();
/**
* Indicates whether the associated timeout represents and immortal object,
* i.e. does not expire
* @return true, if this object is immortal, false otherwise
*/
default boolean isImmortal() {
Duration timeout = this.getTimeout();
return (timeout == null) || timeout.isZero() || timeout.isNegative();
}
}
| 1,718
| 34.8125
| 79
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/expiration/ExpirationMetaData.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.ee.expiration;
import java.time.Instant;
/**
* Describes expiration-related metadata.
* @author Paul Ferraro
*/
public interface ExpirationMetaData extends Expiration {
/**
* Indicates whether or not this object is expired.
* @return true, if this object has expired, false otherwise.
*/
default boolean isExpired() {
if (this.isImmortal()) return false;
Instant lastAccessedTime = this.getLastAccessTime();
return (lastAccessedTime != null) ? !lastAccessedTime.plus(this.getTimeout()).isAfter(Instant.now()) : false;
}
/**
* Returns the time this object was last accessed.
* @return the time this object was last accessed.
*/
Instant getLastAccessTime();
}
| 1,794
| 35.632653
| 117
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/expiration/ExpirationConfiguration.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.ee.expiration;
import java.util.function.Consumer;
/**
* Encapsulates expiration configuration.
* @author Paul Ferraro
* @param <T> the expired object type
*/
public interface ExpirationConfiguration<T> extends Expiration {
/**
* The listener to notify of expiration events.
* @return the listener to invoke when an object expires.
*/
Consumer<T> getExpirationListener();
}
| 1,458
| 36.410256
| 70
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/concurrent/ServiceExecutor.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.ee.concurrent;
import java.util.Optional;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import org.wildfly.common.function.ExceptionRunnable;
import org.wildfly.common.function.ExceptionSupplier;
/**
* Allows safe invocation of tasks that require resources not available after {@link #close(Runnable)} to block a service from stopping.
* @author Paul Ferraro
*/
public interface ServiceExecutor extends Executor {
/**
* Executes the specified runner.
* @param <E> the exception type
* @param runner a runnable task
* @throws E if execution fails
*/
<E extends Exception> void execute(ExceptionRunnable<E> runner) throws E;
/**
* Executes the specified task, but only if the service was not already closed.
* If service is already closed, the task is not run.
* If executed, the specified task must return a non-null value, to be distinguishable from a non-execution.
* @param executeTask a task to execute
* @return an optional value that is present only if the specified task was run.
*/
<R> Optional<R> execute(Supplier<R> executeTask);
/**
* Executes the specified task, but only if the service was not already closed.
* If service is already closed, the task is not run.
* If executed, the specified task must return a non-null value, to be distinguishable from a non-execution.
* @param executeTask a task to execute
* @return an optional value that is present only if the specified task was run.
* @throws E if the task execution failed
*/
<R, E extends Exception> Optional<R> execute(ExceptionSupplier<R, E> executeTask) throws E;
/**
* Closes the service, executing the specified task, first waiting for any concurrent executions to complete.
* The specified task will only execute once, irrespective on subsequent {@link #close(Runnable)} invocations.
* @param closeTask a task which closes the service
*/
void close(Runnable closeTask);
}
| 3,084
| 41.847222
| 136
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/immutable/InstanceOfImmutability.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.ee.immutable;
import org.wildfly.clustering.ee.Immutability;
/**
* Test for immutability using instanceof checks.
* @author Paul Ferraro
*/
public class InstanceOfImmutability implements Immutability {
private final Iterable<Class<?>> immutableClasses;
public InstanceOfImmutability(Iterable<Class<?>> immutableClasses) {
this.immutableClasses = immutableClasses;
}
@Override
public boolean test(Object object) {
for (Class<?> immutableClass : this.immutableClasses) {
if (immutableClass.isInstance(object)) return true;
}
return false;
}
}
| 1,672
| 34.595745
| 72
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/immutable/SimpleImmutability.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.ee.immutable;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import java.util.function.Function;
import org.wildfly.clustering.ee.Immutability;
/**
* Immutability implementation based on a pre-defined set immutable classes.
* @author Paul Ferraro
*/
public class SimpleImmutability implements Immutability {
private final Set<Class<?>> immutableClasses;
public SimpleImmutability(ClassLoader loader, Collection<String> immutableClassNames) {
this(immutableClassNames, new Function<String, Class<?>>() {
@Override
public Class<?> apply(String className) {
try {
return loader.loadClass(className);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(className, e);
}
}
});
}
public SimpleImmutability(Collection<Class<?>> immutableClasses) {
this(immutableClasses, Function.identity());
}
private <T> SimpleImmutability(Collection<T> immutables, Function<T, Class<?>> operator) {
this.immutableClasses = !immutables.isEmpty() ? Collections.newSetFromMap(new IdentityHashMap<>(immutables.size())) : Collections.emptySet();
for (T immutable : immutables) {
this.immutableClasses.add(operator.apply(immutable));
}
}
public SimpleImmutability(Set<Class<?>> classes) {
this.immutableClasses = classes;
}
@Override
public boolean test(Object object) {
return (object == null) || this.immutableClasses.contains(object.getClass());
}
}
| 2,730
| 35.905405
| 149
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/immutable/DefaultImmutability.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.ee.immutable;
import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.security.Permission;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.MonthDay;
import java.time.Period;
import java.time.Year;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.Chronology;
import java.time.chrono.Era;
import java.time.format.DateTimeFormatter;
import java.time.format.DecimalStyle;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalUnit;
import java.time.temporal.ValueRange;
import java.time.temporal.WeekFields;
import java.time.zone.ZoneOffsetTransition;
import java.time.zone.ZoneOffsetTransitionRule;
import java.time.zone.ZoneRules;
import java.util.Arrays;
import java.util.Collections;
import java.util.Currency;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
import org.wildfly.clustering.ee.Immutability;
/**
* Default set of immutability tests.
* @author Paul Ferraro
*/
public enum DefaultImmutability implements Immutability {
// Singleton immutable objects detectable via reference equality test
OBJECT(new IdentityImmutability(Arrays.asList(
Collections.emptyEnumeration(),
Collections.emptyIterator(),
Collections.emptyList(),
Collections.emptyListIterator(),
Collections.emptyMap(),
Collections.emptyNavigableMap(),
Collections.emptyNavigableSet(),
Collections.emptySet(),
Collections.emptySortedMap(),
Collections.emptySortedSet()))),
// Concrete immutable classes detectable via reference equality test
CLASS(new SimpleImmutability(Arrays.asList(
BigDecimal.class,
BigInteger.class,
Boolean.class,
Byte.class,
Character.class,
Class.class,
Currency.class,
DateTimeFormatter.class,
DecimalStyle.class,
Double.class,
Duration.class,
File.class,
Float.class,
Inet4Address.class,
Inet6Address.class,
InetSocketAddress.class,
Instant.class,
Integer.class,
Locale.class,
LocalDate.class,
LocalDateTime.class,
LocalTime.class,
Long.class,
MathContext.class,
MonthDay.class,
Period.class,
Short.class,
StackTraceElement.class,
String.class,
URI.class,
URL.class,
UUID.class,
ValueRange.class,
WeekFields.class,
Year.class,
YearMonth.class,
ZoneOffset.class,
ZoneOffsetTransition.class,
ZoneOffsetTransitionRule.class,
ZoneRules.class,
ZonedDateTime.class))),
// Interfaces and abstract classes documented to be immutable, but only detectable via instanceof tests
ABSTRACT_CLASS(new InstanceOfImmutability(Arrays.asList(
Chronology.class,
ChronoLocalDate.class,
Clock.class,
Enum.class, // In theory, one could implement a mutable enum, but that would just be weird.
Era.class,
Path.class,
Permission.class,
TemporalField.class,
TemporalUnit.class,
TimeZone.class, // Strictly speaking, this class is mutable, although in practice it is never mutated.
ZoneId.class))),
ANNOTATION(new AnnotationImmutability(net.jcip.annotations.Immutable.class)),
;
private final Immutability immutability;
DefaultImmutability(Immutability immutability) {
this.immutability = immutability;
}
@Override
public boolean test(Object object) {
return this.immutability.test(object);
}
}
| 5,633
| 35.348387
| 118
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/immutable/AnnotationImmutability.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.ee.immutable;
import java.lang.annotation.Annotation;
import org.wildfly.clustering.ee.Immutability;
/**
* Detects the presence of a specific annotation.
* @author Paul Ferraro
*/
public class AnnotationImmutability implements Immutability {
private final Class<? extends Annotation> annotationClass;
public AnnotationImmutability(Class<? extends Annotation> annotationClass) {
this.annotationClass = annotationClass;
}
@Override
public boolean test(Object object) {
return object.getClass().isAnnotationPresent(this.annotationClass);
}
}
| 1,643
| 34.73913
| 80
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/immutable/CompositeImmutability.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.ee.immutable;
import java.lang.reflect.Array;
import java.util.Arrays;
import org.wildfly.clustering.ee.Immutability;
/**
* Decorates a series of immutability predicates to additionally test for collection immutability.
* @author Paul Ferraro
*/
public class CompositeImmutability implements Immutability {
private final Iterable<? extends Immutability> immutabilities;
private final Immutability collectionImmutability;
public CompositeImmutability(Immutability... predicates) {
this(Arrays.asList(predicates));
}
public CompositeImmutability(Iterable<? extends Immutability> immutabilities) {
this.immutabilities = immutabilities;
this.collectionImmutability = new CollectionImmutability(this);
}
@Override
public boolean test(Object object) {
if (object == null) return true;
// Short-circuit test if object is an array
if (object.getClass().isArray()) {
return Array.getLength(object) == 0;
}
for (Immutability immutability : this.immutabilities) {
if (immutability.test(object)) {
return true;
}
}
return this.collectionImmutability.test(object);
}
}
| 2,289
| 35.349206
| 98
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/immutable/CollectionImmutability.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.ee.immutable;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.wildfly.clustering.ee.Immutability;
/**
* Tests the immutability of {@link Collections} wrappers.
* N.B. Strictly speaking, an unmodifiable collection is not necessarily immutable since the collection can still be modified through a reference to the delegate collection.
* Were this the case, the immutability test would also run against the delegate collection - and fail, forcing replication.
* @author Paul Ferraro
*/
public class CollectionImmutability implements Immutability {
private final List<Class<?>> unmodifiableCollectionClasses = Arrays.asList(
Collections.singleton(null).getClass(),
Collections.singletonList(null).getClass(),
Collections.unmodifiableCollection(Collections.emptyList()).getClass(),
Collections.unmodifiableList(Collections.emptyList()).getClass(),
Collections.unmodifiableNavigableSet(Collections.emptyNavigableSet()).getClass(),
Collections.unmodifiableSet(Collections.emptySet()).getClass(),
Collections.unmodifiableSortedSet(Collections.emptySortedSet()).getClass(),
List.of().getClass(), // ListN
List.of(Boolean.TRUE).getClass(), // List12
Set.of().getClass(), // SetN
Set.of(Boolean.TRUE).getClass()); // Set12
private final List<Class<?>> unmodifiableMapClasses = Arrays.asList(
Collections.singletonMap(null, null).getClass(),
Collections.unmodifiableMap(Collections.emptyMap()).getClass(),
Collections.unmodifiableNavigableMap(Collections.emptyNavigableMap()).getClass(),
Collections.unmodifiableSortedMap(Collections.emptySortedMap()).getClass(),
Map.ofEntries().getClass(), // MapN
Map.ofEntries(Map.entry(Boolean.TRUE, Boolean.TRUE)).getClass()); // Map1
private final Immutability elementImmutability;
public CollectionImmutability(Immutability elementImmutability) {
this.elementImmutability = elementImmutability;
}
@Override
public boolean test(Object object) {
for (Class<?> unmodifiableCollectionClass : this.unmodifiableCollectionClasses) {
if (unmodifiableCollectionClass.isInstance(object)) {
// An unmodifiable collection is immutable if its members are immutable.
for (Object element : (Collection<?>) object) {
if (!this.elementImmutability.test(element)) return false;
}
return true;
}
}
for (Class<?> unmodifiableMapClass : this.unmodifiableMapClasses) {
if (unmodifiableMapClass.isInstance(object)) {
// An unmodifiable map is immutable if its entries are immutable.
for (Map.Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
if (!this.test(entry)) return false;
}
return true;
}
}
if (object instanceof AbstractMap.SimpleImmutableEntry) {
return this.test((Map.Entry<?, ?>) object);
}
return false;
}
// An unmodifiable map entry is immutable if its key and value are immutable.
private boolean test(Map.Entry<?, ?> entry) {
return this.elementImmutability.test(entry.getKey()) && this.elementImmutability.test(entry.getValue());
}
}
| 4,691
| 45.455446
| 173
|
java
|
null |
wildfly-main/clustering/ee/spi/src/main/java/org/wildfly/clustering/ee/immutable/IdentityImmutability.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.ee.immutable;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import org.wildfly.clustering.ee.Immutability;
/**
* Test for immutability using object identity.
* @author Paul Ferraro
*/
public class IdentityImmutability implements Immutability {
private final Set<Object> immutableObjects;
public IdentityImmutability(Collection<Object> objects) {
this.immutableObjects = !objects.isEmpty() ? Collections.newSetFromMap(new IdentityHashMap<>(objects.size())) : Collections.emptySet();
for (Object object : objects) {
this.immutableObjects.add(object);
}
}
@Override
public boolean test(Object object) {
return (object == null) || this.immutableObjects.contains(object);
}
}
| 1,872
| 35.019231
| 143
|
java
|
null |
wildfly-main/clustering/ee/cache/src/test/java/org/wildfly/clustering/ee/cache/ConcurrentManagerTestCase.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.ee.cache;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.clustering.ee.Manager;
/**
* @author Paul Ferraro
*/
public class ConcurrentManagerTestCase {
private static final int KEYS = 10;
private static final int SIZE = 100;
@Test
public void test() throws InterruptedException, ExecutionException {
Manager<Integer, ManagedObject> manager = new ConcurrentManager<>(ManagedObject::created, ManagedObject::closed);
List<List<Future<ManagedObject>>> keyFutures = new ArrayList<>(KEYS);
ExecutorService executor = Executors.newFixedThreadPool(KEYS);
try {
for (int i = 0; i < KEYS; ++i) {
List<Future<ManagedObject>> futures = new ArrayList<>(SIZE);
keyFutures.add(futures);
for (int j = 0; j < SIZE; ++j) {
int key = i;
Callable<ManagedObject> task = () -> {
try (ManagedObject object = manager.apply(key, ManagedObject::new)) {
Assert.assertTrue(object.isCreated());
Assert.assertFalse(object.isClosed());
Thread.sleep(10);
return object;
}
};
futures.add(executor.submit(task));
}
}
// Wait until all tasks are finished
for (List<Future<ManagedObject>> futures : keyFutures) {
for (Future<ManagedObject> future : futures) {
future.get();
}
}
// Verify
for (List<Future<ManagedObject>> futures : keyFutures) {
for (Future<ManagedObject> future : futures) {
ManagedObject object = future.get();
Assert.assertTrue(object.toString(), object.isCreated());
Assert.assertTrue(object.toString(), object.isClosed());
}
}
} finally {
executor.shutdown();
}
}
private static class ManagedObject implements AutoCloseable {
private volatile boolean created = false;
private volatile boolean closed = false;
private final Runnable closeTask;
ManagedObject(Runnable closeTask) {
this.closeTask = closeTask;
}
void created() {
this.created = true;
}
boolean isCreated() {
return this.created;
}
void closed() {
this.closed = true;
}
boolean isClosed() {
return this.closed;
}
@Override
public void close() {
this.closeTask.run();
}
}
}
| 4,097
| 34.025641
| 121
|
java
|
null |
wildfly-main/clustering/ee/cache/src/test/java/org/wildfly/clustering/ee/cache/function/FunctionTestCase.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.ee.cache.function;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Paul Ferraro
*/
public class FunctionTestCase {
@Test
public void copyOnWriteSet() {
Set<String> result = new CopyOnWriteSetAddFunction<>("foo").apply(null, null);
Assert.assertNotNull(result);
Assert.assertTrue(result.contains("foo"));
Set<String> result2 = new CopyOnWriteSetAddFunction<>("bar").apply(null, result);
Assert.assertNotNull(result2);
Assert.assertNotSame(result, result2);
Assert.assertTrue(result2.contains("foo"));
Assert.assertTrue(result2.contains("bar"));
Set<String> result3 = new CopyOnWriteSetRemoveFunction<>("foo").apply(null, result2);
Assert.assertNotNull(result3);
Assert.assertNotSame(result2, result3);
Assert.assertFalse(result3.contains("foo"));
Assert.assertTrue(result3.contains("bar"));
Set<String> result4 = new CopyOnWriteSetRemoveFunction<>("bar").apply(null, result3);
Assert.assertNull(result4);
}
@Test
public void concurrentSet() {
Set<String> result = new ConcurrentSetAddFunction<>("foo").apply(null, null);
Assert.assertNotNull(result);
Assert.assertTrue(result.contains("foo"));
Set<String> result2 = new ConcurrentSetAddFunction<>("bar").apply(null, result);
Assert.assertNotNull(result2);
Assert.assertSame(result, result2);
Assert.assertTrue(result2.contains("foo"));
Assert.assertTrue(result2.contains("bar"));
Set<String> result3 = new ConcurrentSetRemoveFunction<>("foo").apply(null, result2);
Assert.assertNotNull(result3);
Assert.assertSame(result2, result3);
Assert.assertFalse(result3.contains("foo"));
Assert.assertTrue(result3.contains("bar"));
Set<String> result4 = new ConcurrentSetRemoveFunction<>("bar").apply(null, result3);
Assert.assertNull(result4);
}
@Test
public void copyOnWriteMap() {
Map<String, String> result = new CopyOnWriteMapPutFunction<>("foo", "a").apply(null, null);
Assert.assertNotNull(result);
Assert.assertTrue(result.containsKey("foo"));
Map<String, String> result2 = new CopyOnWriteMapPutFunction<>("bar", "b").apply(null, result);
Assert.assertNotNull(result2);
Assert.assertNotSame(result, result2);
Assert.assertTrue(result2.containsKey("foo"));
Assert.assertTrue(result2.containsKey("bar"));
Map<String, String> result3 = new CopyOnWriteMapRemoveFunction<String, String>("foo").apply(null, result2);
Assert.assertNotNull(result3);
Assert.assertNotSame(result2, result3);
Assert.assertFalse(result3.containsKey("foo"));
Assert.assertTrue(result3.containsKey("bar"));
Map<String, String> result4 = new CopyOnWriteMapRemoveFunction<String, String>("bar").apply(null, result3);
Assert.assertNull(result4);
}
@Test
public void concurrentMap() {
Map<String, String> result = new ConcurrentMapPutFunction<>("foo", "a").apply(null, null);
Assert.assertNotNull(result);
Assert.assertTrue(result.containsKey("foo"));
Map<String, String> result2 = new ConcurrentMapPutFunction<>("bar", "b").apply(null, result);
Assert.assertNotNull(result2);
Assert.assertSame(result, result2);
Assert.assertTrue(result2.containsKey("foo"));
Assert.assertTrue(result2.containsKey("bar"));
Map<String, String> result3 = new ConcurrentMapRemoveFunction<String, String>("foo").apply(null, result2);
Assert.assertNotNull(result3);
Assert.assertSame(result2, result3);
Assert.assertFalse(result3.containsKey("foo"));
Assert.assertTrue(result3.containsKey("bar"));
Map<String, String> result4 = new ConcurrentMapRemoveFunction<String, String>("bar").apply(null, result3);
Assert.assertNull(result4);
}
}
| 5,090
| 40.390244
| 115
|
java
|
null |
wildfly-main/clustering/ee/cache/src/test/java/org/wildfly/clustering/ee/cache/scheduler/LinkedScheduledEntriesTestCase.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.ee.cache.scheduler;
import java.util.function.UnaryOperator;
/**
* Unit test for {@link LinkedScheduledEntries}
* @author Paul Ferraro
*/
public class LinkedScheduledEntriesTestCase extends AbstractScheduledEntriesTestCase {
public LinkedScheduledEntriesTestCase() {
super(new LinkedScheduledEntries<>(), UnaryOperator.identity());
}
}
| 1,413
| 37.216216
| 86
|
java
|
null |
wildfly-main/clustering/ee/cache/src/test/java/org/wildfly/clustering/ee/cache/scheduler/AbstractScheduledEntriesTestCase.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.ee.cache.scheduler;
import java.time.Duration;
import java.time.Instant;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.function.UnaryOperator;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Paul Ferraro
*/
public abstract class AbstractScheduledEntriesTestCase {
private final ScheduledEntries<UUID, Instant> entrySet;
private final UnaryOperator<List<Map.Entry<UUID, Instant>>> expectedFactory;
AbstractScheduledEntriesTestCase(ScheduledEntries<UUID, Instant> entrySet, UnaryOperator<List<Map.Entry<UUID, Instant>>> expectedFactory) {
this.entrySet = entrySet;
this.expectedFactory = expectedFactory;
}
@Test
public void test() {
// Verify empty
Assert.assertFalse(this.entrySet.iterator().hasNext());
// Populate
List<Map.Entry<UUID, Instant>> entries = new LinkedList<>();
Instant now = Instant.now();
entries.add(new SimpleImmutableEntry<>(UUID.randomUUID(), now));
entries.add(new SimpleImmutableEntry<>(UUID.randomUUID(), now));
entries.add(new SimpleImmutableEntry<>(UUID.randomUUID(), now.minus(Duration.ofSeconds(1))));
entries.add(new SimpleImmutableEntry<>(UUID.randomUUID(), now.plus(Duration.ofSeconds(2))));
entries.add(new SimpleImmutableEntry<>(UUID.randomUUID(), now.plus(Duration.ofSeconds(1))));
for (Map.Entry<UUID, Instant> entry : entries) {
this.entrySet.add(entry.getKey(), entry.getValue());
}
List<Map.Entry<UUID, Instant>> expected = this.expectedFactory.apply(entries);
Assert.assertEquals(5, expected.size());
// Verify iteration order corresponds to expected order
Iterator<Map.Entry<UUID, Instant>> iterator = this.entrySet.iterator();
for (Map.Entry<UUID, Instant> entry : expected) {
Assert.assertTrue(iterator.hasNext());
Map.Entry<UUID, Instant> result = iterator.next();
Assert.assertSame(entry.getKey(), result.getKey());
Assert.assertSame(entry.getValue(), result.getValue());
}
Assert.assertFalse(iterator.hasNext());
// Verify iteration order after removal of first item
this.entrySet.remove(expected.remove(0).getKey());
// Verify iteration order corresponds to expected order
iterator = this.entrySet.iterator();
for (Map.Entry<UUID, Instant> entry : expected) {
Assert.assertTrue(iterator.hasNext());
Map.Entry<UUID, Instant> result = iterator.next();
Assert.assertSame(entry.getKey(), result.getKey());
Assert.assertSame(entry.getValue(), result.getValue());
}
Assert.assertFalse(iterator.hasNext());
// Verify iteration order after removal of middle item
this.entrySet.remove(expected.remove((expected.size() - 1) / 2).getKey());
// Verify iteration order corresponds to expected order
iterator = this.entrySet.iterator();
for (Map.Entry<UUID, Instant> entry : expected) {
Assert.assertTrue(iterator.hasNext());
Map.Entry<UUID, Instant> result = iterator.next();
Assert.assertSame(entry.getKey(), result.getKey());
Assert.assertSame(entry.getValue(), result.getValue());
}
Assert.assertFalse(iterator.hasNext());
// Verify iteration order after removal of last item
this.entrySet.remove(expected.remove((expected.size() - 1)).getKey());
// Verify iteration order corresponds to expected order
iterator = this.entrySet.iterator();
for (Map.Entry<UUID, Instant> entry : expected) {
Assert.assertTrue(iterator.hasNext());
Map.Entry<UUID, Instant> result = iterator.next();
Assert.assertSame(entry.getKey(), result.getKey());
Assert.assertSame(entry.getValue(), result.getValue());
}
Assert.assertFalse(iterator.hasNext());
// Verify removal of non-existent entry
this.entrySet.remove(UUID.randomUUID());
}
}
| 5,269
| 41.16
| 143
|
java
|
null |
wildfly-main/clustering/ee/cache/src/test/java/org/wildfly/clustering/ee/cache/scheduler/LocalSchedulerTestCase.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.ee.cache.scheduler;
import static org.mockito.Mockito.*;
import java.time.Duration;
import java.time.Instant;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Predicate;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.clustering.ee.Scheduler;
/**
* @author Paul Ferraro
*/
public class LocalSchedulerTestCase {
@Test
public void successfulTask() throws InterruptedException {
ScheduledEntries<UUID, Instant> entries = mock(ScheduledEntries.class);
Predicate<UUID> task = mock(Predicate.class);
Map.Entry<UUID, Instant> entry = new SimpleImmutableEntry<>(UUID.randomUUID(), Instant.now());
List<Map.Entry<UUID, Instant>> entryList = new ArrayList<>(1);
entryList.add(entry);
try (Scheduler<UUID, Instant> scheduler = new LocalScheduler<>(entries, task, Duration.ZERO)) {
// Verify simple scheduling
when(entries.peek()).thenReturn(entry, null);
doAnswer(invocation -> entryList.iterator()).when(entries).iterator();
when(task.test(entry.getKey())).thenReturn(true);
scheduler.schedule(entry.getKey(), entry.getValue());
verify(entries).add(entry.getKey(), entry.getValue());
Thread.sleep(500);
// Verify that entry was removed from backing collection
Assert.assertTrue(entryList.isEmpty());
}
}
@Test
public void failingTask() throws InterruptedException {
ScheduledEntries<UUID, Instant> entries = mock(ScheduledEntries.class);
Predicate<UUID> task = mock(Predicate.class);
Map.Entry<UUID, Instant> entry = new SimpleImmutableEntry<>(UUID.randomUUID(), Instant.now());
List<Map.Entry<UUID, Instant>> entryList = new ArrayList<>(1);
entryList.add(entry);
try (Scheduler<UUID, Instant> scheduler = new LocalScheduler<>(entries, task, Duration.ZERO)) {
// Verify that a failing scheduled task does not trigger removal
when(entries.peek()).thenReturn(entry, null);
doAnswer(invocation -> entryList.iterator()).when(entries).iterator();
when(task.test(entry.getKey())).thenReturn(false);
scheduler.schedule(entry.getKey(), entry.getValue());
verify(entries).add(entry.getKey(), entry.getValue());
Thread.sleep(500);
// Verify that entry was not removed from backing collection
Assert.assertFalse(entryList.isEmpty());
}
}
@Test
public void retryUntilSuccessfulTask() throws InterruptedException {
ScheduledEntries<UUID, Instant> entries = mock(ScheduledEntries.class);
Predicate<UUID> task = mock(Predicate.class);
Map.Entry<UUID, Instant> entry = new SimpleImmutableEntry<>(UUID.randomUUID(), Instant.now());
List<Map.Entry<UUID, Instant>> entryList = new ArrayList<>(1);
entryList.add(entry);
try (Scheduler<UUID, Instant> scheduler = new LocalScheduler<>(entries, task, Duration.ZERO)) {
// Verify that a failing scheduled task does not trigger removal
when(entries.peek()).thenReturn(entry, entry, null);
doAnswer(invocation -> entryList.iterator()).when(entries).iterator();
when(task.test(entry.getKey())).thenReturn(false, true);
scheduler.schedule(entry.getKey(), entry.getValue());
verify(entries).add(entry.getKey(), entry.getValue());
Thread.sleep(500);
// Verify that entry was eventually removed from backing collection
Assert.assertTrue(entryList.isEmpty());
}
}
@Test
public void cancel() {
ScheduledEntries<UUID, Instant> entries = mock(ScheduledEntries.class);
Predicate<UUID> task = mock(Predicate.class);
Map.Entry<UUID, Instant> entry = new SimpleImmutableEntry<>(UUID.randomUUID(), Instant.now());
try (Scheduler<UUID, Instant> scheduler = new LocalScheduler<>(entries, task, Duration.ZERO)) {
when(entries.peek()).thenReturn(entry);
scheduler.cancel(entry.getKey());
verify(entries).remove(entry.getKey());
}
}
}
| 5,376
| 37.683453
| 103
|
java
|
null |
wildfly-main/clustering/ee/cache/src/test/java/org/wildfly/clustering/ee/cache/scheduler/SortedScheduledEntriesTestCase.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.ee.cache.scheduler;
import java.time.Instant;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Unit test for {@link SortedScheduledEntries}
* @author Paul Ferraro
*/
public class SortedScheduledEntriesTestCase extends AbstractScheduledEntriesTestCase {
public SortedScheduledEntriesTestCase() {
super(new SortedScheduledEntries<>(), list -> {
List<Map.Entry<UUID, Instant>> result = new LinkedList<>(list);
Collections.sort(result, SortedScheduledEntries.comparingByValue());
return result;
});
}
}
| 1,704
| 36.065217
| 86
|
java
|
null |
wildfly-main/clustering/ee/cache/src/test/java/org/wildfly/clustering/ee/cache/concurrent/StampedLockServiceExecutorTestCase.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.ee.cache.concurrent;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Supplier;
import org.junit.Test;
import org.wildfly.clustering.ee.concurrent.ServiceExecutor;
import org.wildfly.common.function.ExceptionRunnable;
import org.wildfly.common.function.ExceptionSupplier;
/**
* @author Paul Ferraro
*/
public class StampedLockServiceExecutorTestCase {
@Test
public void testExecuteRunnable() {
ServiceExecutor executor = new StampedLockServiceExecutor();
Runnable executeTask = mock(Runnable.class);
executor.execute(executeTask);
// Task should run
verify(executeTask).run();
reset(executeTask);
Runnable closeTask = mock(Runnable.class);
executor.close(closeTask);
verify(closeTask).run();
reset(closeTask);
executor.close(closeTask);
// Close task should only run once
verify(closeTask, never()).run();
executor.execute(executeTask);
// Task should no longer run since service is closed
verify(executeTask, never()).run();
}
@SuppressWarnings("unchecked")
@Test
public void testExecuteExceptionRunnable() throws Exception {
ServiceExecutor executor = new StampedLockServiceExecutor();
ExceptionRunnable<Exception> executeTask = mock(ExceptionRunnable.class);
executor.execute(executeTask);
// Task should run
verify(executeTask).run();
reset(executeTask);
doThrow(new Exception()).when(executeTask).run();
try {
executor.execute(executeTask);
fail("Should have thrown an exception");
} catch (Exception e) {
assertNotNull(e);
}
reset(executeTask);
Runnable closeTask = mock(Runnable.class);
executor.close(closeTask);
verify(closeTask).run();
reset(closeTask);
executor.close(closeTask);
// Close task should only run once
verify(closeTask, never()).run();
executor.execute(executeTask);
// Task should no longer run since service is closed
verify(executeTask, never()).run();
}
@SuppressWarnings("unchecked")
@Test
public void testExecuteSupplier() {
ServiceExecutor executor = new StampedLockServiceExecutor();
Object expected = new Object();
Supplier<Object> executeTask = mock(Supplier.class);
when(executeTask.get()).thenReturn(expected);
Optional<Object> result = executor.execute(executeTask);
// Task should run
assertTrue(result.isPresent());
assertSame(expected, result.get());
reset(executeTask);
Runnable closeTask = mock(Runnable.class);
executor.close(closeTask);
verify(closeTask).run();
reset(closeTask);
executor.close(closeTask);
// Close task should only run once
verify(closeTask, never()).run();
result = executor.execute(executeTask);
// Task should no longer run since service is closed
assertFalse(result.isPresent());
}
@SuppressWarnings("unchecked")
@Test
public void testExecuteExceptionSupplier() throws Exception {
ServiceExecutor executor = new StampedLockServiceExecutor();
Object expected = new Object();
ExceptionSupplier<Object, Exception> executeTask = mock(ExceptionSupplier.class);
when(executeTask.get()).thenReturn(expected);
Optional<Object> result = executor.execute(executeTask);
// Task should run
assertTrue(result.isPresent());
assertSame(expected, result.get());
reset(executeTask);
doThrow(new Exception()).when(executeTask).get();
try {
executor.execute(executeTask);
fail("Should have thrown an exception");
} catch (Exception e) {
assertNotNull(e);
}
reset(executeTask);
Runnable closeTask = mock(Runnable.class);
executor.close(closeTask);
verify(closeTask).run();
reset(closeTask);
executor.close(closeTask);
// Close task should only run once
verify(closeTask, never()).run();
result = executor.execute(executeTask);
// Task should no longer run since service is closed
assertFalse(result.isPresent());
}
@Test
public void concurrent() throws InterruptedException, ExecutionException {
ServiceExecutor executor = new StampedLockServiceExecutor();
ExecutorService service = Executors.newFixedThreadPool(2);
try {
CountDownLatch executeLatch = new CountDownLatch(1);
CountDownLatch stopLatch = new CountDownLatch(1);
Runnable executeTask = () -> {
try {
executeLatch.countDown();
stopLatch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
Future<?> executeFuture = service.submit(() -> executor.execute(executeTask));
executeLatch.await();
Runnable closeTask = mock(Runnable.class);
Future<?> closeFuture = service.submit(() -> executor.close(closeTask));
Thread.yield();
// Verify that stop is blocked
verify(closeTask, never()).run();
stopLatch.countDown();
executeFuture.get();
closeFuture.get();
// Verify close task was invoked, now that execute task is complete
verify(closeTask).run();
} finally {
service.shutdownNow();
}
}
}
| 7,068
| 28.701681
| 90
|
java
|
null |
wildfly-main/clustering/ee/cache/src/test/java/org/wildfly/clustering/ee/cache/retry/RetryingInvokerTestCase.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.ee.cache.retry;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.time.Duration;
import org.junit.Test;
import org.wildfly.clustering.ee.Invoker;
import org.wildfly.common.function.ExceptionRunnable;
import org.wildfly.common.function.ExceptionSupplier;
/**
* @author Paul Ferraro
*/
public class RetryingInvokerTestCase {
@Test
public void testSupplier() throws Exception {
Exception[] exceptions = new Exception[3];
for (int i = 0; i < exceptions.length; ++i) {
exceptions[i] = new Exception();
}
Object expected = new Object();
ExceptionSupplier<Object, Exception> action = mock(ExceptionSupplier.class);
Invoker invoker = new RetryingInvoker(Duration.ZERO, Duration.ofMillis(1));
when(action.get()).thenReturn(expected);
Object result = invoker.invoke(action);
assertSame(expected, result);
when(action.get()).thenThrow(exceptions[0]).thenReturn(expected);
result = invoker.invoke(action);
assertSame(expected, result);
when(action.get()).thenThrow(exceptions[0], exceptions[1]).thenReturn(expected);
result = invoker.invoke(action);
assertSame(expected, result);
when(action.get()).thenThrow(exceptions).thenReturn(expected);
try {
result = invoker.invoke(action);
fail("Expected exception");
} catch (Exception e) {
assertSame(exceptions[2], e);
}
}
@Test
public void testRunnable() throws Exception {
Exception[] exceptions = new Exception[3];
for (int i = 0; i < exceptions.length; ++i) {
exceptions[i] = new Exception();
}
ExceptionRunnable<Exception> action = mock(ExceptionRunnable.class);
doNothing().when(action).run();
Invoker invoker = new RetryingInvoker(Duration.ZERO, Duration.ZERO);
invoker.invoke(action);
doThrow(exceptions[0]).doNothing().when(action).run();
invoker.invoke(action);
doThrow(exceptions[0], exceptions[1]).doNothing().when(action).run();
invoker.invoke(action);
doThrow(exceptions).doNothing().when(action).run();
try {
invoker.invoke(action);
fail("Expected exception");
} catch (Exception e) {
assertSame(exceptions[2], e);
}
}
}
| 3,475
| 31.185185
| 88
|
java
|
null |
wildfly-main/clustering/ee/cache/src/test/java/org/wildfly/clustering/ee/cache/tx/TransactionalBatcherTestCase.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.ee.cache.tx;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.junit.After;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.wildfly.clustering.ee.Batch;
import org.wildfly.clustering.ee.BatchContext;
import org.wildfly.clustering.ee.Batcher;
/**
* Unit test for {@link InfinispanBatcher}.
* @author Paul Ferraro
*/
public class TransactionalBatcherTestCase {
private final TransactionManager tm = mock(TransactionManager.class);
private final Batcher<TransactionBatch> batcher = new TransactionalBatcher<>(this.tm, RuntimeException::new);
@After
public void destroy() {
TransactionalBatcher.setCurrentBatch(null);
}
@Test
public void createExistingActiveBatch() throws Exception {
TransactionBatch existingBatch = mock(TransactionBatch.class);
TransactionalBatcher.setCurrentBatch(existingBatch);
when(existingBatch.getState()).thenReturn(Batch.State.ACTIVE);
when(existingBatch.interpose()).thenReturn(existingBatch);
TransactionBatch result = this.batcher.createBatch();
verify(existingBatch).interpose();
verifyNoInteractions(this.tm);
assertSame(existingBatch, result);
}
@Test
public void createExistingClosedBatch() throws Exception {
TransactionBatch existingBatch = mock(TransactionBatch.class);
Transaction tx = mock(Transaction.class);
ArgumentCaptor<Synchronization> capturedSync = ArgumentCaptor.forClass(Synchronization.class);
TransactionalBatcher.setCurrentBatch(existingBatch);
when(existingBatch.getState()).thenReturn(Batch.State.CLOSED);
when(this.tm.getTransaction()).thenReturn(tx);
try (TransactionBatch batch = this.batcher.createBatch()) {
verify(this.tm).begin();
verify(tx).registerSynchronization(capturedSync.capture());
assertSame(tx, batch.getTransaction());
assertSame(batch, TransactionalBatcher.getCurrentBatch());
} finally {
capturedSync.getValue().afterCompletion(Status.STATUS_COMMITTED);
}
verify(tx).commit();
assertNull(TransactionalBatcher.getCurrentBatch());
}
@Test
public void createBatchClose() throws Exception {
Transaction tx = mock(Transaction.class);
ArgumentCaptor<Synchronization> capturedSync = ArgumentCaptor.forClass(Synchronization.class);
when(this.tm.getTransaction()).thenReturn(tx);
try (TransactionBatch batch = this.batcher.createBatch()) {
verify(this.tm).begin();
verify(tx).registerSynchronization(capturedSync.capture());
assertSame(tx, batch.getTransaction());
} finally {
capturedSync.getValue().afterCompletion(Status.STATUS_COMMITTED);
}
verify(tx).commit();
assertNull(TransactionalBatcher.getCurrentBatch());
}
@Test
public void createBatchDiscard() throws Exception {
Transaction tx = mock(Transaction.class);
ArgumentCaptor<Synchronization> capturedSync = ArgumentCaptor.forClass(Synchronization.class);
when(this.tm.getTransaction()).thenReturn(tx);
try (TransactionBatch batch = this.batcher.createBatch()) {
verify(this.tm).begin();
verify(tx).registerSynchronization(capturedSync.capture());
assertSame(tx, batch.getTransaction());
batch.discard();
} finally {
capturedSync.getValue().afterCompletion(Status.STATUS_ROLLEDBACK);
}
verify(tx, never()).commit();
verify(tx).rollback();
assertNull(TransactionalBatcher.getCurrentBatch());
}
@Test
public void createNestedBatchClose() throws Exception {
Transaction tx = mock(Transaction.class);
ArgumentCaptor<Synchronization> capturedSync = ArgumentCaptor.forClass(Synchronization.class);
when(this.tm.getTransaction()).thenReturn(tx);
try (TransactionBatch outerBatch = this.batcher.createBatch()) {
verify(this.tm).begin();
verify(tx).registerSynchronization(capturedSync.capture());
reset(this.tm);
assertSame(tx, outerBatch.getTransaction());
when(this.tm.getTransaction()).thenReturn(tx);
try (TransactionBatch innerBatch = this.batcher.createBatch()) {
verify(this.tm, never()).begin();
verify(this.tm, never()).suspend();
}
verify(tx, never()).rollback();
verify(tx, never()).commit();
} finally {
capturedSync.getValue().afterCompletion(Status.STATUS_COMMITTED);
}
verify(tx, never()).rollback();
verify(tx).commit();
assertNull(TransactionalBatcher.getCurrentBatch());
}
@Test
public void createNestedBatchDiscard() throws Exception {
Transaction tx = mock(Transaction.class);
ArgumentCaptor<Synchronization> capturedSync = ArgumentCaptor.forClass(Synchronization.class);
when(this.tm.getTransaction()).thenReturn(tx);
try (TransactionBatch outerBatch = this.batcher.createBatch()) {
verify(this.tm).begin();
verify(tx).registerSynchronization(capturedSync.capture());
reset(this.tm);
assertSame(tx, outerBatch.getTransaction());
when(tx.getStatus()).thenReturn(Status.STATUS_ACTIVE);
when(this.tm.getTransaction()).thenReturn(tx);
try (TransactionBatch innerBatch = this.batcher.createBatch()) {
verify(this.tm, never()).begin();
innerBatch.discard();
}
verify(tx, never()).commit();
verify(tx, never()).rollback();
} finally {
capturedSync.getValue().afterCompletion(Status.STATUS_ROLLEDBACK);
}
verify(tx).rollback();
verify(tx, never()).commit();
assertNull(TransactionalBatcher.getCurrentBatch());
}
@SuppressWarnings("resource")
@Test
public void createOverlappingBatchClose() throws Exception {
Transaction tx = mock(Transaction.class);
ArgumentCaptor<Synchronization> capturedSync = ArgumentCaptor.forClass(Synchronization.class);
when(this.tm.getTransaction()).thenReturn(tx);
TransactionBatch batch = this.batcher.createBatch();
verify(this.tm).begin();
verify(tx).registerSynchronization(capturedSync.capture());
reset(this.tm);
try {
assertSame(tx, batch.getTransaction());
when(this.tm.getTransaction()).thenReturn(tx);
when(tx.getStatus()).thenReturn(Status.STATUS_ACTIVE);
try (TransactionBatch innerBatch = this.batcher.createBatch()) {
verify(this.tm, never()).begin();
batch.close();
verify(tx, never()).rollback();
verify(tx, never()).commit();
}
} finally {
capturedSync.getValue().afterCompletion(Status.STATUS_COMMITTED);
}
verify(tx, never()).rollback();
verify(tx).commit();
assertNull(TransactionalBatcher.getCurrentBatch());
}
@SuppressWarnings("resource")
@Test
public void createOverlappingBatchDiscard() throws Exception {
Transaction tx = mock(Transaction.class);
ArgumentCaptor<Synchronization> capturedSync = ArgumentCaptor.forClass(Synchronization.class);
when(this.tm.getTransaction()).thenReturn(tx);
TransactionBatch batch = this.batcher.createBatch();
verify(this.tm).begin();
verify(tx).registerSynchronization(capturedSync.capture());
reset(this.tm);
try {
assertSame(tx, batch.getTransaction());
when(this.tm.getTransaction()).thenReturn(tx);
when(tx.getStatus()).thenReturn(Status.STATUS_ACTIVE);
try (TransactionBatch innerBatch = this.batcher.createBatch()) {
verify(this.tm, never()).begin();
innerBatch.discard();
batch.close();
verify(tx, never()).commit();
verify(tx, never()).rollback();
}
} finally {
capturedSync.getValue().afterCompletion(Status.STATUS_ROLLEDBACK);
}
verify(tx).rollback();
verify(tx, never()).commit();
assertNull(TransactionalBatcher.getCurrentBatch());
}
@Test
public void resumeNullBatch() throws Exception {
TransactionBatch batch = mock(TransactionBatch.class);
TransactionalBatcher.setCurrentBatch(batch);
try (BatchContext context = this.batcher.resumeBatch(null)) {
verifyNoInteractions(this.tm);
assertNull(TransactionalBatcher.getCurrentBatch());
}
verifyNoInteractions(this.tm);
assertSame(batch, TransactionalBatcher.getCurrentBatch());
}
@Test
public void resumeNonTxBatch() throws Exception {
TransactionBatch existingBatch = mock(TransactionBatch.class);
TransactionalBatcher.setCurrentBatch(existingBatch);
TransactionBatch batch = mock(TransactionBatch.class);
try (BatchContext context = this.batcher.resumeBatch(batch)) {
verifyNoInteractions(this.tm);
assertSame(batch, TransactionalBatcher.getCurrentBatch());
}
verifyNoInteractions(this.tm);
assertSame(existingBatch, TransactionalBatcher.getCurrentBatch());
}
@Test
public void resumeBatch() throws Exception {
TransactionBatch batch = mock(TransactionBatch.class);
Transaction tx = mock(Transaction.class);
when(batch.getTransaction()).thenReturn(tx);
try (BatchContext context = this.batcher.resumeBatch(batch)) {
verify(this.tm, never()).suspend();
verify(this.tm).resume(tx);
reset(this.tm);
assertSame(batch, TransactionalBatcher.getCurrentBatch());
}
verify(this.tm).suspend();
verify(this.tm, never()).resume(any());
assertNull(TransactionalBatcher.getCurrentBatch());
}
@Test
public void resumeBatchExisting() throws Exception {
TransactionBatch existingBatch = mock(TransactionBatch.class);
Transaction existingTx = mock(Transaction.class);
TransactionalBatcher.setCurrentBatch(existingBatch);
TransactionBatch batch = mock(TransactionBatch.class);
Transaction tx = mock(Transaction.class);
when(existingBatch.getTransaction()).thenReturn(existingTx);
when(batch.getTransaction()).thenReturn(tx);
when(this.tm.suspend()).thenReturn(existingTx);
try (BatchContext context = this.batcher.resumeBatch(batch)) {
verify(this.tm).resume(tx);
reset(this.tm);
assertSame(batch, TransactionalBatcher.getCurrentBatch());
when(this.tm.suspend()).thenReturn(tx);
}
verify(this.tm).resume(existingTx);
assertSame(existingBatch, TransactionalBatcher.getCurrentBatch());
}
@Test
public void suspendBatch() throws Exception {
TransactionBatch batch = mock(TransactionBatch.class);
TransactionalBatcher.setCurrentBatch(batch);
TransactionBatch result = this.batcher.suspendBatch();
verify(this.tm).suspend();
assertSame(batch, result);
assertNull(TransactionalBatcher.getCurrentBatch());
}
@Test
public void suspendNoBatch() throws Exception {
TransactionBatch result = this.batcher.suspendBatch();
verify(this.tm, never()).suspend();
assertNull(result);
}
}
| 12,996
| 33.02356
| 113
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/CacheConfiguration.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.ee.cache;
import java.util.Map;
import org.wildfly.clustering.ee.Batcher;
import org.wildfly.clustering.ee.cache.tx.TransactionBatch;
/**
* @author Paul Ferraro
*/
public interface CacheConfiguration {
<K, V> Map<K, V> getCache();
CacheProperties getCacheProperties();
Batcher<TransactionBatch> getBatcher();
}
| 1,386
| 32.829268
| 70
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/IdentifierFactory.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.ee.cache;
import java.util.function.Supplier;
import org.wildfly.clustering.ee.Restartable;
/**
* Factory for creating unique identifiers suitable for use by the local cluster member.
* @author Paul Ferraro
* @param <I> the identifier type
*/
public interface IdentifierFactory<I> extends Restartable, Supplier<I> {
}
| 1,379
| 38.428571
| 88
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/CacheProperties.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.ee.cache;
/**
* Exposes a cache configuration as simple high-level properties.
* @author Paul Ferraro
*/
public interface CacheProperties {
/**
* Indicates whether the associated cache requires eager locking for cache reads.
* @return true, if the cache client should perform reads under lock, false otherwise
*/
boolean isLockOnRead();
/**
* Indicates whether the associated cache uses eager locking for cache writes.
* @return true, if the cache client should perform writes under lock, false otherwise
*/
boolean isLockOnWrite();
/**
* Indicates whether the mode of this cache requires marshalling of cache values
* @return true, if cache values need to be marshallable, false otherwise.
*/
boolean isMarshalling();
/**
* Indicates whether cache operations should assume immediate marshalling/unmarshalling of the value.
* @return true, if the cache client will need to handle passivation/activation notifications on read/write, false otherwise
*/
boolean isPersistent();
/**
* Indicates whether the cache is transactional.
* @return true, if this cache is transactional, false otherwise.
*/
boolean isTransactional();
}
| 2,302
| 37.383333
| 128
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/SimpleManager.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.ee.cache;
import java.util.AbstractMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import org.wildfly.clustering.ee.Manager;
/**
* Manages creation and destruction of objects not sharable across threads.
* @author Paul Ferraro
* @param <K> the key type
* @param <V> the type of the managed value
*/
public class SimpleManager<K, V> implements Manager<K, V> {
private final Consumer<V> createTask;
private final Consumer<V> closeTask;
public SimpleManager(Consumer<V> createTask, Consumer<V> closeTask) {
this.createTask = createTask;
this.closeTask = closeTask;
}
@Override
public V apply(K key, Function<Runnable, V> factory) {
Map.Entry<K, V> entry = new AbstractMap.SimpleEntry<>(key, null);
Consumer<V> closeTask = this.closeTask;
V value = factory.apply(new Runnable() {
@Override
public void run() {
closeTask.accept(entry.getValue());
}
});
if (value != null) {
entry.setValue(value);
this.createTask.accept(value);
}
return value;
}
}
| 2,236
| 33.415385
| 75
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/ConcurrentManager.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.ee.cache;
import java.util.AbstractMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import org.wildfly.clustering.ee.Manager;
/**
* Manages creation and destruction of values to be shared across threads.
* @author Paul Ferraro
* @param <K> the key type
* @param <V> the type of the managed value
*/
public class ConcurrentManager<K, V> implements Manager<K, V> {
private final Map<K, Map.Entry<Integer, AtomicReference<V>>> objects = new ConcurrentHashMap<>();
private final BiFunction<K, Map.Entry<Integer, AtomicReference<V>>, Map.Entry<Integer, AtomicReference<V>>> addFunction = new BiFunction<>() {
@Override
public Map.Entry<Integer, AtomicReference<V>> apply(K id, Map.Entry<Integer, AtomicReference<V>> entry) {
int count = (entry != null) ? entry.getKey() + 1 : 0;
AtomicReference<V> reference = (entry != null) ? entry.getValue() : new AtomicReference<>();
return new AbstractMap.SimpleImmutableEntry<>(count, reference);
}
};
private final Consumer<V> createTask;
private final BiFunction<K, Map.Entry<Integer, AtomicReference<V>>, Map.Entry<Integer, AtomicReference<V>>> removeFunction;
public ConcurrentManager(Consumer<V> createTask, Consumer<V> closeTask) {
this.createTask = createTask;
this.removeFunction = new BiFunction<>() {
@Override
public Map.Entry<Integer, AtomicReference<V>> apply(K key, Map.Entry<Integer, AtomicReference<V>> entry) {
// Entry can be null if entry was already removed, i.e. managed object was already closed
int count = (entry != null) ? entry.getKey() : 0;
AtomicReference<V> reference = (entry != null) ? entry.getValue() : null;
if (count == 0) {
V value = (reference != null) ? reference.get() : null;
if (value != null) {
closeTask.accept(value);
}
// Returning null will remove the map entry
return null;
}
return new AbstractMap.SimpleImmutableEntry<>(count - 1, reference);
}
};
}
@Override
public V apply(K key, Function<Runnable, V> factory) {
Map.Entry<Integer, AtomicReference<V>> entry = this.objects.compute(key, this.addFunction);
AtomicReference<V> reference = entry.getValue();
if (reference.get() == null) {
synchronized (reference) {
if (reference.get() == null) {
Map<K, Map.Entry<Integer, AtomicReference<V>>> objects = this.objects;
BiFunction<K, Map.Entry<Integer, AtomicReference<V>>, Map.Entry<Integer, AtomicReference<V>>> removeFunction = this.removeFunction;
Runnable closeTask = new Runnable() {
@Override
public void run() {
objects.compute(key, removeFunction);
}
};
V value = factory.apply(closeTask);
if (value != null) {
this.createTask.accept(value);
reference.set(value);
} else {
closeTask.run();
}
}
}
}
return reference.get();
}
}
| 4,676
| 43.971154
| 151
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/SimpleIdentifierFactory.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.ee.cache;
import java.util.function.Supplier;
/**
* Simple {@link IdentifierFactory} that delegates to a supplier.
* @author Paul Ferraro
*/
public class SimpleIdentifierFactory<I> implements IdentifierFactory<I> {
private final Supplier<I> factory;
public SimpleIdentifierFactory(Supplier<I> factory) {
this.factory = factory;
}
@Override
public I get() {
return this.factory.get();
}
@Override
public void start() {
// Do nothing
}
@Override
public void stop() {
// Do nothing
}
}
| 1,628
| 29.166667
| 73
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/CollectionFunction.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.ee.cache.function;
import java.util.Collection;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
/**
* Function that operates on a collection.
* @author Paul Ferraro
* @param <V> the collection element type
* @param <C> the collection type
*/
public abstract class CollectionFunction<V, C extends Collection<V>> extends AbstractFunction<V, C> {
public CollectionFunction(V operand, UnaryOperator<C> copier, Supplier<C> factory) {
super(operand, copier, factory, Collection::isEmpty);
}
}
| 1,595
| 37.926829
| 101
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/MapRemoveFunction.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.ee.cache.function;
import java.util.Collections;
import java.util.Map;
/**
* Function that removes an entry from a map.
* @author Paul Ferraro
* @param <K> the map key type
* @param <V> the map value type
*/
public class MapRemoveFunction<K, V> extends MapFunction<K, V, K> {
public MapRemoveFunction(K operand, Operations<Map<K, V>> operations) {
super(operand, operations, Collections::emptyMap);
}
@Override
public void accept(Map<K, V> map, K key) {
map.remove(key);
}
}
| 1,575
| 34.022222
| 75
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/CopyOnWriteSetOperations.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.ee.cache.function;
import java.util.HashSet;
import java.util.Set;
/**
* Defines operations for creating and copying a non-concurrent set.
* A non-concurrent set must perform writes against a copy, thus the underlying set need not be concurrent.
* @author Paul Ferraro
* @param <V> the set element type
*/
public class CopyOnWriteSetOperations<V> implements Operations<Set<V>> {
@Override
public Set<V> apply(Set<V> set) {
return new HashSet<>(set);
}
@Override
public Set<V> get() {
return new HashSet<>();
}
}
| 1,616
| 34.152174
| 107
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/CopyOnWriteSetAddFunction.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.ee.cache.function;
/**
* Function that adds an item to a set within a transactional cache.
* @author Paul Ferraro
* @param <V> the set element type
*/
public class CopyOnWriteSetAddFunction<V> extends SetAddFunction<V> {
public CopyOnWriteSetAddFunction(V value) {
super(value, new CopyOnWriteSetOperations<>());
}
}
| 1,394
| 37.75
| 70
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/CopyOnWriteSetRemoveFunction.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.ee.cache.function;
/**
* Function that removes an item from a set within a transactional cache.
* @author Paul Ferraro
* @param <V> the set element type
*/
public class CopyOnWriteSetRemoveFunction<V> extends SetRemoveFunction<V> {
public CopyOnWriteSetRemoveFunction(V value) {
super(value, new CopyOnWriteSetOperations<>());
}
}
| 1,408
| 38.138889
| 75
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/Operations.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.ee.cache.function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
/**
* Defines operations for creating and copying an operable object.
* @author Paul Ferraro
* @param <T> the operable object type
*/
public interface Operations<T> extends UnaryOperator<T>, Supplier<T> {
}
| 1,365
| 36.944444
| 70
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/CopyOnWriteMapRemoveFunction.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.ee.cache.function;
/**
* Function that removes an entry from a map within a transactional cache.
* @author Paul Ferraro
* @param <K> the map key type
* @param <V> the map value type
*/
public class CopyOnWriteMapRemoveFunction<K, V> extends MapRemoveFunction<K, V> {
public CopyOnWriteMapRemoveFunction(K key) {
super(key, new CopyOnWriteMapOperations<>());
}
}
| 1,440
| 37.945946
| 81
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/CopyOnWriteMapOperations.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.ee.cache.function;
import java.util.HashMap;
import java.util.Map;
/**
* Defines operations for creating and copying a non-concurrent map.
* A non-concurrent map must perform writes against a copy, thus the underlying map need not be concurrent.
* @author Paul Ferraro
* @param <K> the map key type
* @param <V> the map value type
*/
public class CopyOnWriteMapOperations<K, V> implements Operations<Map<K, V>> {
@Override
public Map<K, V> apply(Map<K, V> map) {
return new HashMap<>(map);
}
@Override
public Map<K, V> get() {
return new HashMap<>();
}
}
| 1,660
| 34.340426
| 107
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/ConcurrentMapOperations.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.ee.cache.function;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Defines operations for creating and copying a concurrent map.
* A concurrent map can perform writes against the map directly, thus an explicitly copy is unnecessary.
* @author Paul Ferraro
* @param <K> the map key type
* @param <V> the map value type
*/
public class ConcurrentMapOperations<K, V> implements Operations<Map<K, V>> {
@Override
public Map<K, V> apply(Map<K, V> map) {
return map;
}
@Override
public Map<K, V> get() {
return new ConcurrentHashMap<>();
}
}
| 1,668
| 34.510638
| 104
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/ConcurrentMapPutFunction.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.ee.cache.function;
import java.util.AbstractMap;
import java.util.Map;
/**
* Function that puts an entry into a map within a non-transactional cache.
* @author Paul Ferraro
* @param <K> the map key type
* @param <V> the map value type
*/
public class ConcurrentMapPutFunction<K, V> extends MapPutFunction<K, V> {
public ConcurrentMapPutFunction(K key, V value) {
this(new AbstractMap.SimpleImmutableEntry<>(key, value));
}
public ConcurrentMapPutFunction(Map.Entry<K, V> operand) {
super(operand, new ConcurrentMapOperations<>());
}
}
| 1,631
| 36.090909
| 75
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/ConcurrentSetOperations.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.ee.cache.function;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Defines operations for creating and copying a concurrent set.
* A concurrent set can perform writes against the set directly, thus an explicitly copy is unnecessary.
* @author Paul Ferraro
* @param <V> the set element type
*/
public class ConcurrentSetOperations<V> implements Operations<Set<V>> {
@Override
public Set<V> apply(Set<V> set) {
return set;
}
@Override
public Set<V> get() {
return new CopyOnWriteArraySet<>();
}
}
| 1,628
| 34.413043
| 104
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/CollectionAddFunction.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.ee.cache.function;
import java.util.Collection;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
/**
* Function that adds an item to a collection.
* @author Paul Ferraro
* @param <V> the collection element type
* @param <C> the collection type
*/
public class CollectionAddFunction<V, C extends Collection<V>> extends CollectionFunction<V, C> {
public CollectionAddFunction(V value, UnaryOperator<C> copier, Supplier<C> factory) {
super(value, copier, factory);
}
@Override
public void accept(C collection, V value) {
collection.add(value);
}
}
| 1,673
| 35.391304
| 97
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/CollectionRemoveFunction.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.ee.cache.function;
import java.util.Collection;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
/**
* Function that removes an item from a collection.
* @author Paul Ferraro
* @param <V> the collection element type
* @param <C> the collection type
*/
public class CollectionRemoveFunction<V, C extends Collection<V>> extends CollectionFunction<V, C> {
public CollectionRemoveFunction(V value, UnaryOperator<C> copier, Supplier<C> factory) {
super(value, copier, factory);
}
@Override
public void accept(C collection, V value) {
collection.remove(value);
}
}
| 1,687
| 35.695652
| 100
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/ConcurrentSetAddFunction.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.ee.cache.function;
/**
* Function that adds an item to a set within a non-transactional cache.
* @author Paul Ferraro
* @param <V> the set element type
*/
public class ConcurrentSetAddFunction<V> extends SetAddFunction<V> {
public ConcurrentSetAddFunction(V value) {
super(value, new ConcurrentSetOperations<>());
}
}
| 1,395
| 37.777778
| 72
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/SetRemoveFunction.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.ee.cache.function;
import java.util.Collections;
import java.util.Set;
/**
* Function that removes an item from a set.
* @author Paul Ferraro
* @param <V> the set element type
*/
public class SetRemoveFunction<V> extends CollectionRemoveFunction<V, Set<V>> {
public SetRemoveFunction(V value, Operations<Set<V>> operations) {
super(value, operations, Collections::emptySet);
}
}
| 1,457
| 36.384615
| 79
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/CopyOnWriteMapPutFunction.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.ee.cache.function;
import java.util.AbstractMap;
import java.util.Map;
/**
* Function that puts an entry into a map within a transactional cache.
* @author Paul Ferraro
* @param <K> the map key type
* @param <V> the map value type
*/
public class CopyOnWriteMapPutFunction<K, V> extends MapPutFunction<K, V> {
public CopyOnWriteMapPutFunction(K key, V value) {
this(new AbstractMap.SimpleImmutableEntry<>(key, value));
}
public CopyOnWriteMapPutFunction(Map.Entry<K, V> operand) {
super(operand, new CopyOnWriteMapOperations<>());
}
}
| 1,631
| 36.090909
| 75
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/SetAddFunction.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.ee.cache.function;
import java.util.Set;
/**
* Function that adds an item to a set.
* @author Paul Ferraro
* @param <V> the set element type
*/
public class SetAddFunction<V> extends CollectionAddFunction<V, Set<V>> {
public SetAddFunction(V value, Operations<Set<V>> operations) {
super(value, operations, operations);
}
}
| 1,402
| 35.921053
| 73
|
java
|
null |
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/MapFunction.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.ee.cache.function;
import java.util.Map;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
/**
* Function that operates on a map.
* @author Paul Ferraro
* @param <K> the map key type
* @param <V> the map value type
*/
public abstract class MapFunction<K, V, T> extends AbstractFunction<T, Map<K, V>> {
public MapFunction(T operand, UnaryOperator<Map<K, V>> copier, Supplier<Map<K, V>> factory) {
super(operand, copier, factory, Map::isEmpty);
}
}
| 1,553
| 36.902439
| 97
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.