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 |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/LifecycleCallbacks.java
|
package org.infinispan.server.core;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.Transcoder;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.encoding.impl.TwoStepTranscoder;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.factories.annotations.InfinispanModule;
import org.infinispan.lifecycle.ModuleLifecycle;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.core.EncoderRegistry;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.server.core.dataconversion.JsonTranscoder;
import org.infinispan.server.core.dataconversion.XMLTranscoder;
/**
* Server module lifecycle callbacks
*
* @author Galder Zamarreño
* @since 5.0
*/
@InfinispanModule(name = "server-core", requiredModules = "core", optionalModules = "jboss-marshalling")
public class LifecycleCallbacks implements ModuleLifecycle {
@Override
public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) {
SerializationContextRegistry ctxRegistry = gcr.getComponent(SerializationContextRegistry.class);
ctxRegistry.addContextInitializer(SerializationContextRegistry.MarshallerType.PERSISTENCE, new PersistenceContextInitializerImpl());
ClassAllowList classAllowList = gcr.getComponent(EmbeddedCacheManager.class).getClassAllowList();
ClassLoader classLoader = globalConfiguration.classLoader();
EncoderRegistry encoderRegistry = gcr.getComponent(EncoderRegistry.class);
JsonTranscoder jsonTranscoder = new JsonTranscoder(classLoader, classAllowList);
encoderRegistry.registerTranscoder(jsonTranscoder);
registerXmlTranscoder(encoderRegistry, classLoader, classAllowList);
// Allow transcoding between JBoss Marshalling and JSON
if (encoderRegistry.isConversionSupported(MediaType.APPLICATION_OBJECT, MediaType.APPLICATION_JBOSS_MARSHALLING)) {
Transcoder jbossMarshallingTranscoder =
encoderRegistry.getTranscoder(MediaType.APPLICATION_OBJECT, MediaType.APPLICATION_JBOSS_MARSHALLING);
encoderRegistry.registerTranscoder(new TwoStepTranscoder(jbossMarshallingTranscoder, jsonTranscoder));
}
}
// This method is here for Quarkus to replace. If this method is moved or modified Infinispan Quarkus will also
// be required to be updated
private void registerXmlTranscoder(EncoderRegistry encoderRegistry, ClassLoader classLoader, ClassAllowList classAllowList) {
encoderRegistry.registerTranscoder(new XMLTranscoder(classLoader, classAllowList));
}
}
| 2,755
| 50.037037
| 138
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/ServerManagement.java
|
package org.infinispan.server.core;
import java.nio.file.Path;
import java.security.Principal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import javax.sql.DataSource;
import org.infinispan.commons.configuration.io.ConfigurationWriter;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.tasks.TaskManager;
/**
* @since 10.0
*/
public interface ServerManagement {
ComponentStatus getStatus();
void serializeConfiguration(ConfigurationWriter writer);
void serverStop(List<String> servers);
void clusterStop();
void containerStop();
/**
* @deprecated Multiple Cache Managers are not supported in the server
*/
@Deprecated
default Set<String> cacheManagerNames() {
return Collections.singleton(getCacheManager().getName());
}
/**
* @deprecated Multiple Cache Managers are not supported in the server. Use {@link #getCacheManager()} instead.
*/
@Deprecated
default DefaultCacheManager getCacheManager(String name) {
DefaultCacheManager cm = getCacheManager();
return cm.getName().equals(name) ? cm : null;
}
DefaultCacheManager getCacheManager();
ServerStateManager getServerStateManager();
Map<String, String> getLoginConfiguration(ProtocolServer protocolServer);
Map<String, ProtocolServer> getProtocolServers();
TaskManager getTaskManager();
CompletionStage<Path> getServerReport();
BackupManager getBackupManager();
Map<String, DataSource> getDataSources();
Path getServerDataPath();
Map<String, List<Principal>> getPrincipalList();
CompletionStage<Void> flushSecurityCaches();
}
| 1,778
| 23.708333
| 114
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/QueryFacade.java
|
package org.infinispan.server.core;
import org.infinispan.AdvancedCache;
/**
* Query facade SPI. This is not meant to be implemented by regular users. At most one implmentation can exist in
* server's classpath.
*
* @author Galder Zamarreño
* @author wburns
* @since 9.0
*/
public interface QueryFacade {
/**
* Execute a query against a cache.
*
* @param cache the cache to execute the query
* @param query the query, serialized using protobuf
* @return the results, serialized using protobuf
*/
byte[] query(AdvancedCache<?, ?> cache, byte[] query);
}
| 593
| 23.75
| 113
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/BackupManager.java
|
package org.infinispan.server.core;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* Handles all tasks related to the creation/restoration of server backups.
*
* @author Ryan Emerson
* @since 12.0
*/
@Scope(Scopes.GLOBAL)
public interface BackupManager {
/**
* An enum representing the current state of a Backup operation.
*/
enum Status {
COMPLETE,
FAILED,
IN_PROGRESS,
NOT_FOUND
}
/**
* Performs initialisation of all resources required by the implementation before backup files can be created or
* restored.
*/
void init() throws IOException;
/**
* @return the names of all backups.
*/
Set<String> getBackupNames();
/**
* Return the current {@link Status} of a Backup request.
*
* @param name the name of the backup.
* @return the {@link Status} of the backup.
*/
Status getBackupStatus(String name);
/**
* Returns the {@link Path} of a backup file if it is complete.
*
* @param name the name of the backup.
* @return the {@link Path} of the created backup file if {@link Status#COMPLETE}, otherwise null.
*/
Path getBackupLocation(String name);
/**
* Remove the created backup file from the server. When it's possible to remove a backup file immediately, then a
* {@link Status#COMPLETE} is returned. However, if a backup operation is currently in progress, then the removal is
* attempted once the backup has completed and {@link Status#IN_PROGRESS} is returned. Finally, {@link
* Status#NOT_FOUND} is returned if no backup exists with the specified name.
*
* @param name the name of the backup.
* @return a {@link CompletionStage} that returns a {@link Status} when complete to indicate what course of action
* was taken.
*/
CompletionStage<Status> removeBackup(String name);
/**
* Create a backup of all containers configured on the server, including all available resources.
*
* @param name the name of the backup.
* @param workingDir a path used as the working directory for creating the backup contents and storing the final
* backup. If null, then the default location is used.
* @return a {@link CompletionStage} that on completion returns the {@link Path} to the backup file that will be
* created.
*/
CompletionStage<Path> create(String name, Path workingDir);
/**
* Create a backup of the specified containers, including the resources defined in the provided {@link Resources}
* object.
*
* @param name the name of the backup.
* @param params a map of container names and an associated {@link Resources} instance.
* @param workingDir a path used as the working directory for creating the backup contents and storing the final *
* backup. If null, then the default location is used.
* @return a {@link CompletionStage} that on completion returns the {@link Path} to the backup file that will be
* created.
*/
CompletionStage<Path> create(String name, Path workingDir, Map<String, Resources> params);
/**
* Restore content from the provided backup file.
*
* @param name a unique name to identify the restore process
* @param backup a path to the backup file to be restored.
* @return a {@link CompletionStage} that completes when all of the entries in the backup have been restored.
*/
CompletionStage<Void> restore(String name, Path backup);
/**
* Restore content from the provided backup file. The keyset of the provided {@link Map} determines which containers
* are restored from the backup file. Similarly, the {@link Resources} object determines which {@link
* Resources.Type}s are restored.
*
* @param name a unique name to identify the restore request.
* @param backup a path to the backup file to be restored.
* @return a {@link CompletionStage} that completes when all of the entries in the backup have been restored.
*/
CompletionStage<Void> restore(String name, Path backup, Map<String, Resources> params);
/**
* Remove the meta information associated with a restoration. When a restoration is not currently in progress, then a
* {@link Status#COMPLETE} is returned. However, if a restore operation is currently in progress, then the removal is
* attempted once the restore has completed and {@link Status#IN_PROGRESS} is returned. Finally, {@link
* Status#NOT_FOUND} is returned if no restore exists with the specified name.
*
* @param name a unique name to identify the restore request.
* @return a {@link CompletionStage} that returns a {@link Status} when complete to indicate what course of action
* was taken.
*/
CompletionStage<Status> removeRestore(String name);
/**
* Return the current {@link Status} of a Restore request.
*
* @param name a unique name to identify the restore request.
* @return the {@link Status} of the restore.
*/
Status getRestoreStatus(String name);
/**
* @return the names of all restores.
*/
Set<String> getRestoreNames();
/**
* An interface to encapsulate the various arguments required by the {@link BackupManager} in order to
* include/exclude resources from a backup/restore operation.
*/
interface Resources {
enum Type {
CACHES("caches"),
TEMPLATES("templates"),
COUNTERS("counters"),
PROTO_SCHEMAS("proto-schemas"),
TASKS("tasks");
final String name;
Type(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
public static Type fromString(String s) {
for (Type t : Type.values()) {
if (t.name.equalsIgnoreCase(s)) {
return t;
}
}
throw new IllegalArgumentException(String.format("Type with name '%s' does not exist", s));
}
}
/**
* @return the {@link Type} to be included in the backup/restore.
*/
Set<Type> includeTypes();
/**
* @param type the {@link Type} to retrieve the associated resources for.
* @return a {@link Set} of resource names to process.
*/
Set<String> getQualifiedResources(Type type);
}
}
| 6,605
| 34.708108
| 120
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/ProtocolDetector.java
|
package org.infinispan.server.core;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
/**
* @since 15.0
**/
public abstract class ProtocolDetector extends ByteToMessageDecoder {
protected final ProtocolServer<?> server;
protected ProtocolDetector(ProtocolServer<?> server) {
this.server = server;
}
public abstract String getName();
/**
* Removes all handlers in the pipeline after this
*/
protected void trimPipeline(ChannelHandlerContext ctx) {
ChannelHandlerAdapter dummy = new ChannelHandlerAdapter() {};
ctx.pipeline().addAfter(ctx.name(), "dummy", dummy);
ChannelHandler channelHandler = ctx.pipeline().removeLast();
// Remove everything else
while (channelHandler != dummy) {
channelHandler = ctx.pipeline().removeLast();
}
}
}
| 958
| 28.060606
| 69
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/ServerConstants.java
|
package org.infinispan.server.core;
/**
* Server Constant values
*
* @author Tristan Tarrant
* @author wburns
* @since 9.0
*/
public final class ServerConstants {
private ServerConstants() { }
public static final int EXPIRATION_NONE = -1;
public static final int EXPIRATION_DEFAULT = -2;
}
| 306
| 19.466667
| 51
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/ProtocolServer.java
|
package org.infinispan.server.core;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.core.configuration.ProtocolServerConfiguration;
import org.infinispan.server.core.transport.Transport;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.group.ChannelMatcher;
/**
* Represents a protocol compliant server.
*
* @author Galder Zamarreño
* @author wburns
* @since 9.0
*/
public interface ProtocolServer<C extends ProtocolServerConfiguration> {
/**
* Starts the server backed by the given cache manager, with the corresponding configuration. The cache manager is
* expected to be completely initialized and started prior to this call.
*/
void start(C configuration, EmbeddedCacheManager cacheManager);
/**
* Stops the server.
*/
void stop();
/**
* Gets the encoder for this protocol server. The encoder is responsible for writing back common header responses
* back to client. This method can return null if the server has no encoder. You can find an example of the server
* that has no encoder in the Memcached server.
*/
ChannelOutboundHandler getEncoder();
/**
* Gets the decoder for this protocol server. The decoder is responsible for reading client requests.
* This method cannot return null.
*/
ChannelInboundHandler getDecoder();
/**
* Returns the configuration used to start this server
*/
C getConfiguration();
/**
* Returns a pipeline factory
*/
ChannelInitializer<Channel> getInitializer();
/**
* Returns the name of this server
*/
String getName();
/**
* Returns the transport for this server
*/
Transport getTransport();
/**
* Sets the {@link ServerManagement} instance for this protocol server
*/
void setServerManagement(ServerManagement server, boolean adminEndpoint);
/**
* Sets the enclosing {@link ProtocolServer}. Used by the single port server
*/
void setEnclosingProtocolServer(ProtocolServer<?> enclosingProtocolServer);
/**
* Returns the enclosing {@link ProtocolServer}. May be null if this server has none.
*/
ProtocolServer<?> getEnclosingProtocolServer();
/**
* Returns a {@link ChannelMatcher} which matches channels which belong to this protocol server
*/
ChannelMatcher getChannelMatcher();
/**
* Installs a protocol detector on the channel
* @param ch
*/
void installDetector(Channel ch);
}
| 2,622
| 27.51087
| 117
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/MagicByteDetector.java
|
package org.infinispan.server.core;
import java.util.List;
import org.infinispan.server.core.logging.Log;
import org.infinispan.server.core.transport.AccessControlFilter;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
public abstract class MagicByteDetector extends ProtocolDetector {
private final byte magicByte;
protected MagicByteDetector(AbstractProtocolServer<?> server, byte magicByte) {
super(server);
this.magicByte = magicByte;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
// We need to only see the Magic byte
if (in.readableBytes() < 1) {
// noop, wait for further reads
return;
}
byte b = in.getByte(in.readerIndex());
if (b == magicByte) {
// We found the Magic, let's do some pipeline surgery
trimPipeline(ctx);
// Add the protocol server handler
ctx.pipeline().addLast(getInitializer());
Log.SERVER.tracef("Detected %s connection %s", getName(), ctx);
// Make sure to fire registered on the newly installed handlers
ctx.fireChannelRegistered();
// Trigger any protocol-specific rules
ctx.pipeline().fireUserEventTriggered(AccessControlFilter.EVENT);
}
// Remove this
ctx.pipeline().remove(this);
}
protected ChannelInitializer<Channel> getInitializer() {
return server.getInitializer();
}
}
| 1,560
| 31.520833
| 83
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/AbstractProtocolServer.java
|
package org.infinispan.server.core;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import javax.management.ObjectName;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.jmx.CacheManagerJmxRegistration;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.metrics.impl.CacheManagerMetricsRegistration;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.core.configuration.ProtocolServerConfiguration;
import org.infinispan.server.core.logging.Log;
import org.infinispan.server.core.transport.NettyTransport;
import org.infinispan.server.core.utils.ManageableThreadPoolExecutorService;
import org.infinispan.tasks.TaskManager;
import org.infinispan.util.concurrent.BlockingManager;
/**
* A common protocol server dealing with common property parameter validation and assignment and transport lifecycle.
*
* @author Galder Zamarreño
* @author wburns
* @since 4.1
*/
public abstract class AbstractProtocolServer<C extends ProtocolServerConfiguration> implements ProtocolServer<C> {
private static final Log log = LogFactory.getLog(AbstractProtocolServer.class, Log.class);
private final String protocolName;
protected NettyTransport transport;
protected EmbeddedCacheManager cacheManager;
protected C configuration;
protected ServerManagement server;
private ServerStateManager serverStateManager;
private ObjectName transportObjName;
private CacheManagerJmxRegistration jmxRegistration;
private BlockingManager blockingManager;
private ExecutorService executor;
private ManageableThreadPoolExecutorService manageableThreadPoolExecutorService;
private ObjectName executorObjName;
private CacheManagerMetricsRegistration metricsRegistration;
private Set<Object> metricIds;
private ProtocolServer<?> enclosingProtocolServer;
protected boolean adminEndpoint = false;
protected AbstractProtocolServer(String protocolName) {
this.protocolName = protocolName;
}
@Override
public String getName() {
return protocolName;
}
protected void startInternal() {
registerAdminOperationsHandler();
// Start default cache
startCaches();
if (configuration.startTransport())
startTransport();
}
private void registerAdminOperationsHandler() {
if (configuration.adminOperationsHandler() != null) {
TaskManager taskManager = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(TaskManager.class);
if (taskManager != null) {
taskManager.registerTaskEngine(configuration.adminOperationsHandler());
} else {
throw log.cannotRegisterAdminOperationsHandler();
}
}
}
public void setServerManagement(ServerManagement server, boolean adminEndpoint) {
this.server = server;
this.adminEndpoint = adminEndpoint;
}
protected boolean isCacheIgnored(String cache) {
return serverStateManager != null && serverStateManager.isCacheIgnored(cache);
}
public ServerStateManager getServerStateManager() {
return serverStateManager;
}
@Override
public void start(C configuration, EmbeddedCacheManager cacheManager) {
if (log.isDebugEnabled()) {
log.debugf("Starting server with configuration: %s", configuration);
}
this.configuration = configuration;
this.cacheManager = cacheManager;
BasicComponentRegistry bcr = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(BasicComponentRegistry.class.getName());
ComponentRef<ServerStateManager> stateManagerComponentRef = bcr.getComponent(ServerStateManager.class);
if (stateManagerComponentRef != null) {
serverStateManager = stateManagerComponentRef.running();
}
bcr.replaceComponent(getQualifiedName(), this, false);
blockingManager = bcr.getComponent(BlockingManager.class).running();
executor = bcr.getComponent(KnownComponentNames.BLOCKING_EXECUTOR, ExecutorService.class).running();
manageableThreadPoolExecutorService = new ManageableThreadPoolExecutorService(executor);
try {
startInternal();
} catch (RuntimeException t) {
stop();
throw t;
}
}
protected void startTransport() {
log.debugf("Starting Netty transport for %s on %s:%s", configuration.name(), configuration.host(), configuration.port());
InetSocketAddress address = new InetSocketAddress(configuration.host(), configuration.port());
transport = new NettyTransport(address, configuration, getQualifiedName(), cacheManager);
transport.initializeHandler(getInitializer());
// Register transport and worker MBeans regardless
registerServerMBeans();
try {
transport.start();
} catch (Throwable re) {
try {
unregisterServerMBeans();
} catch (Exception e) {
throw new CacheException(e);
}
throw re;
}
registerMetrics();
}
public BlockingManager getBlockingManager() {
return blockingManager;
}
public ExecutorService getExecutor() {
return executor;
}
protected void registerServerMBeans() {
if (cacheManager != null && SecurityActions.getCacheManagerConfiguration(cacheManager).jmx().enabled()) {
jmxRegistration = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(CacheManagerJmxRegistration.class);
String groupName = String.format("type=Server,name=%s-%d", getQualifiedName(), configuration.port());
try {
transportObjName = jmxRegistration.registerExternalMBean(transport, groupName);
if (manageableThreadPoolExecutorService != null) {
executorObjName = jmxRegistration.registerExternalMBean(manageableThreadPoolExecutorService, groupName);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
protected void unregisterServerMBeans() throws Exception {
if (transportObjName != null) {
jmxRegistration.unregisterMBean(transportObjName);
}
if (executorObjName != null) {
jmxRegistration.unregisterMBean(executorObjName);
}
}
protected void registerMetrics() {
if (cacheManager == null) {
return;
}
metricsRegistration = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(CacheManagerMetricsRegistration.class);
if (metricsRegistration.metricsEnabled()) {
String protocol = "server_" + getQualifiedName() + '_' + configuration.port();
metricIds = Collections.synchronizedSet(metricsRegistration.registerExternalMetrics(transport, protocol));
if (manageableThreadPoolExecutorService != null) {
metricIds.addAll(metricsRegistration.registerExternalMetrics(manageableThreadPoolExecutorService, protocol));
}
}
}
protected void unregisterMetrics() {
if (metricIds != null) {
metricsRegistration.unregisterMetrics(metricIds);
metricIds = null;
}
}
public final String getQualifiedName() {
if (configuration == null)
return protocolName;
return protocolName + (configuration.name().length() > 0 ? "-" : "") + configuration.name();
}
@Override
public void stop() {
boolean isDebug = log.isDebugEnabled();
if (isDebug && configuration != null)
log.debugf("Stopping server %s listening at %s:%d", getQualifiedName(), configuration.host(), configuration.port());
if (transport != null)
transport.stop();
try {
unregisterServerMBeans();
} catch (Exception e) {
throw new CacheException(e);
}
unregisterMetrics();
if (isDebug)
log.debugf("Server %s stopped", getQualifiedName());
}
public EmbeddedCacheManager getCacheManager() {
return cacheManager;
}
public String getHost() {
return configuration.host();
}
public Integer getPort() {
if (transport != null) {
return transport.getPort();
}
return configuration.port();
}
@Override
public C getConfiguration() {
return configuration;
}
protected void startCaches() {
// DefaultCacheManager already starts all the defined/persisted/global state caches
// But the default cache may not be defined (e.g. it might be using a wildcard template)
String name = defaultCacheName();
if (name != null) {
log.debugf("Starting default cache: %s", configuration.defaultCacheName());
cacheManager.getCache(name);
} else {
log.debugf("No default cache to start");
}
}
public String defaultCacheName() {
if (configuration.defaultCacheName() != null) {
return configuration.defaultCacheName();
} else {
return SecurityActions.getCacheManagerConfiguration(cacheManager).defaultCacheName().orElse(null);
}
}
public boolean isTransportEnabled() {
return transport != null;
}
@Override
public NettyTransport getTransport() {
return transport;
}
@Override
public void setEnclosingProtocolServer(ProtocolServer<?> enclosingProtocolServer) {
this.enclosingProtocolServer = enclosingProtocolServer;
}
@Override
public ProtocolServer<?> getEnclosingProtocolServer() {
return enclosingProtocolServer;
}
}
| 9,808
| 32.941176
| 145
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/ServerCoreBlockHoundIntegration.java
|
package org.infinispan.server.core;
import java.util.Arrays;
import org.infinispan.server.core.utils.SslUtils;
import org.kohsuke.MetaInfServices;
import reactor.blockhound.BlockHound;
import reactor.blockhound.BlockingOperationError;
import reactor.blockhound.integration.BlockHoundIntegration;
@SuppressWarnings("unused")
@MetaInfServices
public class ServerCoreBlockHoundIntegration implements BlockHoundIntegration {
@Override
public void applyTo(BlockHound.Builder builder) {
// The xerces parser when it finds a parsing error will print to possibly a file output - ignore
builder.allowBlockingCallsInside("com.sun.org.apache.xerces.internal.util.DefaultErrorHandler", "printError");
// XStream uses reflection that can incur in illegal access being logged to disk due to modules isolation
builder.allowBlockingCallsInside("com.thoughtworks.xstream.converters.reflection.SerializableConverter", "isSerializable");
// Nashorn prints to stderr in its constructor
builder.allowBlockingCallsInside("jdk.nashorn.api.scripting.NashornScriptEngineFactory", "getScriptEngine");
questionableBlockingMethod(builder);
methodsToBeRemoved(builder);
configureBlockingCallback(builder);
}
// This is copied from BlockHound. Many things in the server will gobble up the exception from BlockHound
// so we add a printStackTrace so that we can more easily identify the callback
private static void configureBlockingCallback(BlockHound.Builder builder) {
builder.blockingMethodCallback(bm -> {
Error error = new BlockingOperationError(bm);
// Strip BlockHound's internal noisy frames from the stacktrace to not mislead the users
StackTraceElement[] stackTrace = error.getStackTrace();
int length = stackTrace.length;
for (int i = 0; i < length; i++) {
StackTraceElement stackTraceElement = stackTrace[i];
if ("checkBlocking".equals(stackTraceElement.getMethodName())) {
if (i + 1 < length) {
error.setStackTrace(Arrays.copyOfRange(stackTrace, i + 1, length));
}
break;
}
}
error.printStackTrace();
throw error;
});
}
private static void questionableBlockingMethod(BlockHound.Builder builder) {
// Loads a file on ssl connect to read the key store
builder.allowBlockingCallsInside(SslUtils.class.getName(), "createNettySslContext");
}
/**
* Various methods that need to be removed as they are essentially bugs. Please ensure that a JIRA is created and
* referenced here for any such method
* @param builder the block hound builder to register methods
*/
private static void methodsToBeRemoved(BlockHound.Builder builder) {
// Counter creation is blocking
// https://issues.redhat.com/browse/ISPN-11434
builder.allowBlockingCallsInside("org.infinispan.counter.impl.manager.EmbeddedCounterManager", "createCounter");
}
}
| 3,038
| 40.067568
| 129
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/ServerStateManager.java
|
package org.infinispan.server.core;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import org.infinispan.commons.api.Lifecycle;
import org.infinispan.commons.dataconversion.internal.Json;
import org.infinispan.server.core.transport.IpSubnetFilterRule;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public interface ServerStateManager extends Lifecycle {
CompletableFuture<Void> unignoreCache(String cacheName);
CompletableFuture<Void> ignoreCache(String cacheName);
boolean isCacheIgnored(String cache);
Set<String> getIgnoredCaches();
CompletableFuture<Boolean> connectorStatus(String name);
CompletableFuture<Boolean> connectorStart(String name);
CompletableFuture<Void> connectorStop(String name);
CompletableFuture<Void> setConnectorIpFilterRule(String name, Collection<IpSubnetFilterRule> filterRule);
CompletableFuture<Void> clearConnectorIpFilterRules(String name);
CompletableFuture<Json> listConnections();
ServerManagement managedServer();
}
| 1,085
| 27.578947
| 108
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/CacheInfo.java
|
package org.infinispan.server.core;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.security.auth.Subject;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.util.KeyValuePair;
/**
* @since 12.0
*/
public class CacheInfo<K, V> {
private final Map<KeyValuePair<MediaType, MediaType>, AdvancedCache<K, V>> encodedCaches = new ConcurrentHashMap<>();
protected final AdvancedCache<K, V> cache;
public CacheInfo(AdvancedCache<K, V> cache) {
this.cache = cache;
}
public AdvancedCache<K, V> getCache(KeyValuePair<MediaType, MediaType> mediaTypes, Subject subject) {
AdvancedCache<K, V> encodedCache = encodedCaches.get(mediaTypes);
if (encodedCache == null) {
encodedCache = cache.withMediaType(mediaTypes.getKey(), mediaTypes.getValue());
encodedCaches.put(mediaTypes, encodedCache);
}
if (subject == null) {
return encodedCache;
} else {
return encodedCache.withSubject(subject);
}
}
public AdvancedCache<K, V> getCache() {
return cache;
}
}
| 1,153
| 27.85
| 120
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/SslConfigurationChildBuilder.java
|
package org.infinispan.server.core.configuration;
import org.infinispan.commons.configuration.Builder;
/**
* ProtocolServerConfigurationChildBuilder.
*
* @author Tristan Tarrant
* @since 5.3
*/
public interface SslConfigurationChildBuilder extends Builder<SslEngineConfiguration> {
SslEngineConfigurationBuilder sniHostName(String domain);
}
| 354
| 21.1875
| 87
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/SaslAuthenticationConfiguration.java
|
package org.infinispan.server.core.configuration;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
/**
* AuthenticationConfiguration.
*
* @author Tristan Tarrant
* @since 7.0
*/
public class SaslAuthenticationConfiguration implements AuthenticationConfiguration {
static final AttributeDefinition<String> SECURITY_REALM = AttributeDefinition.builder("security-realm", null, String.class).build();
public static AttributeSet attributeDefinitionSet() {
return new AttributeSet(SaslAuthenticationConfiguration.class, SECURITY_REALM);
}
private final AttributeSet attributes;
private final boolean enabled;
private final SaslConfiguration saslConfiguration;
SaslAuthenticationConfiguration(AttributeSet attributes, SaslConfiguration saslConfiguration, boolean enabled) {
this.attributes = attributes.checkProtection();
this.saslConfiguration = saslConfiguration;
this.enabled = enabled;
}
public AttributeSet attributes() {
return attributes;
}
@Override
public String securityRealm() {
return attributes.attribute(SECURITY_REALM).get();
}
public boolean enabled() {
return enabled;
}
public SaslConfiguration sasl() {
return saslConfiguration;
}
@Override
public String toString() {
return "AuthenticationConfiguration{" +
"attributes=" + attributes +
", enabled=" + enabled +
", sasl=" + saslConfiguration +
'}';
}
}
| 1,588
| 27.890909
| 135
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/package-info.java
|
/**
* Core Server Configuration API
*
* @api.public
*/
package org.infinispan.server.core.configuration;
| 109
| 14.714286
| 49
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/IpFilterConfigurationBuilder.java
|
package org.infinispan.server.core.configuration;
import java.util.ArrayList;
import java.util.List;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.server.core.transport.IpSubnetFilterRule;
import io.netty.handler.ipfilter.IpFilterRuleType;
/**
* IpFilterConfigurationBuilder.
*
* @author Tristan Tarrant
* @since 12.1
*/
public class IpFilterConfigurationBuilder<T extends ProtocolServerConfiguration<T, A>, S extends ProtocolServerConfigurationChildBuilder<T, S, A>, A extends AuthenticationConfiguration>
extends AbstractProtocolServerConfigurationChildBuilder<T, S, A>
implements Builder<IpFilterConfiguration> {
private final List<IpSubnetFilterRule> rules = new ArrayList<>();
public IpFilterConfigurationBuilder(ProtocolServerConfigurationChildBuilder<T, S, A> builder) {
super(builder);
}
@Override
public AttributeSet attributes() {
return AttributeSet.EMPTY;
}
public IpFilterConfigurationBuilder<T, S, A> allowFrom(String rule) {
rules.add(new IpSubnetFilterRule(rule, IpFilterRuleType.ACCEPT));
return this;
}
public IpFilterConfigurationBuilder<T, S, A> rejectFrom(String rule) {
rules.add(new IpSubnetFilterRule(rule, IpFilterRuleType.REJECT));
return this;
}
@Override
public IpFilterConfiguration create() {
return new IpFilterConfiguration(rules);
}
@Override
public IpFilterConfigurationBuilder<T, S, A> read(IpFilterConfiguration template, Combine combine) {
rules.clear();
rules.addAll(template.rules());
return this;
}
@Override
public S self() {
return (S) this;
}
}
| 1,791
| 28.377049
| 185
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/SslEngineConfigurationBuilder.java
|
package org.infinispan.server.core.configuration;
import java.util.function.Supplier;
import javax.net.ssl.SSLContext;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.util.InstanceSupplier;
import org.infinispan.server.core.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
*
* SSLConfigurationBuilder.
*
* @author Tristan Tarrant
* @since 5.3
*/
public class SslEngineConfigurationBuilder implements SslConfigurationChildBuilder {
private static final Log log = LogFactory.getLog(SslEngineConfigurationBuilder.class, Log.class);
private final SslConfigurationBuilder parentSslConfigurationBuilder;
private String keyStoreFileName;
private char[] keyStorePassword;
private String keyAlias;
private String protocol;
private Supplier<SSLContext> sslContextSupplier;
private String trustStoreFileName;
private char[] trustStorePassword;
private char[] keyStoreCertificatePassword;
private String domain = SslConfiguration.DEFAULT_SNI_DOMAIN;
private String keyStoreType;
private String trustStoreType;
SslEngineConfigurationBuilder(SslConfigurationBuilder parentSslConfigurationBuilder) {
this.parentSslConfigurationBuilder = parentSslConfigurationBuilder;
}
@Override
public AttributeSet attributes() {
return AttributeSet.EMPTY;
}
/**
* Sets the {@link SSLContext} to use for setting up SSL connections.
*/
public SslEngineConfigurationBuilder sslContext(SSLContext sslContext) {
this.sslContextSupplier = new InstanceSupplier<>(sslContext);
return this;
}
/**
* Sets the {@link SSLContext} to use for setting up SSL connections.
*/
public SslEngineConfigurationBuilder sslContext(Supplier<SSLContext> sslContext) {
this.sslContextSupplier = sslContext;
return this;
}
/**
* Specifies the filename of a keystore to use to create the {@link SSLContext} You also need to
* specify a {@link #keyStorePassword(char[])}. Alternatively specify an initialized {@link #sslContext(SSLContext)}.
*/
public SslEngineConfigurationBuilder keyStoreFileName(String keyStoreFileName) {
this.keyStoreFileName = keyStoreFileName;
return this;
}
/**
* Specifies the type of the keystore, such as JKS or JCEKS. Defaults to JKS
*/
public SslEngineConfigurationBuilder keyStoreType(String keyStoreType) {
this.keyStoreType = keyStoreType;
return this;
}
/**
* Specifies the password needed to open the keystore You also need to specify a
* {@link #keyStoreFileName(String)}. Alternatively specify an initialized {@link #sslContext(SSLContext)}.
*/
public SslEngineConfigurationBuilder keyStorePassword(char[] keyStorePassword) {
this.keyStorePassword = keyStorePassword;
return this;
}
/**
* Specifies the filename of a truststore to use to create the {@link SSLContext} You also need
* to specify a {@link #trustStorePassword(char[])}. Alternatively specify an initialized {@link #sslContext(SSLContext)}.
*/
public SslEngineConfigurationBuilder trustStoreFileName(String trustStoreFileName) {
this.trustStoreFileName = trustStoreFileName;
return this;
}
/**
* Specifies the type of the truststore, such as JKS or JCEKS. Defaults to JKS
*/
public SslEngineConfigurationBuilder trustStoreType(String trustStoreType) {
this.trustStoreType = trustStoreType;
return this;
}
/**
* Specifies the password needed to open the truststore You also need to specify a
* {@link #trustStoreFileName(String)}. Alternatively specify an initialized {@link #sslContext(SSLContext)}.
*/
public SslEngineConfigurationBuilder trustStorePassword(char[] trustStorePassword) {
this.trustStorePassword = trustStorePassword;
return this;
}
/**
* Specifies the password needed to access private key associated with certificate stored in specified
* {@link #keyStoreFileName(String)}. If password is not specified, the password provided in
* {@link #keyStorePassword(char[])} will be used.
*/
public SslEngineConfigurationBuilder keyStoreCertificatePassword(char[] keyStoreCertificatePassword) {
this.keyStoreCertificatePassword = keyStoreCertificatePassword;
return this;
}
/**
* Selects a specific key to choose from the keystore
*/
public SslEngineConfigurationBuilder keyAlias(String keyAlias) {
this.keyAlias = keyAlias;
return this;
}
/**
* Configures the secure socket protocol.
*
* @see javax.net.ssl.SSLContext#getInstance(String)
* @param protocol The standard name of the requested protocol, e.g TLSv1.2
*/
public SslEngineConfigurationBuilder protocol(String protocol) {
this.protocol = protocol;
return this;
}
@Override
public void validate() {
if(domain == null) {
throw log.noSniDomainConfigured();
}
if (sslContextSupplier == null || sslContextSupplier.get() == null) {
if (keyStoreFileName == null) {
throw log.noSSLKeyManagerConfiguration();
}
if (keyStoreFileName != null && keyStorePassword == null) {
throw log.missingKeyStorePassword(keyStoreFileName);
}
if (trustStoreFileName != null && trustStorePassword == null) {
throw log.missingTrustStorePassword(trustStoreFileName);
}
} else {
if (keyStoreFileName != null || trustStoreFileName != null) {
throw log.xorSSLContext();
}
}
}
@Override
public SslEngineConfiguration create() {
return new SslEngineConfiguration(keyStoreFileName, keyStoreType, keyStorePassword, keyStoreCertificatePassword, keyAlias, sslContextSupplier, trustStoreFileName, trustStoreType, trustStorePassword, protocol);
}
@Override
public SslEngineConfigurationBuilder read(SslEngineConfiguration template, Combine combine) {
this.keyStoreFileName = template.keyStoreFileName();
this.keyStoreType = template.keyStoreType();
this.keyStorePassword = template.keyStorePassword();
this.keyAlias = template.keyAlias();
this.sslContextSupplier = template.sslContextSupplier();
this.trustStoreFileName = template.trustStoreFileName();
this.trustStoreType = template.trustStoreType();
this.trustStorePassword = template.trustStorePassword();
this.protocol = template.protocol();
return this;
}
@Override
public SslEngineConfigurationBuilder sniHostName(String domain) {
return parentSslConfigurationBuilder.sniHostName(domain);
}
}
| 6,754
| 35.122995
| 215
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/SslEngineConfiguration.java
|
package org.infinispan.server.core.configuration;
import java.util.function.Supplier;
import javax.net.ssl.SSLContext;
/**
* SslEngineConfiguration
*
* @author Sebastian Łaskawiec
* @since 9.0
*/
public class SslEngineConfiguration {
private final String keyStoreFileName;
private final String keyStoreType;
private final char[] keyStorePassword;
private final String keyAlias;
private final String protocol;
private final Supplier<SSLContext> sslContext;
private final String trustStoreFileName;
private final String trustStoreType;
private final char[] trustStorePassword;
private final char[] keyStoreCertificatePassword;
SslEngineConfiguration(String keyStoreFileName, String keyStoreType, char[] keyStorePassword, char[] keyStoreCertificatePassword, String keyAlias,
Supplier<SSLContext> sslContext, String trustStoreFileName, String trustStoreType, char[] trustStorePassword, String protocol) {
this.keyStoreFileName = keyStoreFileName;
this.keyStoreType = keyStoreType;
this.keyStorePassword = keyStorePassword;
this.keyStoreCertificatePassword = keyStoreCertificatePassword;
this.keyAlias = keyAlias;
this.sslContext = sslContext;
this.trustStoreFileName = trustStoreFileName;
this.trustStoreType = trustStoreType;
this.trustStorePassword = trustStorePassword;
this.protocol = protocol;
}
public String keyStoreFileName() {
return keyStoreFileName;
}
public String keyStoreType() {
return keyStoreType;
}
public char[] keyStorePassword() {
return keyStorePassword;
}
public char[] keyStoreCertificatePassword() {
return keyStoreCertificatePassword;
}
public String keyAlias() {
return keyAlias;
}
public SSLContext sslContext() {
return sslContext == null ? null : sslContext.get();
}
Supplier<SSLContext> sslContextSupplier() {
return sslContext;
}
public String trustStoreFileName() {
return trustStoreFileName;
}
public String trustStoreType() {
return trustStoreType;
}
public char[] trustStorePassword() {
return trustStorePassword;
}
public String protocol() {
return protocol;
}
public String[] protocols() {
if (protocol != null) {
return new String[]{protocol};
} else {
return null;
}
}
@Override
public String toString() {
return "SslEngineConfiguration{" +
"keyStoreFileName='" + keyStoreFileName + '\'' +
", keyStoreType='" + keyStoreType + '\'' +
", keyAlias='" + keyAlias + '\'' +
", protocol='" + protocol + '\'' +
", sslContext=" + sslContext +
", trustStoreFileName='" + trustStoreFileName + '\'' +
", trustStoreType='" + trustStoreType + '\'' +
'}';
}
}
| 2,911
| 26.733333
| 154
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/NoAuthenticationConfiguration.java
|
package org.infinispan.server.core.configuration;
/**
* @since 15.0
**/
public class NoAuthenticationConfiguration implements AuthenticationConfiguration {
@Override
public String securityRealm() {
return null;
}
@Override
public boolean enabled() {
return false;
}
}
| 302
| 16.823529
| 83
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/SslConfiguration.java
|
package org.infinispan.server.core.configuration;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.configuration.attributes.ConfigurationElement;
/**
* SslConfiguration.
*
* @author Tristan Tarrant
* @since 5.3
*/
public class SslConfiguration extends ConfigurationElement<SslConfiguration> {
public static final String DEFAULT_SNI_DOMAIN = "*";
static final AttributeDefinition<Boolean> ENABLED = AttributeDefinition.builder("enabled", false).immutable().build();
static final AttributeDefinition<Boolean> REQUIRE_CLIENT_AUTH = AttributeDefinition.builder("require-client-auth", false).immutable().build();
private final Map<String, SslEngineConfiguration> sniDomainsConfiguration;
public static AttributeSet attributeDefinitionSet() {
return new AttributeSet(SslConfiguration.class, ENABLED, REQUIRE_CLIENT_AUTH);
}
SslConfiguration(AttributeSet attributes, Map<String, SslEngineConfiguration> sniDomainsConfiguration) {
super("ssl", attributes);
this.sniDomainsConfiguration = sniDomainsConfiguration;
}
public boolean enabled() {
return attributes.attribute(ENABLED).get();
}
public boolean requireClientAuth() {
return attributes.attribute(REQUIRE_CLIENT_AUTH).get();
}
public String keyStoreFileName() {
return sniDomainsConfiguration.get(DEFAULT_SNI_DOMAIN).keyStoreFileName();
}
public char[] keyStorePassword() {
return sniDomainsConfiguration.get(DEFAULT_SNI_DOMAIN).keyStorePassword();
}
public char[] keyStoreCertificatePassword() {
return sniDomainsConfiguration.get(DEFAULT_SNI_DOMAIN).keyStoreCertificatePassword();
}
public SSLContext sslContext() {
return sniDomainsConfiguration.get(DEFAULT_SNI_DOMAIN).sslContext();
}
public String trustStoreFileName() {
return sniDomainsConfiguration.get(DEFAULT_SNI_DOMAIN).trustStoreFileName();
}
public char[] trustStorePassword() {
return sniDomainsConfiguration.get(DEFAULT_SNI_DOMAIN).trustStorePassword();
}
public Map<String, SslEngineConfiguration> sniDomainsConfiguration() {
return sniDomainsConfiguration;
}
}
| 2,329
| 32.285714
| 145
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/SslConfigurationBuilder.java
|
package org.infinispan.server.core.configuration;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.net.ssl.SSLContext;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
/**
*
* SSLConfigurationBuilder.
*
* @author Tristan Tarrant
* @author Sebastian Łaskawiec
* @since 5.3
*/
public class SslConfigurationBuilder<T extends ProtocolServerConfiguration<T, A>, S extends ProtocolServerConfigurationChildBuilder<T, S, A>, A extends AuthenticationConfiguration>
extends AbstractProtocolServerConfigurationChildBuilder<T, S, A>
implements Builder<SslConfiguration> {
private final AttributeSet attributes;
private SslEngineConfigurationBuilder defaultDomainConfigurationBuilder;
private Map<String, SslEngineConfigurationBuilder> sniDomains;
public SslConfigurationBuilder(ProtocolServerConfigurationChildBuilder<T, S, A> builder) {
super(builder);
attributes = SslConfiguration.attributeDefinitionSet();
sniDomains = new HashMap<>();
defaultDomainConfigurationBuilder = new SslEngineConfigurationBuilder(this);
sniDomains.put(SslConfiguration.DEFAULT_SNI_DOMAIN, defaultDomainConfigurationBuilder);
}
@Override
public AttributeSet attributes() {
return attributes;
}
/**
* Disables the SSL support
*/
public SslConfigurationBuilder disable() {
return enabled(false);
}
/**
* Enables the SSL support
*/
public SslConfigurationBuilder enable() {
return enabled(true);
}
/**
* Enables or disables the SSL support
*/
public SslConfigurationBuilder enabled(boolean enabled) {
attributes.attribute(SslConfiguration.ENABLED).set(enabled);
return this;
}
public boolean isEnabled() {
return attributes.attribute(SslConfiguration.ENABLED).get();
}
/**
* Enables client certificate authentication
*/
public SslConfigurationBuilder requireClientAuth(boolean requireClientAuth) {
attributes.attribute(SslConfiguration.REQUIRE_CLIENT_AUTH).set(requireClientAuth);
return this;
}
/**
* Returns SNI domain configuration.
*
* @param domain A domain which will hold configuration details. It is also possible to specify <code>*</code>
* for all domains.
* @return {@link SslConfigurationBuilder} instance associated with specified domain.
*/
public SslEngineConfigurationBuilder sniHostName(String domain) {
return sniDomains.computeIfAbsent(domain, (v) -> new SslEngineConfigurationBuilder(this));
}
/**
* Sets the {@link SSLContext} to use for setting up SSL connections.
*/
public SslConfigurationBuilder sslContext(SSLContext sslContext) {
defaultDomainConfigurationBuilder.sslContext(sslContext);
return this;
}
/**
* Sets the {@link SSLContext} to use for setting up SSL connections.
*/
public SslConfigurationBuilder sslContext(Supplier<SSLContext> sslContext) {
defaultDomainConfigurationBuilder.sslContext(sslContext);
return this;
}
/**
* Specifies the filename of a keystore to use to create the {@link SSLContext} You also need to
* specify a {@link #keyStorePassword(char[])}. Alternatively specify prebuilt {@link SSLContext}
* through {@link #sslContext(SSLContext)}.
*/
public SslConfigurationBuilder keyStoreFileName(String keyStoreFileName) {
defaultDomainConfigurationBuilder.keyStoreFileName(keyStoreFileName);
return this;
}
/**
* Specifies the type of the keystore, such as JKS or JCEKS. Defaults to JKS
*/
public SslConfigurationBuilder keyStoreType(String keyStoreType) {
defaultDomainConfigurationBuilder.keyStoreType(keyStoreType);
return this;
}
/**
* Specifies the password needed to open the keystore You also need to specify a
* {@link #keyStoreFileName(String)}. Alternatively specify prebuilt {@link SSLContext}
* through {@link #sslContext(SSLContext)}.
*/
public SslConfigurationBuilder keyStorePassword(char[] keyStorePassword) {
defaultDomainConfigurationBuilder.keyStorePassword(keyStorePassword);
return this;
}
/**
* Specifies the password needed to access private key associated with certificate stored in specified
* {@link #keyStoreFileName(String)}. If password is not specified, the password provided in
* {@link #keyStorePassword(char[])} will be used.
*/
public SslConfigurationBuilder keyStoreCertificatePassword(char[] keyStoreCertificatePassword) {
defaultDomainConfigurationBuilder.keyStoreCertificatePassword(keyStoreCertificatePassword);
return this;
}
/**
* Selects a specific key to choose from the keystore
*/
public SslConfigurationBuilder keyAlias(String keyAlias) {
defaultDomainConfigurationBuilder.keyAlias(keyAlias);
return this;
}
/**
* Specifies the filename of a truststore to use to create the {@link SSLContext} You also need
* to specify a {@link #trustStorePassword(char[])}. Alternatively specify prebuilt {@link SSLContext}
* through {@link #sslContext(SSLContext)}.
*/
public SslConfigurationBuilder trustStoreFileName(String trustStoreFileName) {
defaultDomainConfigurationBuilder.trustStoreFileName(trustStoreFileName);
return this;
}
/**
* Specifies the type of the truststore, such as JKS or JCEKS. Defaults to JKS
*/
public SslConfigurationBuilder trustStoreType(String trustStoreType) {
defaultDomainConfigurationBuilder.trustStoreType(trustStoreType);
return this;
}
/**
* Specifies the password needed to open the truststore You also need to specify a
* {@link #trustStoreFileName(String)}. Alternatively specify prebuilt {@link SSLContext}
* through {@link #sslContext(SSLContext)}.
*/
public SslConfigurationBuilder trustStorePassword(char[] trustStorePassword) {
defaultDomainConfigurationBuilder.trustStorePassword(trustStorePassword);
return this;
}
/**
* Configures the secure socket protocol.
*
* @see javax.net.ssl.SSLContext#getInstance(String)
* @param protocol The standard name of the requested protocol, e.g TLSv1.2
*/
public SslConfigurationBuilder protocol(String protocol) {
defaultDomainConfigurationBuilder.protocol(protocol);
return this;
}
@Override
public void validate() {
if (isEnabled()) {
sniDomains.forEach((domainName, config) -> config.validate());
}
}
@Override
public SslConfiguration create() {
Map<String, SslEngineConfiguration> producedSniConfigurations = sniDomains.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().create()));
return new SslConfiguration(attributes.protect(), producedSniConfigurations);
}
@Override
public SslConfigurationBuilder read(SslConfiguration template, Combine combine) {
this.attributes.read(template.attributes(), combine);
this.sniDomains = new HashMap<>();
template.sniDomainsConfiguration().entrySet()
.forEach(e -> sniDomains.put(e.getKey(), new SslEngineConfigurationBuilder(this).read(e.getValue(), combine)));
this.defaultDomainConfigurationBuilder = sniDomains
.computeIfAbsent(SslConfiguration.DEFAULT_SNI_DOMAIN, (v) -> new SslEngineConfigurationBuilder(this));
return this;
}
@Override
public S self() {
return (S) this;
}
}
| 7,735
| 33.535714
| 180
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/SaslConfigurationBuilder.java
|
package org.infinispan.server.core.configuration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.security.auth.Subject;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslServerFactory;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.Attribute;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.util.SaslUtils;
import org.infinispan.server.core.logging.Log;
import org.infinispan.server.core.security.external.ExternalSaslServerFactory;
import org.infinispan.server.core.security.sasl.SaslAuthenticator;
/**
* @since 10.0
*/
public class SaslConfigurationBuilder implements Builder<SaslConfiguration> {
private final AttributeSet attributes;
private SaslAuthenticator saslAuthenticator;
private Map<String, String> mechProperties = new HashMap<>();
public SaslConfigurationBuilder() {
this.attributes = SaslConfiguration.attributeDefinitionSet();
}
@Override
public AttributeSet attributes() {
return attributes;
}
public SaslConfigurationBuilder authenticator(SaslAuthenticator saslAuthenticator) {
this.saslAuthenticator = saslAuthenticator;
return this;
}
public SaslConfigurationBuilder serverName(String name) {
attributes.attribute(SaslConfiguration.SERVER_NAME).set(name);
return this;
}
public String serverName() {
return attributes.attribute(SaslConfiguration.SERVER_NAME).get();
}
public SaslConfigurationBuilder serverSubject(Subject subject) {
attributes.attribute(SaslConfiguration.SERVER_SUBJECT).set(subject);
return this;
}
public SaslConfigurationBuilder addQOP(String value) {
Attribute<List<QOP>> attribute = attributes.attribute(SaslConfiguration.QOP);
List<QOP> qops = attribute.get();
qops.add(QOP.fromString(value));
attribute.set(qops);
return this;
}
public SaslConfigurationBuilder addStrength(String value) {
Attribute<List<Strength>> attribute = attributes.attribute(SaslConfiguration.STRENGTH);
List<Strength> strengths = attribute.get();
strengths.add(Strength.fromString(value));
attribute.set(strengths);
return this;
}
public SaslConfigurationBuilder addPolicy(String value) {
Attribute<List<Policy>> attribute = attributes.attribute(SaslConfiguration.POLICY);
List<Policy> policies = attribute.get();
policies.add(Policy.fromString(value));
attribute.set(policies);
return this;
}
public SaslConfigurationBuilder addProperty(String key, String value) {
Attribute<Map<String, String>> a = attributes.attribute(SaslConfiguration.SASL_PROPERTIES);
Map<String, String> map = a.get();
map.put(key, value);
a.set(map);
return this;
}
private Map<String, String> getMechProperties() {
if (mechProperties.isEmpty()) {
mechProperties = new HashMap<>();
List<QOP> qops = attributes.attribute(SaslConfiguration.QOP).get();
if (!qops.isEmpty()) {
String qopsValue = qops.stream().map(QOP::toString).collect(Collectors.joining(","));
mechProperties.put(Sasl.QOP, qopsValue);
}
List<Strength> strengths = attributes.attribute(SaslConfiguration.STRENGTH).get();
if (!strengths.isEmpty()) {
String strengthsValue = strengths.stream().map(Strength::toString).collect(Collectors.joining(","));
mechProperties.put(Sasl.STRENGTH, strengthsValue);
}
mechProperties.putAll(attributes.attribute(SaslConfiguration.SASL_PROPERTIES).get());
}
return mechProperties;
}
public SaslConfigurationBuilder addMechanisms(String... mechs) {
for(String mech : mechs) {
addAllowedMech(mech);
}
return this;
}
public SaslConfigurationBuilder addAllowedMech(String mech) {
Attribute<Set<String>> attribute = attributes.attribute(SaslConfiguration.MECHANISMS);
Set<String> mechs = attribute.get();
mechs.add(mech);
attribute.set(mechs);
return this;
}
public boolean hasMechanisms() {
return !attributes.attribute(SaslConfiguration.MECHANISMS).get().isEmpty();
}
public Set<String> mechanisms() {
return attributes.attribute(SaslConfiguration.MECHANISMS).get();
}
@Override
public void validate() {
if (saslAuthenticator == null) {
throw Log.CONFIG.saslAuthenticationProvider();
}
Set<String> allMechs = new LinkedHashSet<>(Arrays.asList(ExternalSaslServerFactory.NAMES));
for (SaslServerFactory factory : SaslUtils.getSaslServerFactories(this.getClass().getClassLoader(), null, true)) {
allMechs.addAll(Arrays.asList(factory.getMechanismNames(mechProperties)));
}
Attribute<Set<String>> mechanismAttr = attributes.attribute(SaslConfiguration.MECHANISMS);
Set<String> allowedMechs = mechanismAttr.get();
if (allowedMechs.isEmpty()) {
mechanismAttr.set(allMechs);
} else if (!allMechs.containsAll(allowedMechs)) {
throw Log.CONFIG.invalidAllowedMechs(allowedMechs, allMechs);
}
if (attributes.attribute(SaslConfiguration.SERVER_NAME) == null) {
throw Log.CONFIG.missingServerName();
}
}
@Override
public SaslConfiguration create() {
Map<String, String> mechProperties = getMechProperties();
return new SaslConfiguration(attributes.protect(), saslAuthenticator, mechProperties);
}
@Override
public SaslConfigurationBuilder read(SaslConfiguration template, Combine combine) {
attributes.read(template.attributes(), combine);
mechProperties = template.mechProperties();
saslAuthenticator = template.authenticator();
return this;
}
public SaslConfigurationBuilder addMechProperty(String key, String value) {
mechProperties.put(key, value);
return this;
}
public SaslConfigurationBuilder mechProperties(Map<String, String> mechProperties) {
this.mechProperties = mechProperties;
return this;
}
}
| 6,340
| 34.227778
| 120
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/Element.java
|
package org.infinispan.server.core.configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @author Tristan Tarrant
* @since 10.0
*/
public enum Element {
UNKNOWN(null), //must be first
AUTHENTICATION,
ENCRYPTION,
FORWARD_SECRECY,
NO_ACTIVE,
NO_ANONYMOUS,
NO_DICTIONARY,
NO_PLAIN_TEXT,
PASS_CREDENTIALS,
POLICY,
PROPERTIES,
PROPERTY,
SASL,
SNI,
SERVER_SUBJECT;
private static final Map<String, Element> ELEMENTS;
static {
final Map<String, Element> map = new HashMap<>(8);
for (Element element : values()) {
final String name = element.name;
if (name != null) {
map.put(name, element);
}
}
ELEMENTS = map;
}
private final String name;
Element(final String name) {
this.name = name;
}
Element() {
this.name = name().toLowerCase().replace('_', '-');
}
public static Element forName(final String localName) {
final Element element = ELEMENTS.get(localName);
return element == null ? UNKNOWN : element;
}
@Override
public String toString() {
return name;
}
}
| 1,157
| 17.983607
| 58
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/EncryptionConfigurationBuilder.java
|
package org.infinispan.server.core.configuration;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import javax.net.ssl.SSLContext;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
/**
* @since 10.0
*/
public class EncryptionConfigurationBuilder implements Builder<EncryptionConfiguration> {
private final AttributeSet attributes;
private final List<SniConfigurationBuilder> sniConfigurations = new ArrayList<>();
private final SslConfigurationBuilder ssl;
public EncryptionConfigurationBuilder(SslConfigurationBuilder sslConfigurationBuilder) {
this.ssl = sslConfigurationBuilder;
this.attributes = EncryptionConfiguration.attributeDefinitionSet();
}
@Override
public AttributeSet attributes() {
return attributes;
}
public SniConfigurationBuilder addSni() {
SniConfigurationBuilder sni = new SniConfigurationBuilder(ssl);
sniConfigurations.add(sni);
return sni;
}
public EncryptionConfigurationBuilder sslContext(SSLContext context) {
ssl.sslContext(context);
return this;
}
public EncryptionConfigurationBuilder sslContext(Supplier<SSLContext> context) {
ssl.sslContext(context);
return this;
}
public EncryptionConfigurationBuilder realm(String name) {
ssl.enable();
attributes.attribute(EncryptionConfiguration.SECURITY_REALM).set(name);
return this;
}
public EncryptionConfigurationBuilder requireClientAuth(boolean require) {
attributes.attribute(EncryptionConfiguration.REQUIRE_CLIENT_AUTH).set(require);
ssl.requireClientAuth(require);
return this;
}
@Override
public EncryptionConfiguration create() {
List<SniConfiguration> snis = sniConfigurations.stream().map(SniConfigurationBuilder::create).collect(toList());
return new EncryptionConfiguration(attributes.protect(), snis);
}
@Override
public EncryptionConfigurationBuilder read(EncryptionConfiguration template, Combine combine) {
attributes.read(template.attributes(), combine);
sniConfigurations.clear();
template.sniConfigurations().forEach(s -> addSni().read(s, combine));
return this;
}
}
| 2,395
| 30.526316
| 118
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/SaslAuthenticationConfigurationBuilder.java
|
package org.infinispan.server.core.configuration;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
/**
* AuthenticationConfigurationBuilder.
*
* @author Tristan Tarrant
* @since 7.0
*/
public class SaslAuthenticationConfigurationBuilder implements AuthenticationConfigurationBuilder<SaslAuthenticationConfiguration> {
private final AttributeSet attributes;
private boolean enabled = false;
private final SaslConfigurationBuilder sasl = new SaslConfigurationBuilder();
public SaslAuthenticationConfigurationBuilder(ProtocolServerConfigurationChildBuilder<?,?,?> builder) {
this.attributes = SaslAuthenticationConfiguration.attributeDefinitionSet();
}
@Override
public AttributeSet attributes() {
return attributes;
}
public SaslAuthenticationConfigurationBuilder enable() {
this.enabled = true;
return this;
}
public SaslAuthenticationConfigurationBuilder disable() {
this.enabled = false;
return this;
}
public SaslAuthenticationConfigurationBuilder enabled(boolean enabled) {
this.enabled = enabled;
return this;
}
public boolean enabled() {
return enabled;
}
public SaslAuthenticationConfigurationBuilder securityRealm(String name) {
attributes.attribute(SaslAuthenticationConfiguration.SECURITY_REALM).set(name);
return this;
}
public String securityRealm() {
return attributes.attribute(SaslAuthenticationConfiguration.SECURITY_REALM).get();
}
public boolean hasSecurityRealm() {
return !attributes.attribute(SaslAuthenticationConfiguration.SECURITY_REALM).isNull();
}
public SaslConfigurationBuilder sasl() {
return sasl;
}
@Override
public void validate() {
if (enabled) {
sasl.validate();
}
}
@Override
public SaslAuthenticationConfiguration create() {
return new SaslAuthenticationConfiguration(attributes.protect(), sasl.create(), enabled);
}
@Override
public Builder<?> read(SaslAuthenticationConfiguration template, Combine combine) {
this.enabled = template.enabled();
this.sasl.read(template.sasl(), combine);
return this;
}
}
| 2,314
| 27.231707
| 132
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/AuthenticationConfigurationBuilder.java
|
package org.infinispan.server.core.configuration;
import org.infinispan.commons.configuration.Builder;
/**
* @since 15.0
**/
public interface AuthenticationConfigurationBuilder<A extends AuthenticationConfiguration> extends Builder<A> {
AuthenticationConfigurationBuilder<A> enable();
String securityRealm();
}
| 323
| 22.142857
| 111
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/ProtocolServerConfiguration.java
|
package org.infinispan.server.core.configuration;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.configuration.attributes.ConfigurationElement;
import org.infinispan.commons.util.ProcessorInfo;
import org.infinispan.server.core.admin.AdminOperationsHandler;
/**
* ServerConfiguration.
*
* @author Tristan Tarrant
* @since 5.3
*/
public abstract class ProtocolServerConfiguration<T extends ProtocolServerConfiguration, A extends AuthenticationConfiguration> extends ConfigurationElement<T> {
public static final AttributeDefinition<String> DEFAULT_CACHE_NAME = AttributeDefinition.builder(Attribute.CACHE, null, String.class).immutable().build();
public static final AttributeDefinition<String> NAME = AttributeDefinition.builder(Attribute.NAME, "").immutable().build();
public static final AttributeDefinition<String> HOST = AttributeDefinition.builder(Attribute.HOST, "127.0.0.1").immutable().autoPersist(false).build();
public static final AttributeDefinition<Integer> PORT = AttributeDefinition.builder(Attribute.PORT, -1).immutable().autoPersist(false).build();
public static final AttributeDefinition<Integer> IDLE_TIMEOUT = AttributeDefinition.builder(Attribute.IDLE_TIMEOUT, -1).immutable().build();
public static final AttributeDefinition<Set<String>> IGNORED_CACHES = AttributeDefinition.builder(Attribute.IGNORED_CACHES, Collections.emptySet(), (Class<Set<String>>) (Class<?>) Set.class).immutable().build();
public static final AttributeDefinition<Integer> RECV_BUF_SIZE = AttributeDefinition.builder(Attribute.RECEIVE_BUFFER_SIZE, 0).immutable().build();
public static final AttributeDefinition<Integer> SEND_BUF_SIZE = AttributeDefinition.builder(Attribute.SEND_BUFFER_SIZE, 0).immutable().build();
public static final AttributeDefinition<Boolean> START_TRANSPORT = AttributeDefinition.builder(Attribute.START_TRANSPORT, true).immutable().autoPersist(false).build();
public static final AttributeDefinition<Boolean> TCP_NODELAY = AttributeDefinition.builder(Attribute.TCP_NODELAY, true).immutable().build();
public static final AttributeDefinition<Boolean> TCP_KEEPALIVE = AttributeDefinition.builder(Attribute.TCP_KEEPALIVE, false).immutable().build();
public static final AttributeDefinition<Integer> IO_THREADS = AttributeDefinition.builder(Attribute.IO_THREADS, 2 * ProcessorInfo.availableProcessors()).immutable().build();
public static final AttributeDefinition<AdminOperationsHandler> ADMIN_OPERATION_HANDLER = AttributeDefinition.builder("admin-operation-handler", null, AdminOperationsHandler.class)
.immutable().autoPersist(false).build();
public static final AttributeDefinition<Boolean> ZERO_CAPACITY_NODE = AttributeDefinition.builder(Attribute.ZERO_CAPACITY_NODE, false).immutable().build();
public static final AttributeDefinition<String> SOCKET_BINDING = AttributeDefinition.builder(Attribute.SOCKET_BINDING, null, String.class).immutable().build();
public static final AttributeDefinition<Boolean> IMPLICIT_CONNECTOR = AttributeDefinition.builder("implicit-connector", false).immutable().autoPersist(false).build();
private volatile boolean enabled = true;
public static AttributeSet attributeDefinitionSet() {
return new AttributeSet(ProtocolServerConfiguration.class,
DEFAULT_CACHE_NAME, NAME, HOST, PORT, IDLE_TIMEOUT, IGNORED_CACHES, RECV_BUF_SIZE, SEND_BUF_SIZE, START_TRANSPORT,
TCP_NODELAY, TCP_KEEPALIVE, IO_THREADS, ADMIN_OPERATION_HANDLER, ZERO_CAPACITY_NODE, SOCKET_BINDING,
IMPLICIT_CONNECTOR);
}
protected final A authentication;
protected final SslConfiguration ssl;
protected final IpFilterConfiguration ipFilter;
protected ProtocolServerConfiguration(Enum<?> element, AttributeSet attributes, A authentication, SslConfiguration ssl, IpFilterConfiguration ipFilter) {
this(element.toString(), attributes, authentication, ssl, ipFilter);
}
protected ProtocolServerConfiguration(String element, AttributeSet attributes, A authentication, SslConfiguration ssl, IpFilterConfiguration ipFilter) {
super(element, attributes, ssl);
this.authentication = authentication;
this.ssl = ssl;
this.ipFilter = ipFilter;
}
public String defaultCacheName() {
return attributes.attribute(DEFAULT_CACHE_NAME).get();
}
public String name() {
return attributes.attribute(NAME).get();
}
public String host() {
return attributes.attribute(HOST).get();
}
public int port() {
return attributes.attribute(PORT).get();
}
public int idleTimeout() {
return attributes.attribute(IDLE_TIMEOUT).get();
}
public int recvBufSize() {
return attributes.attribute(RECV_BUF_SIZE).get();
}
public int sendBufSize() {
return attributes.attribute(SEND_BUF_SIZE).get();
}
public A authentication() {
return authentication;
}
public SslConfiguration ssl() {
return ssl;
}
public IpFilterConfiguration ipFilter() {
return ipFilter;
}
public boolean tcpNoDelay() {
return attributes.attribute(TCP_NODELAY).get();
}
public boolean tcpKeepAlive() {
return attributes.attribute(TCP_KEEPALIVE).get();
}
public int ioThreads() {
return attributes.attribute(IO_THREADS).get();
}
public boolean startTransport() {
return attributes.attribute(START_TRANSPORT).get();
}
public AdminOperationsHandler adminOperationsHandler() {
return attributes.attribute(ADMIN_OPERATION_HANDLER).get();
}
public String socketBinding() {
return attributes.attribute(SOCKET_BINDING).get();
}
public boolean zeroCapacityNode() {
return attributes.attribute(ZERO_CAPACITY_NODE).get();
}
public void disable() {
this.enabled = false;
}
public void enable() {
this.enabled = true;
}
public boolean isEnabled() {
return enabled;
}
public boolean isImplicit() {
return attributes.attribute(IMPLICIT_CONNECTOR).get();
}
}
| 6,213
| 41.855172
| 214
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/ProtocolServerConfigurationBuilder.java
|
package org.infinispan.server.core.configuration;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.ADMIN_OPERATION_HANDLER;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.DEFAULT_CACHE_NAME;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.HOST;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.IDLE_TIMEOUT;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.IMPLICIT_CONNECTOR;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.IO_THREADS;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.NAME;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.PORT;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.RECV_BUF_SIZE;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.SEND_BUF_SIZE;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.SOCKET_BINDING;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.START_TRANSPORT;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.TCP_KEEPALIVE;
import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.TCP_NODELAY;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.server.core.admin.AdminOperationsHandler;
import org.infinispan.server.core.logging.Log;
public abstract class ProtocolServerConfigurationBuilder<T extends ProtocolServerConfiguration<T, A>, S extends ProtocolServerConfigurationChildBuilder<T, S, A>, A extends AuthenticationConfiguration>
implements ProtocolServerConfigurationChildBuilder<T, S, A>, Builder<T> {
protected final AttributeSet attributes;
protected final SslConfigurationBuilder<T, S, A> ssl;
protected final IpFilterConfigurationBuilder<T, S, A> ipFilter;
protected ProtocolServerConfigurationBuilder(int port, AttributeSet attributes) {
this.attributes = attributes;
this.ssl = new SslConfigurationBuilder(this);
this.ipFilter = new IpFilterConfigurationBuilder<>(this);
port(port);
}
@Override
public S defaultCacheName(String defaultCacheName) {
attributes.attribute(DEFAULT_CACHE_NAME).set(defaultCacheName);
return this.self();
}
@Override
public S name(String name) {
attributes.attribute(NAME).set(name);
return this.self();
}
public String name() {
return attributes.attribute(NAME).get();
}
@Override
public S host(String host) {
attributes.attribute(HOST).set(host);
return this.self();
}
public String host() {
return attributes.attribute(HOST).get();
}
@Override
public S port(int port) {
attributes.attribute(PORT).set(port);
return this.self();
}
public int port() {
return attributes.attribute(PORT).get();
}
@Override
public S idleTimeout(int idleTimeout) {
attributes.attribute(IDLE_TIMEOUT).set(idleTimeout);
return this.self();
}
@Override
public S tcpNoDelay(boolean tcpNoDelay) {
attributes.attribute(TCP_NODELAY).set(tcpNoDelay);
return this.self();
}
@Override
public S tcpKeepAlive(boolean tcpKeepAlive) {
attributes.attribute(TCP_KEEPALIVE).set(tcpKeepAlive);
return this.self();
}
@Override
public S recvBufSize(int recvBufSize) {
attributes.attribute(RECV_BUF_SIZE).set(recvBufSize);
return this.self();
}
@Override
public S sendBufSize(int sendBufSize) {
attributes.attribute(SEND_BUF_SIZE).set(sendBufSize);
return this.self();
}
@Override
public SslConfigurationBuilder ssl() {
return ssl;
}
@Override
public IpFilterConfigurationBuilder<T, S, A> ipFilter() {
return ipFilter;
}
@Override
public S ioThreads(int ioThreads) {
attributes.attribute(IO_THREADS).set(ioThreads);
return this.self();
}
@Override
public S startTransport(boolean startTransport) {
attributes.attribute(START_TRANSPORT).set(startTransport);
return this.self();
}
public boolean startTransport() {
return attributes.attribute(START_TRANSPORT).get();
}
@Override
public S adminOperationsHandler(AdminOperationsHandler handler) {
attributes.attribute(ADMIN_OPERATION_HANDLER).set(handler);
return this.self();
}
@Override
public S socketBinding(String name) {
attributes.attribute(SOCKET_BINDING).set(name);
return this.self();
}
public String socketBinding() {
return attributes.attribute(SOCKET_BINDING).get();
}
@Override
public S implicitConnector(boolean implicitConnector) {
attributes.attribute(IMPLICIT_CONNECTOR).set(implicitConnector);
return this.self();
}
public boolean implicitConnector() {
return attributes.attribute(IMPLICIT_CONNECTOR).get();
}
@Override
public void validate() {
authentication().validate();
ssl.validate();
if (attributes.attribute(IDLE_TIMEOUT).get() < -1) {
throw Log.CONFIG.illegalIdleTimeout(attributes.attribute(IDLE_TIMEOUT).get());
}
if (attributes.attribute(SEND_BUF_SIZE).get() < 0) {
throw Log.CONFIG.illegalSendBufferSize(attributes.attribute(SEND_BUF_SIZE).get());
}
if (attributes.attribute(RECV_BUF_SIZE).get() < 0) {
throw Log.CONFIG.illegalReceiveBufferSize(attributes.attribute(RECV_BUF_SIZE).get());
}
if (attributes.attribute(IO_THREADS).get() < 0) {
throw Log.CONFIG.illegalIOThreads(attributes.attribute(IO_THREADS).get());
}
}
@Override
public Builder<?> read(T template, Combine combine) {
this.attributes.read(template.attributes(), combine);
this.authentication().read(template.authentication(), combine);
this.ssl.read(template.ssl(), combine);
this.ipFilter.read(template.ipFilter(), combine);
return this;
}
}
| 6,263
| 33.417582
| 200
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/AuthenticationConfiguration.java
|
package org.infinispan.server.core.configuration;
/**
* @since 15.0
**/
public interface AuthenticationConfiguration {
String securityRealm();
boolean enabled();
}
| 174
| 14.909091
| 49
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/ProtocolServerConfigurationChildBuilder.java
|
package org.infinispan.server.core.configuration;
import org.infinispan.commons.configuration.Self;
import org.infinispan.server.core.admin.AdminOperationsHandler;
/**
* ProtocolServerConfigurationChildBuilder.
*
* @param <T> the root configuration object returned by the builder. Must extend {@link ProtocolServerConfiguration}
* @param <S> the sub-builder this is an implementation of. Must extend ProtocolServerConfigurationChildBuilder
*
* @author Tristan Tarrant
* @since 5.3
*/
public interface ProtocolServerConfigurationChildBuilder<T extends ProtocolServerConfiguration<T, A>, S extends ProtocolServerConfigurationChildBuilder<T, S, A>, A extends AuthenticationConfiguration>
extends Self<S> {
/**
* Specifies the cache to use as a default cache for the protocol
*/
S defaultCacheName(String defaultCacheName);
/**
* Specifies a custom name for this protocol server in order to easily distinguish it from others of the same type on the same server, e.g. via JMX. Defaults to the empty string.
* The name should be the same across the cluster.
*/
S name(String name);
/**
* Specifies the host or IP address on which this server will listen
*/
S host(String host);
/**
* Specifies the port on which this server will listen
*/
S port(int port);
/**
* Specifies the maximum time that connections from client will be kept open without activity
*/
S idleTimeout(int idleTimeout);
/**
* Affects TCP NODELAY on the TCP stack. Defaults to enabled
*/
S tcpNoDelay(boolean tcpNoDelay);
/**
* Affects TCP KEEPALIVE on the TCP stack. Defaults to disabled
*/
S tcpKeepAlive(boolean tcpKeepAlive);
/**
* Sets the size of the receive buffer
*/
S recvBufSize(int recvBufSize);
/**
* Sets the size of the send buffer
*/
S sendBufSize(int sendBufSize);
AuthenticationConfigurationBuilder<A> authentication();
/**
* Configures SSL
*/
SslConfigurationBuilder<T, S, A> ssl();
/**
* Configures the IP filter rules
*/
IpFilterConfigurationBuilder<T, S, A> ipFilter();
/**
* Sets the number of I/O threads
*/
S ioThreads(int ioThreads);
/**
* Indicates whether transport implementation should or should not be started.
*/
S startTransport(boolean startTransport);
/**
* Indicates the {@link AdminOperationsHandler} which will be used to handle admin operations
*/
S adminOperationsHandler(AdminOperationsHandler handler);
/**
* Indicates the name of socket binding which will be used
*/
S socketBinding(String name);
/**
* Indicates whether this connector was added implicitly
*/
S implicitConnector(boolean implicitConnector);
/**
* Builds a configuration object
*/
T build();
}
| 2,842
| 26.07619
| 200
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/Attribute.java
|
package org.infinispan.server.core.configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @author Tristan Tarrant
* @since 10.0
*/
public enum Attribute {
UNKNOWN(null), // must be first
CACHE,
HOST,
IDLE_TIMEOUT,
IGNORED_CACHES,
IO_THREADS,
MECHANISMS,
NAME,
POLICY,
PORT,
QOP,
RECEIVE_BUFFER_SIZE,
REQUIRE_SSL_CLIENT_AUTH,
SECURITY_REALM,
SEND_BUFFER_SIZE,
SERVER_NAME,
SERVER_PRINCIPAL,
SOCKET_BINDING,
START_TRANSPORT,
STRENGTH,
TCP_KEEPALIVE,
TCP_NODELAY,
VALUE,
ZERO_CAPACITY_NODE
;
private static final Map<String, Attribute> ATTRIBUTES;
static {
final Map<String, Attribute> map = new HashMap<>(64);
for (Attribute attribute : values()) {
final String name = attribute.name;
if (name != null) {
map.put(name, attribute);
}
}
ATTRIBUTES = map;
}
private final String name;
Attribute(final String name) {
this.name = name;
}
Attribute() {
this.name = name().toLowerCase().replace('_', '-');
}
public static Attribute forName(String localName) {
final Attribute attribute = ATTRIBUTES.get(localName);
return attribute == null ? UNKNOWN : attribute;
}
@Override
public String toString() {
return name;
}
}
| 1,344
| 17.943662
| 60
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/SniConfiguration.java
|
package org.infinispan.server.core.configuration;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.configuration.attributes.ConfigurationElement;
/**
* @since 10.0
*/
public class SniConfiguration extends ConfigurationElement<SniConfiguration> {
static final AttributeDefinition<String> SECURITY_REALM = AttributeDefinition.builder("security-realm", null, String.class).build();
static final AttributeDefinition<String> HOST_NAME = AttributeDefinition.builder("host-name", null, String.class).build();
public static AttributeSet attributeDefinitionSet() {
return new AttributeSet(SniConfiguration.class, HOST_NAME, SECURITY_REALM);
}
SniConfiguration(AttributeSet attributes) {
super("sni", true, attributes);
}
public String realm() {
return attributes.attribute(SECURITY_REALM).get();
}
public String host() {
return attributes.attribute(HOST_NAME).get();
}
}
| 1,050
| 34.033333
| 135
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/EncryptionConfiguration.java
|
package org.infinispan.server.core.configuration;
import java.util.List;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.configuration.attributes.ConfigurationElement;
/**
* @since 10.0
*/
public class EncryptionConfiguration extends ConfigurationElement<EncryptionConfiguration> {
static final AttributeDefinition<String> SECURITY_REALM = AttributeDefinition.builder(Attribute.SECURITY_REALM, null, String.class).build();
static final AttributeDefinition<Boolean> REQUIRE_CLIENT_AUTH = AttributeDefinition.builder(Attribute.REQUIRE_SSL_CLIENT_AUTH, false, Boolean.class).build();
public static AttributeSet attributeDefinitionSet() {
return new AttributeSet(EncryptionConfiguration.class, REQUIRE_CLIENT_AUTH, SECURITY_REALM);
}
private final List<SniConfiguration> sniConfigurations;
EncryptionConfiguration(AttributeSet attributes, List<SniConfiguration> sniConfigurations) {
super("encryption", attributes, children(sniConfigurations));
this.sniConfigurations = sniConfigurations;
}
public List<SniConfiguration> sniConfigurations() {
return sniConfigurations;
}
public String realm() {
return attributes.attribute(SECURITY_REALM).get();
}
public boolean requireClientAuth() {
return attributes.attribute(REQUIRE_CLIENT_AUTH).get();
}
}
| 1,454
| 36.307692
| 160
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/SaslConfiguration.java
|
package org.infinispan.server.core.configuration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.security.auth.Subject;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSerializer;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.configuration.attributes.ConfigurationElement;
import org.infinispan.commons.configuration.attributes.PropertiesAttributeSerializer;
import org.infinispan.server.core.security.sasl.SaslAuthenticator;
/**
* @since 10.0
*/
@SuppressWarnings("unchecked")
public class SaslConfiguration extends ConfigurationElement<SaslConfiguration> {
public static final AttributeDefinition<String> SERVER_NAME = AttributeDefinition.builder(Attribute.SERVER_NAME, null, String.class).immutable().build();
public static final AttributeDefinition<Set<String>> MECHANISMS = AttributeDefinition.builder(Attribute.MECHANISMS, null, (Class<Set<String>>) (Class<?>) Set.class)
.initializer(LinkedHashSet::new).serializer(AttributeSerializer.STRING_COLLECTION).immutable().build();
public static final AttributeDefinition<List<org.infinispan.server.core.configuration.QOP>> QOP = AttributeDefinition.builder(Attribute.QOP, new ArrayList<>(), (Class<List<QOP>>) (Class<?>) List.class)
.initializer(ArrayList::new).serializer(AttributeSerializer.ENUM_COLLECTION).immutable().build();
public static final AttributeDefinition<List<Strength>> STRENGTH = AttributeDefinition.builder(Attribute.STRENGTH, new ArrayList<>(), (Class<List<Strength>>) (Class<?>) Strength.class)
.initializer(ArrayList::new).serializer(AttributeSerializer.ENUM_COLLECTION).immutable().build();
public static final AttributeDefinition<List<Policy>> POLICY = AttributeDefinition.builder(Attribute.POLICY, new ArrayList<>(), (Class<List<Policy>>) (Class<?>) Policy.class)
.initializer(ArrayList::new).serializer(AttributeSerializer.ENUM_COLLECTION).immutable().build();
static final AttributeDefinition<Map<String, String>> SASL_PROPERTIES = AttributeDefinition.builder(Element.PROPERTY, null, (Class<Map<String, String>>) (Class<?>) Map.class).initializer(LinkedHashMap::new)
.serializer(PropertiesAttributeSerializer.PROPERTIES).immutable().build();
static final AttributeDefinition<Subject> SERVER_SUBJECT = AttributeDefinition.builder(Element.SERVER_SUBJECT, null, Subject.class).autoPersist(false).immutable().build();
private final Map<String, String> mechProperties;
private final SaslAuthenticator authenticator;
public static AttributeSet attributeDefinitionSet() {
return new AttributeSet(SaslConfiguration.class, SERVER_NAME, MECHANISMS, QOP, STRENGTH, POLICY, SASL_PROPERTIES, SERVER_SUBJECT);
}
SaslConfiguration(AttributeSet attributes, SaslAuthenticator authenticator, Map<String, String> mechProperties) {
super(Element.SASL, attributes);
this.authenticator = authenticator;
this.mechProperties = mechProperties;
}
public Map<String, String> mechProperties() {
return mechProperties;
}
public String serverName() {
return attributes.attribute(SERVER_NAME).get();
}
public Set<String> mechanisms() {
return attributes.attribute(MECHANISMS).get();
}
public List<QOP> qop() {
return attributes.attribute(QOP).get();
}
public List<Strength> strength() {
return attributes.attribute(STRENGTH).get();
}
public SaslAuthenticator authenticator() {
return authenticator;
}
public Subject serverSubject() {
return attributes.attribute(SERVER_SUBJECT).get();
}
}
| 3,814
| 47.910256
| 209
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/NoAuthenticationConfigurationBuilder.java
|
package org.infinispan.server.core.configuration;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
/**
* @since 15.0
**/
public class NoAuthenticationConfigurationBuilder implements AuthenticationConfigurationBuilder<NoAuthenticationConfiguration> {
@Override
public NoAuthenticationConfiguration create() {
return new NoAuthenticationConfiguration();
}
@Override
public Builder<?> read(NoAuthenticationConfiguration template, Combine combine) {
return this;
}
@Override
public AttributeSet attributes() {
return AttributeSet.EMPTY;
}
@Override
public AuthenticationConfigurationBuilder<NoAuthenticationConfiguration> enable() {
return this;
}
@Override
public String securityRealm() {
return null;
}
}
| 912
| 24.361111
| 128
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/AbstractProtocolServerConfigurationChildBuilder.java
|
package org.infinispan.server.core.configuration;
import org.infinispan.server.core.admin.AdminOperationsHandler;
/**
* Helper
*
* @author Tristan Tarrant
* @since 9.1
*/
public abstract class AbstractProtocolServerConfigurationChildBuilder<T extends ProtocolServerConfiguration<T, A>, S extends ProtocolServerConfigurationChildBuilder<T, S, A>, A extends AuthenticationConfiguration>
implements ProtocolServerConfigurationChildBuilder<T, S, A> {
final protected ProtocolServerConfigurationChildBuilder<T, S, A> builder;
protected AbstractProtocolServerConfigurationChildBuilder(ProtocolServerConfigurationChildBuilder<T, S, A> builder) {
this.builder = builder;
}
@Override
public S defaultCacheName(String defaultCacheName) {
builder.defaultCacheName(defaultCacheName);
return self();
}
@Override
public S name(String name) {
builder.name(name);
return self();
}
@Override
public S host(String host) {
builder.host(host);
return self();
}
@Override
public S port(int port) {
builder.port(port);
return self();
}
@Override
public S idleTimeout(int idleTimeout) {
builder.idleTimeout(idleTimeout);
return self();
}
@Override
public S tcpNoDelay(boolean tcpNoDelay) {
builder.tcpNoDelay(tcpNoDelay);
return self();
}
@Override
public S tcpKeepAlive(boolean tcpKeepAlive) {
builder.tcpKeepAlive(tcpKeepAlive);
return self();
}
@Override
public S recvBufSize(int recvBufSize) {
builder.recvBufSize(recvBufSize);
return self();
}
@Override
public S sendBufSize(int sendBufSize) {
builder.sendBufSize(sendBufSize);
return self();
}
@Override
public AuthenticationConfigurationBuilder<A> authentication() {
return builder.authentication();
}
@Override
public SslConfigurationBuilder<T, S, A> ssl() {
return builder.ssl();
}
@Override
public S ioThreads(int ioThreads) {
builder.ioThreads(ioThreads);
return self();
}
@Override
public S startTransport(boolean startTransport) {
builder.startTransport(startTransport);
return self();
}
@Override
public S adminOperationsHandler(AdminOperationsHandler handler) {
builder.adminOperationsHandler(handler);
return self();
}
@Override
public S socketBinding(String name) {
builder.socketBinding(name);
return self();
}
@Override
public IpFilterConfigurationBuilder<T, S, A> ipFilter() {
return builder.ipFilter();
}
@Override
public S implicitConnector(boolean implicitConnector) {
builder.implicitConnector(implicitConnector);
return self();
}
@Override
public T build() {
return builder.build();
}
}
| 2,841
| 21.919355
| 213
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/Strength.java
|
package org.infinispan.server.core.configuration;
import static java.util.Arrays.stream;
/**
* @since 10.0
*/
public enum Strength {
LOW("low"), MEDIUM("medium"), HIGH("high");
private final String str;
Strength(String str) {
this.str = str;
}
@Override
public String toString() {
return str;
}
public static Strength fromString(String s) {
return stream(Strength.values())
.filter(q -> q.str.equalsIgnoreCase(s))
.findFirst().orElse(null);
}
}
| 523
| 17.068966
| 51
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/QOP.java
|
package org.infinispan.server.core.configuration;
import static java.util.Arrays.stream;
/**
* @since 10.0
*/
public enum QOP {
AUTH("auth"),
AUTH_INT("auth-int"),
AUTH_CONF("auth-conf");
private String v;
QOP(String v) {
this.v = v;
}
@Override
public String toString() {
return v;
}
public static QOP fromString(String s) {
return stream(QOP.values())
.filter(q -> q.v.equalsIgnoreCase(s))
.findFirst().orElse(null);
}
}
| 507
| 15.387097
| 49
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/IpFilterConfiguration.java
|
package org.infinispan.server.core.configuration;
import java.util.Collections;
import java.util.List;
import org.infinispan.server.core.transport.IpSubnetFilterRule;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public class IpFilterConfiguration {
private volatile List<IpSubnetFilterRule> rules;
public IpFilterConfiguration(List<IpSubnetFilterRule> rules) {
this.rules = rules;
}
public List<IpSubnetFilterRule> rules() {
return rules;
}
public void rules(List<IpSubnetFilterRule> rules) {
this.rules = Collections.unmodifiableList(rules);
}
@Override
public String toString() {
return "IpFilterConfiguration{" +
"rules=" + rules +
'}';
}
}
| 766
| 21.558824
| 65
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/Policy.java
|
package org.infinispan.server.core.configuration;
import static java.util.Arrays.stream;
import org.infinispan.commons.configuration.io.NamingStrategy;
/**
* @since 13.0
*/
public enum Policy {
FORWARD_SECRECY,
NO_ACTIVE,
NO_ANONYMOUS,
NO_DICTIONARY,
NO_PLAIN_TEXT,
PASS_CREDENTIALS;
private final String name;
Policy() {
this.name = NamingStrategy.KEBAB_CASE.convert(name().toLowerCase());
}
@Override
public String toString() {
return name;
}
public static Policy fromString(String s) {
return stream(Policy.values())
.filter(p -> p.name.equalsIgnoreCase(s))
.findFirst().orElse(null);
}
}
| 686
| 18.083333
| 74
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/configuration/SniConfigurationBuilder.java
|
package org.infinispan.server.core.configuration;
import java.util.function.Supplier;
import javax.net.ssl.SSLContext;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
/**
* @since 10.0
*/
public class SniConfigurationBuilder implements Builder<SniConfiguration> {
private final AttributeSet attributes;
private final SslConfigurationBuilder ssl;
SniConfigurationBuilder(SslConfigurationBuilder ssl) {
this.ssl = ssl;
this.attributes = SniConfiguration.attributeDefinitionSet();
}
@Override
public AttributeSet attributes() {
return attributes;
}
public SniConfigurationBuilder realm(String name) {
attributes.attribute(SniConfiguration.SECURITY_REALM).set(name);
return this;
}
public SniConfigurationBuilder host(String name) {
attributes.attribute(SniConfiguration.HOST_NAME).set(name);
ssl.sniHostName(name);
return this;
}
public SniConfigurationBuilder sslContext(SSLContext sslContext) {
ssl.sslContext(sslContext);
return this;
}
public SniConfigurationBuilder sslContext(Supplier<SSLContext> sslContext) {
ssl.sslContext(sslContext);
return this;
}
@Override
public SniConfiguration create() {
return new SniConfiguration(attributes.protect());
}
@Override
public SniConfigurationBuilder read(SniConfiguration template, Combine combine) {
attributes.read(template.attributes(), combine);
return this;
}
}
| 1,608
| 25.377049
| 84
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/UserPrincipal.java
|
package org.infinispan.server.core.security;
import java.security.Principal;
/**
* UserPrincipal. A {@link Principal} which denotes a user
*
* @author Tristan Tarrant
* @since 7.0
*/
public interface UserPrincipal extends Principal {
}
| 244
| 16.5
| 58
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/SubjectUserInfo.java
|
package org.infinispan.server.core.security;
import java.security.Principal;
import java.util.Collection;
import javax.security.auth.Subject;
public interface SubjectUserInfo {
/**
* Get the name for this user.
*/
String getUserName();
/**
* Get the principals for this user.
*/
Collection<Principal> getPrincipals();
/**
* Returns the subject
*/
Subject getSubject();
}
| 433
| 15.074074
| 44
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/InetAddressPrincipal.java
|
package org.infinispan.server.core.security;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.Principal;
import java.util.Objects;
/**
* InetAddressPrincipal.
*
* @author Tristan Tarrant
* @since 7.0
*/
public class InetAddressPrincipal implements Principal {
private final InetAddress address;
public InetAddressPrincipal(InetAddress address) {
if (address == null) {
throw new IllegalArgumentException("address is null");
}
try {
this.address = InetAddress.getByAddress(address.getHostAddress(), address.getAddress());
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
}
@Override
public String getName() {
return address.getHostAddress();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InetAddressPrincipal that = (InetAddressPrincipal) o;
return Objects.equals(address, that.address);
}
@Override
public int hashCode() {
return Objects.hash(address);
}
@Override
public String toString() {
return "InetAddressPrincipal [address=" + address + "]";
}
}
| 1,255
| 23.627451
| 97
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/UsernamePasswordAuthenticator.java
|
package org.infinispan.server.core.security;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.CompletionStage;
import javax.security.auth.Subject;
import org.infinispan.server.core.ProtocolServer;
/**
* Authentication mechanism.
*/
public interface UsernamePasswordAuthenticator extends Closeable {
/**
* Performs authentication using the supplied credentials and returns the authenticated {@link Subject}
*/
CompletionStage<Subject> authenticate(String username, char[] password);
/**
* Invoked by the {@link ProtocolServer} on startup. Can perform additional configuration
* @param server
*/
default void init(ProtocolServer<?> server) {}
@Override
default void close() throws IOException {
// No-op
}
}
| 796
| 23.151515
| 106
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/external/ExternalSaslServerFactory.java
|
package org.infinispan.server.core.security.external;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.x500.X500Principal;
import javax.security.sasl.SaslServer;
import javax.security.sasl.SaslServerFactory;
public final class ExternalSaslServerFactory implements SaslServerFactory {
public static final String[] NAMES = new String[]{"EXTERNAL"};
private final X500Principal peerPrincipal;
public ExternalSaslServerFactory(final X500Principal peerPrincipal) {
this.peerPrincipal = peerPrincipal;
}
public SaslServer createSaslServer(final String mechanism, final String protocol, final String serverName,
final Map<String, ?> props, final CallbackHandler cbh) {
return new ExternalSaslServer(cbh, peerPrincipal);
}
public String[] getMechanismNames(final Map<String, ?> props) {
return NAMES;
}
}
| 938
| 31.37931
| 109
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/external/ExternalSaslServer.java
|
package org.infinispan.server.core.security.external;
import static org.infinispan.server.core.security.sasl.SubjectSaslServer.SUBJECT;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.x500.X500Principal;
import javax.security.sasl.AuthorizeCallback;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import org.infinispan.commons.util.Util;
final class ExternalSaslServer implements SaslServer {
private final AtomicBoolean complete = new AtomicBoolean();
private String authorizationID;
private final X500Principal peerPrincipal;
private final CallbackHandler callbackHandler;
ExternalSaslServer(final CallbackHandler callbackHandler, final X500Principal peerPrincipal) {
this.callbackHandler = callbackHandler;
this.peerPrincipal = peerPrincipal;
}
public String getMechanismName() {
return "EXTERNAL";
}
public byte[] evaluateResponse(final byte[] response) throws SaslException {
if (complete.getAndSet(true)) {
throw new SaslException("Received response after complete");
}
String userName = new String(response, StandardCharsets.UTF_8);
if (userName.length() == 0) {
userName = peerPrincipal.getName();
}
final AuthorizeCallback authorizeCallback = new AuthorizeCallback(peerPrincipal.getName(), userName);
handleCallback(callbackHandler, authorizeCallback);
if (authorizeCallback.isAuthorized()) {
authorizationID = authorizeCallback.getAuthorizedID();
} else {
throw new SaslException("EXTERNAL: " + peerPrincipal.getName() + " is not authorized to act as " + userName);
}
return Util.EMPTY_BYTE_ARRAY;
}
private static void handleCallback(CallbackHandler handler, Callback callback) throws SaslException {
try {
handler.handle(new Callback[]{
callback,
});
} catch (SaslException e) {
throw e;
} catch (IOException e) {
throw new SaslException("Failed to authenticate due to callback exception", e);
} catch (UnsupportedCallbackException e) {
throw new SaslException("Failed to authenticate due to unsupported callback", e);
}
}
public boolean isComplete() {
return complete.get();
}
public String getAuthorizationID() {
return authorizationID;
}
public byte[] unwrap(final byte[] incoming, final int offset, final int len) throws SaslException {
throw new IllegalStateException();
}
public byte[] wrap(final byte[] outgoing, final int offset, final int len) throws SaslException {
throw new IllegalStateException();
}
public Object getNegotiatedProperty(final String propName) {
if (SUBJECT.equals(propName)) {
if (isComplete()) {
Subject subject = new Subject();
subject.getPrincipals().add(peerPrincipal);
return subject;
} else {
throw new IllegalStateException("Authentication is not complete");
}
} else {
return null;
}
}
public void dispose() throws SaslException {
}
}
| 3,442
| 33.089109
| 118
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/simple/SimpleGroupPrincipal.java
|
package org.infinispan.server.core.security.simple;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.security.Principal;
import org.infinispan.commons.marshall.SerializeWith;
/**
* SimpleGroupPrincipal.
*
* @author Tristan Tarrant
* @since 7.0
*/
@SerializeWith(SimpleGroupPrincipal.Externalizer.class)
public class SimpleGroupPrincipal implements Principal {
final String name;
public SimpleGroupPrincipal(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public String toString() {
return "SimpleGroupPrincipal [name=" + name + "]";
}
public static class Externalizer implements org.infinispan.commons.marshall.Externalizer<SimpleGroupPrincipal> {
@Override
public void writeObject(ObjectOutput output, SimpleGroupPrincipal object) throws IOException {
output.writeUTF(object.name);
}
@Override
public SimpleGroupPrincipal readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new SimpleGroupPrincipal(input.readUTF());
}
}
}
| 1,173
| 22.019608
| 115
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/simple/SimpleUserPrincipal.java
|
package org.infinispan.server.core.security.simple;
import org.infinispan.server.core.security.UserPrincipal;
/**
* SimpleUserPrincipal.
*
* @author Tristan Tarrant
* @since 7.0
*/
public final class SimpleUserPrincipal implements UserPrincipal {
private final String name;
public SimpleUserPrincipal(final String name) {
if (name == null) {
throw new IllegalArgumentException("name is null");
}
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object other) {
return other instanceof SimpleUserPrincipal && equals((SimpleUserPrincipal) other);
}
public boolean equals(SimpleUserPrincipal other) {
return this == other || other != null && name.equals(other.name);
}
@Override
public String toString() {
return "SimpleUserPrincipal [name=" + name + "]";
}
}
| 993
| 20.608696
| 89
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/simple/SimpleSaslAuthenticator.java
|
package org.infinispan.server.core.security.simple;
import java.io.IOException;
import java.security.Principal;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.x500.X500Principal;
import javax.security.sasl.AuthenticationException;
import javax.security.sasl.AuthorizeCallback;
import javax.security.sasl.RealmCallback;
import javax.security.sasl.RealmChoiceCallback;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import javax.security.sasl.SaslServerFactory;
import org.infinispan.commons.util.SaslUtils;
import org.infinispan.server.core.security.SubjectUserInfo;
import org.infinispan.server.core.security.external.ExternalSaslServerFactory;
import org.infinispan.server.core.security.sasl.AuthorizingCallbackHandler;
import org.infinispan.server.core.security.sasl.SaslAuthenticator;
import org.infinispan.server.core.security.sasl.SubjectSaslServer;
/**
* A server authentication handler which maintains a simple map of user names and passwords.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
* @author Tristan Tarrant
*/
public final class SimpleSaslAuthenticator implements SaslAuthenticator {
private final Map<String, Map<String, Entry>> map = new HashMap<>();
public SaslServer createSaslServer(String mechanism, List<Principal> principals, String protocol, String serverName, Map<String, String> props) throws SaslException {
AuthorizingCallbackHandler callbackHandler = getCallbackHandler();
if ("EXTERNAL".equals(mechanism)) {
// Find the X500Principal among the supplied principals
for (Principal principal : principals) {
if (principal instanceof X500Principal) {
ExternalSaslServerFactory factory = new ExternalSaslServerFactory((X500Principal) principal);
SaslServer saslServer = factory.createSaslServer(mechanism, protocol, serverName, props, callbackHandler);
return new SubjectSaslServer(saslServer, principals, callbackHandler);
}
}
throw new IllegalStateException("EXTERNAL mech requires X500Principal");
} else {
for (SaslServerFactory factory : SaslUtils.getSaslServerFactories(this.getClass().getClassLoader(), null, true)) {
if (factory != null) {
SaslServer saslServer = factory.createSaslServer(mechanism, protocol, serverName, props, callbackHandler);
if (saslServer != null) {
return new SubjectSaslServer(saslServer, principals, callbackHandler);
}
}
}
}
return null;
}
private AuthorizingCallbackHandler getCallbackHandler() {
return new AuthorizingCallbackHandler() {
final Subject subject = new Subject();
Principal userPrincipal;
public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException {
String userName = null;
String realmName = null;
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
final NameCallback nameCallback = (NameCallback) callback;
final String defaultName = nameCallback.getDefaultName();
userName = defaultName.toLowerCase().trim();
nameCallback.setName(userName);
userPrincipal = new SimpleUserPrincipal(userName);
subject.getPrincipals().add(userPrincipal);
} else if (callback instanceof RealmCallback) {
final RealmCallback realmCallback = (RealmCallback) callback;
final String defaultRealm = realmCallback.getDefaultText();
if (defaultRealm != null) {
realmName = defaultRealm.toLowerCase().trim();
realmCallback.setText(realmName);
}
} else if (callback instanceof RealmChoiceCallback) {
final RealmChoiceCallback realmChoiceCallback = (RealmChoiceCallback) callback;
realmChoiceCallback.setSelectedIndex(realmChoiceCallback.getDefaultChoice());
} else if (callback instanceof PasswordCallback) {
final PasswordCallback passwordCallback = (PasswordCallback) callback;
// retrieve the record based on user and realm (if any)
Entry entry = null;
if (realmName == null) {
// scan all realms
synchronized (map) {
for (Map<String, Entry> realmMap : map.values()) {
if (realmMap.containsKey(userName)) {
entry = realmMap.get(userName);
break;
}
}
}
} else {
synchronized (map) {
final Map<String, Entry> realmMap = map.get(realmName);
if (realmMap != null) {
entry = realmMap.get(userName);
}
}
}
if (entry == null) {
throw new AuthenticationException("No matching user found");
}
for (String group : entry.getGroups()) {
subject.getPrincipals().add(new SimpleGroupPrincipal(group));
}
passwordCallback.setPassword(entry.getPassword());
} else if (callback instanceof AuthorizeCallback) {
final AuthorizeCallback authorizeCallback = (AuthorizeCallback) callback;
authorizeCallback.setAuthorized(authorizeCallback.getAuthenticationID().equals(
authorizeCallback.getAuthorizationID()));
} else {
throw new UnsupportedCallbackException(callback, "Callback not supported: " + callback);
}
}
}
@Override
public SubjectUserInfo getSubjectUserInfo(Collection<Principal> principals) {
if (principals != null) {
subject.getPrincipals().addAll(principals);
}
if (userPrincipal != null) {
return new SimpleSubjectUserInfo(userPrincipal.getName(), subject);
} else {
return new SimpleSubjectUserInfo(subject);
}
}
};
}
/**
* Add a user to the authentication table.
*
* @param userName
* the user name
* @param userRealm
* the user realm
* @param password
* the password
* @param groups
* the groups the user belongs to
*/
public void addUser(String userName, String userRealm, char[] password, String... groups) {
if (userName == null) {
throw new IllegalArgumentException("userName is null");
}
if (userRealm == null) {
throw new IllegalArgumentException("userRealm is null");
}
if (password == null) {
throw new IllegalArgumentException("password is null");
}
final String canonUserRealm = userRealm.toLowerCase().trim();
final String canonUserName = userName.toLowerCase().trim();
synchronized (map) {
Map<String, Entry> realmMap = map.computeIfAbsent(canonUserRealm, k -> new HashMap<>());
realmMap.put(canonUserName, new Entry(canonUserName, canonUserRealm, password, groups != null ? groups : new String[0]));
}
}
private static final class Entry {
private final String userName;
private final String userRealm;
private final char[] password;
private final String[] groups;
private Entry(final String userName, final String userRealm, final char[] password, final String[] groups) {
this.userName = userName;
this.userRealm = userRealm;
this.password = password;
this.groups = groups;
}
String getUserName() {
return userName;
}
String getUserRealm() {
return userRealm;
}
char[] getPassword() {
return password;
}
String[] getGroups() {
return groups;
}
}
}
| 8,681
| 41.35122
| 169
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/simple/SimpleSubjectUserInfo.java
|
package org.infinispan.server.core.security.simple;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.security.Principal;
import java.util.Collection;
import javax.security.auth.Subject;
import org.infinispan.commons.marshall.SerializeWith;
import org.infinispan.security.Security;
import org.infinispan.server.core.security.SubjectUserInfo;
/**
* SimpleSubjectUserInfo.
*
* @author Tristan Tarrant
* @since 7.0
*/
@SerializeWith(SimpleSubjectUserInfo.Externalizer.class)
public class SimpleSubjectUserInfo implements SubjectUserInfo {
final String userName;
final Subject subject;
public SimpleSubjectUserInfo(Subject subject) {
this.userName = Security.getSubjectUserPrincipal(subject).getName();
this.subject = subject;
}
public SimpleSubjectUserInfo(String userName, Subject subject) {
this.userName = userName;
this.subject = subject;
}
@Override
public String getUserName() {
return userName;
}
@Override
public Collection<Principal> getPrincipals() {
return subject.getPrincipals();
}
@Override
public Subject getSubject() {
return subject;
}
public static class Externalizer implements org.infinispan.commons.marshall.Externalizer<SimpleSubjectUserInfo> {
@Override
public void writeObject(ObjectOutput output, SimpleSubjectUserInfo object) throws IOException {
output.writeUTF(object.userName);
output.writeObject(object.subject);
}
@Override
public SimpleSubjectUserInfo readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new SimpleSubjectUserInfo(input.readUTF(), (Subject)input.readObject());
}
}
}
| 1,778
| 25.954545
| 116
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/sasl/AuthorizingCallbackHandler.java
|
package org.infinispan.server.core.security.sasl;
import java.security.Principal;
import java.util.Collection;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import org.infinispan.server.core.security.SubjectUserInfo;
/**
* AuthorizingCallbackHandler. A {@link CallbackHandler} which allows retrieving the {@link Subject} which has been authorized wrapped in a {@link SubjectUserInfo}
*
* @author Tristan Tarrant
* @since 7.0
*/
public interface AuthorizingCallbackHandler extends CallbackHandler {
SubjectUserInfo getSubjectUserInfo(Collection<Principal> principals);
}
| 628
| 27.590909
| 163
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/sasl/SaslAuthenticator.java
|
package org.infinispan.server.core.security.sasl;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.security.auth.Subject;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import javax.security.sasl.SaslServerFactory;
import org.infinispan.server.core.configuration.SaslConfiguration;
import org.infinispan.server.core.logging.Log;
import org.infinispan.server.core.security.InetAddressPrincipal;
import io.netty.channel.Channel;
import io.netty.handler.ssl.SslHandler;
/**
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
* @author Tristan Tarrant
*/
public interface SaslAuthenticator {
/**
* Create a SaslServer, to be used for a single authentication session, for the specified mechanismName. On
* completion of the SASL authentication exchange, the SaslServer <b>MUST</b> provide a non-read-only negotiated
* {@link javax.security.auth.Subject} when {@link SaslServer#getNegotiatedProperty(String)} is invoked with the
* {@link SubjectSaslServer#SUBJECT} property. The default implementation of this method wraps any matching {@link
* SaslServerFactory} with a {@link SubjectSaslServer} to transparently supply the resolved Subject.
*
* @param mechanism The non-null IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param principals Any principals which can be obtained before the authentication (e.g. TLS peer, remote network
* address). Can be empty.
* @param protocol The non-null string name of the protocol for which the authentication is being performed (e.g.,
* "ldap").
* @param serverName The fully qualified host name of the server to authenticate to, or null if the server is not
* bound to any specific host name. If the mechanism does not allow an unbound server, a {@code
* SaslException} will be thrown.
* @param props The possibly null set of properties used to select the SASL mechanism and to configure the
* authentication exchange of the selected mechanism. See the {@code Sasl} class for a list of
* standard properties. Other, possibly mechanism-specific, properties can be included. Properties
* not relevant to the selected mechanism are ignored, including any map entries with non-String
* keys.
* @return an instance of SaslServer (or null if it cannot be created)
*/
default SaslServer createSaslServer(String mechanism, List<Principal> principals, String protocol, String serverName, Map<String, String> props) throws SaslException {
throw new UnsupportedOperationException();
}
static SaslServer createSaslServer(SaslConfiguration configuration, Channel channel, String mech, String protocol) throws Throwable {
SaslAuthenticator sap = configuration.authenticator();
return createSaslServer(sap, configuration, channel, mech, protocol);
}
static SaslServer createSaslServer(SaslAuthenticator sap, SaslConfiguration configuration, Channel channel, String mech, String protocol) throws Throwable {
List<Principal> principals = new ArrayList<>(2);
SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
if (sslHandler != null) {
try {
Principal peerPrincipal = sslHandler.engine().getSession().getPeerPrincipal();
principals.add(peerPrincipal);
} catch (SSLPeerUnverifiedException e) {
if ("EXTERNAL".equals(mech)) {
throw Log.SECURITY.externalMechNotAllowedWithoutSSLClientCert();
}
}
}
principals.add(new InetAddressPrincipal(((InetSocketAddress) channel.remoteAddress()).getAddress()));
if (configuration != null && configuration.serverSubject() != null) {
try {
// We must use Subject.doAs() here instead of Security.doAs()
return Subject.doAs(configuration.serverSubject(), (PrivilegedExceptionAction<SaslServer>) () ->
sap.createSaslServer(mech, principals, protocol, configuration.serverName(),
configuration.mechProperties()));
} catch (PrivilegedActionException e) {
throw e.getCause();
}
} else {
Map<String, String> mechProperties = configuration != null ? configuration.mechProperties() : null;
String serverName = configuration != null ? configuration.serverName() : null;
return sap.createSaslServer(mech, principals, protocol, serverName, mechProperties);
}
}
}
| 4,906
| 52.923077
| 170
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/security/sasl/SubjectSaslServer.java
|
package org.infinispan.server.core.security.sasl;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import javax.security.auth.Subject;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import org.infinispan.server.core.security.UserPrincipal;
import org.infinispan.server.core.security.simple.SimpleUserPrincipal;
/**
* A {@link SaslServer} which, when complete, can return a negotiated property named {@link #SUBJECT} which contains a
* populated {@link Subject} representing the authenticated user.
*
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.0
**/
public class SubjectSaslServer implements SaslServer {
public static final String SUBJECT = "org.infinispan.security.Subject";
protected final SaslServer delegate;
protected final AuthorizingCallbackHandler callbackHandler;
protected final List<Principal> principals;
public SubjectSaslServer(SaslServer delegate, List<Principal> principals, AuthorizingCallbackHandler callbackHandler) {
this.delegate = delegate;
this.principals = principals;
this.callbackHandler = callbackHandler;
}
@Override
public String getMechanismName() {
return delegate.getMechanismName();
}
@Override
public byte[] evaluateResponse(byte[] response) throws SaslException {
return delegate.evaluateResponse(response);
}
@Override
public boolean isComplete() {
return delegate.isComplete();
}
@Override
public String getAuthorizationID() {
return delegate.getAuthorizationID();
}
@Override
public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException {
return delegate.unwrap(incoming, offset, len);
}
@Override
public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException {
return delegate.wrap(outgoing, offset, len);
}
@Override
public Object getNegotiatedProperty(String propName) {
if (SUBJECT.equals(propName)) {
if (isComplete()) {
UserPrincipal userPrincipal = new SimpleUserPrincipal(normalizeAuthorizationId(getAuthorizationID()));
List<Principal> combinedPrincipals = new ArrayList<>(this.principals.size() + 1);
combinedPrincipals.add(userPrincipal);
combinedPrincipals.addAll(this.principals);
return callbackHandler.getSubjectUserInfo(combinedPrincipals).getSubject();
} else {
throw new IllegalStateException("Authentication is not complete");
}
} else {
return delegate.getNegotiatedProperty(propName);
}
}
@Override
public void dispose() throws SaslException {
delegate.dispose();
}
private static String normalizeAuthorizationId(String id) {
int realm = id.indexOf('@');
if (realm >= 0) return id.substring(0, realm);
else return id;
}
}
| 2,930
| 31.208791
| 122
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/telemetry/TelemetryServiceFactory.java
|
package org.infinispan.server.core.telemetry;
import java.util.Collections;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.factories.AbstractComponentFactory;
import org.infinispan.factories.AutoInstantiableFactory;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.server.core.telemetry.impl.OpenTelemetryService;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
@Scope(Scopes.GLOBAL)
@DefaultFactoryFor(classes = TelemetryService.class)
public class TelemetryServiceFactory extends AbstractComponentFactory implements AutoInstantiableFactory {
private static final Log log = LogFactory.getLog(TelemetryServiceFactory.class);
private static final String TRACING_ENABLED = System.getProperty("infinispan.tracing.enabled");
@Override
public Object construct(String name) {
if (TRACING_ENABLED == null || !"true".equalsIgnoreCase(TRACING_ENABLED.trim())) {
log.telemetryDisabled();
return null;
}
try {
OpenTelemetry openTelemetry = AutoConfiguredOpenTelemetrySdk.builder()
// At the moment we don't export Infinispan server metrics with OpenTelemetry,
// so we manually disable any metrics export
.addPropertiesSupplier(() -> Collections.singletonMap("otel.metrics.exporter", "none"))
.build()
.getOpenTelemetrySdk();
log.telemetryLoaded(openTelemetry);
return new OpenTelemetryService(openTelemetry);
} catch (Throwable e) {
log.errorOnLoadingTelemetry();
return null;
}
}
}
| 1,831
| 37.166667
| 106
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/telemetry/TelemetryService.java
|
package org.infinispan.server.core.telemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.context.propagation.TextMapGetter;
public interface TelemetryService {
<T> Span requestStart(String operationName, TextMapGetter<T> textMapGetter, T carrier);
void requestEnd(Object span);
void recordException(Object span, Throwable throwable);
class NoTelemetry implements TelemetryService {
@Override
public <T> Span requestStart(String operationName, TextMapGetter<T> textMapGetter, T carrier) {
return null;
}
@Override
public void requestEnd(Object span) {
// do nothing
}
@Override
public void recordException(Object span, Throwable throwable) {
// do nothing
}
}
}
| 787
| 23.625
| 101
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/telemetry/impl/OpenTelemetryService.java
|
package org.infinispan.server.core.telemetry.impl;
import org.infinispan.server.core.telemetry.TelemetryService;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.TextMapGetter;
public class OpenTelemetryService implements TelemetryService {
private static final String INFINISPAN_SERVER_TRACING_NAME = "org.infinispan.server.tracing";
private static final String INFINISPAN_SERVER_TRACING_VERSION = "1.0.0";
private final OpenTelemetry openTelemetry;
private final Tracer tracer;
public OpenTelemetryService(OpenTelemetry openTelemetry) {
this.openTelemetry = openTelemetry;
this.tracer = openTelemetry.getTracer(INFINISPAN_SERVER_TRACING_NAME, INFINISPAN_SERVER_TRACING_VERSION);
}
@Override
public <T> Span requestStart(String operationName, TextMapGetter<T> textMapGetter, T carrier) {
Context extractedContext = openTelemetry.getPropagators().getTextMapPropagator()
.extract(Context.current(), carrier, textMapGetter);
Span span = tracer.spanBuilder(operationName)
.setSpanKind(SpanKind.SERVER)
.setParent(extractedContext).startSpan();
return span;
}
@Override
public void requestEnd(Object span) {
((Span) span).end();
}
@Override
public void recordException(Object span, Throwable throwable) {
Span casted = (Span) span;
casted.setStatus(StatusCode.ERROR, "Error during the cache request processing");
casted.recordException(throwable);
}
}
| 1,744
| 34.612245
| 111
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/Constants.java
|
package org.infinispan.server.core.backup;
/**
* @author Ryan Emerson
* @since 12.0
*/
class Constants {
static final String CONTAINER_KEY = "containers";
static final String CONTAINERS_PROPERTIES_FILE = "container.properties";
static final String GLOBAL_CONFIG_FILE = "global.xml";
static final String MANIFEST_PROPERTIES_FILE = "manifest.properties";
static final String VERSION_KEY = "version";
static final String WORKING_DIR = "backups";
}
| 467
| 30.2
| 75
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/package-info.java
|
/*
* @api.private
*/
package org.infinispan.server.core.backup;
| 66
| 12.4
| 42
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/ContainerResource.java
|
package org.infinispan.server.core.backup;
import java.util.Properties;
import java.util.concurrent.CompletionStage;
import java.util.zip.ZipFile;
import org.infinispan.commons.CacheException;
import org.infinispan.server.core.BackupManager;
/**
* An interface that defines how a container resource is backed up and
* restored by the {@link org.infinispan.server.core.BackupManager}.
*
* @author Ryan Emerson
* @since 12.0
*/
public interface ContainerResource {
/**
* A method to ensure that the resources requested in the {@link BackupManager.Resources}
* are valid and can be included in a backup. This method is called for all {@link ContainerResource} implementations
* before the backup process begins in order to allow a backup to fail-fast before any data is processed.
*
* @throws CacheException if an invalid parameter is specified, e.g. a unknown resource name.
*/
void prepareAndValidateBackup() throws CacheException;
/**
* Writes the backup files for the {@link BackupManager.Resources.Type} to the local
* filesystem, where it can then be packaged for distribution.
* <p>
* Implementations of this method depend on content created by {@link #prepareAndValidateBackup()}.
*
* @return a {@link CompletionStage} that completes once the backup of this {@link
* BackupManager.Resources.Type} has finished.
*/
CompletionStage<Void> backup();
/**
* Writes the name of the individual resources that have been included in this backup. The {@link
* BackupManager.Resources.Type} associated with an implementation is the key, whilst the
* value is a csv of resource names.
* <p>
* Implementations of this method depend on state created by {@link #backup()}.
*
* @param properties the {@link Properties} instance to add the key/value property.
*/
void writeToManifest(Properties properties);
/**
* A method to ensure that the resources requested in the {@link BackupManager.Resources}
* are contained in the backup to be restored. This method is called for all {@link ContainerResource}
* implementations before the restore process begins in order to allow a restore to fail-fast before any state is
* restored to a container.
*/
void prepareAndValidateRestore(Properties properties);
/**
* Restores the {@link BackupManager.Resources.Type} content from the provided {@link
* ZipFile} to the target container.
*
* @param zip the {@link ZipFile} to restore content from.
* @return a {@link CompletionStage} that completes once the restoration of this {@link
* BackupManager.Resources.Type} has finished.
*/
CompletionStage<Void> restore(ZipFile zip);
}
| 2,735
| 39.235294
| 120
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/BackupManagerImpl.java
|
package org.infinispan.server.core.backup;
import static org.infinispan.server.core.backup.Constants.WORKING_DIR;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.configuration.parsing.ParserRegistry;
import org.infinispan.lock.EmbeddedClusteredLockManagerFactory;
import org.infinispan.lock.api.ClusteredLock;
import org.infinispan.lock.api.ClusteredLockManager;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.security.AuthorizationPermission;
import org.infinispan.security.Security;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.core.BackupManager;
import org.infinispan.server.core.logging.Log;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.LogFactory;
/**
* @author Ryan Emerson
* @since 12.0
*/
public class BackupManagerImpl implements BackupManager {
private static final Log log = LogFactory.getLog(BackupManagerImpl.class, Log.class);
final ParserRegistry parserRegistry;
final BlockingManager blockingManager;
final Path rootDir;
final BackupReader reader;
final Lock backupLock;
final Lock restoreLock;
private final EmbeddedCacheManager cacheManager;
final Map<String, DefaultCacheManager> cacheManagers;
final Map<String, BackupRequest> backupMap;
final Map<String, CompletionStage<Void>> restoreMap;
public BackupManagerImpl(BlockingManager blockingManager, DefaultCacheManager cm, Path dataRoot) {
this.blockingManager = blockingManager;
this.rootDir = dataRoot.resolve(WORKING_DIR);
this.cacheManager = cm;
this.cacheManagers = Collections.singletonMap(cm.getName(), cm);
this.parserRegistry = new ParserRegistry();
this.reader = new BackupReader(blockingManager, cacheManagers, parserRegistry);
this.backupLock = new Lock("backup", cm);
this.restoreLock = new Lock("restore", cm);
this.backupMap = new ConcurrentHashMap<>();
this.restoreMap = new ConcurrentHashMap<>();
}
@Override
public void init() throws IOException {
Files.createDirectories(rootDir);
}
@Override
public Set<String> getBackupNames() {
SecurityActions.checkPermission(cacheManager.withSubject(Security.getSubject()), AuthorizationPermission.ADMIN);
return new HashSet<>(backupMap.keySet());
}
@Override
public Status getBackupStatus(String name) {
SecurityActions.checkPermission(cacheManager.withSubject(Security.getSubject()), AuthorizationPermission.ADMIN);
Status status = getBackupStatus(backupMap.get(name));
log.tracef("Backup status %s = %s", name, status);
return status;
}
@Override
public Path getBackupLocation(String name) {
SecurityActions.checkPermission(cacheManager.withSubject(Security.getSubject()), AuthorizationPermission.ADMIN);
BackupRequest request = backupMap.get(name);
Status status = getBackupStatus(request);
if (status != Status.COMPLETE)
return null;
return request.future.join();
}
private Status getBackupStatus(BackupRequest request) {
CompletableFuture<Path> future = request == null ? null : request.future;
return getFutureStatus(future);
}
private Status getFutureStatus(CompletionStage<?> stage) {
if (stage == null)
return Status.NOT_FOUND;
CompletableFuture<?> future = stage.toCompletableFuture();
if (future.isCompletedExceptionally())
return Status.FAILED;
return future.isDone() ? Status.COMPLETE : Status.IN_PROGRESS;
}
@Override
public CompletionStage<Status> removeBackup(String name) {
SecurityActions.checkPermission(cacheManager.withSubject(Security.getSubject()), AuthorizationPermission.ADMIN);
BackupRequest request = backupMap.get(name);
Status status = getBackupStatus(request);
switch (status) {
case NOT_FOUND:
backupMap.remove(name);
return CompletableFuture.completedFuture(status);
case COMPLETE:
case FAILED:
backupMap.remove(name);
return blockingManager.supplyBlocking(() -> {
request.writer.cleanup();
return Status.COMPLETE;
}, "remove-completed-backup");
case IN_PROGRESS:
// The backup files are removed on exceptional or successful completion.
blockingManager.handleBlocking(request.future, (path, t) -> {
// Regardless of whether the backup completes exceptionally or successfully, we remove the files
request.writer.cleanup();
return null;
}, "remove-inprogress-backup");
return CompletableFuture.completedFuture(Status.IN_PROGRESS);
}
throw new IllegalStateException();
}
@Override
public CompletionStage<Path> create(String name, Path workingDir) {
return create(
name,
workingDir,
cacheManagers.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
p -> new BackupManagerResources.Builder().includeAll().build()))
);
}
@Override
public CompletionStage<Path> create(String name, Path workingDir, Map<String, Resources> params) {
SecurityActions.checkPermission(cacheManager.withSubject(Security.getSubject()), AuthorizationPermission.ADMIN);
if (getBackupStatus(name) != Status.NOT_FOUND)
return CompletableFuture.failedFuture(log.backupAlreadyExists(name));
BackupWriter writer = new BackupWriter(name, blockingManager, cacheManagers, parserRegistry, workingDir == null ? rootDir : workingDir);
CompletionStage<Path> backupStage = backupLock.lock()
.thenCompose(lockAcquired -> {
log.tracef("Backup %s locked = %s", backupLock, lockAcquired);
if (!lockAcquired)
return CompletableFuture.failedFuture(log.backupInProgress());
log.initiatingBackup(name);
return writer.create(params);
});
backupStage = CompletionStages.handleAndCompose(backupStage,
(path, t) -> {
CompletionStage<Void> unlock = backupLock.unlock().thenAccept(v -> log.tracef("Backup %s unlocked", backupLock));
if (t != null) {
Throwable backupErr = log.errorCreatingBackup(t);
log.errorf(backupErr.getCause(), "%s:", backupErr.getMessage());
return unlock.thenCompose(ignore ->
CompletableFuture.failedFuture(backupErr)
);
}
log.backupComplete(path.getFileName().toString());
return unlock.thenCompose(ignore -> CompletableFuture.completedFuture(path));
});
backupMap.put(name, new BackupRequest(writer, backupStage));
return backupStage;
}
@Override
public CompletionStage<Status> removeRestore(String name) {
SecurityActions.checkPermission(cacheManager.withSubject(Security.getSubject()), AuthorizationPermission.ADMIN);
CompletionStage<Void> stage = restoreMap.remove(name);
Status status = getFutureStatus(stage);
return CompletableFuture.completedFuture(status);
}
@Override
public Status getRestoreStatus(String name) {
SecurityActions.checkPermission(cacheManager.withSubject(Security.getSubject()), AuthorizationPermission.ADMIN);
return getFutureStatus(restoreMap.get(name));
}
@Override
public Set<String> getRestoreNames() {
SecurityActions.checkPermission(cacheManager.withSubject(Security.getSubject()), AuthorizationPermission.ADMIN);
return new HashSet<>(restoreMap.keySet());
}
@Override
public CompletionStage<Void> restore(String name, Path backup) {
return restore(
name,
backup,
cacheManagers.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
p -> new BackupManagerResources.Builder().includeAll().build()))
);
}
@Override
public CompletionStage<Void> restore(String name, Path backup, Map<String, Resources> params) {
SecurityActions.checkPermission(cacheManager.withSubject(Security.getSubject()), AuthorizationPermission.ADMIN);
if (getRestoreStatus(name) != Status.NOT_FOUND)
return CompletableFuture.failedFuture(log.restoreAlreadyExists(name));
if (!Files.exists(backup)) {
CacheException e = log.errorRestoringBackup(backup, new FileNotFoundException(backup.toString()));
log.errorf(e.getCause(), "%s:", e.getMessage());
return CompletableFuture.failedFuture(e);
}
CompletionStage<Void> restoreStage = restoreLock.lock()
.thenCompose(lockAcquired -> {
if (!lockAcquired)
return CompletableFuture.failedFuture(log.restoreInProgress());
log.initiatingRestore(name, backup);
return reader.restore(backup, params);
});
restoreStage = CompletionStages.handleAndCompose(restoreStage,
(path, t) -> {
CompletionStage<Void> unlock = restoreLock.unlock();
if (t != null) {
Throwable restoreErr = log.errorRestoringBackup(backup, t);
log.errorf(restoreErr.getCause(), "%s:", restoreErr.getMessage());
return unlock.thenCompose(ignore ->
CompletableFuture.failedFuture(restoreErr)
);
}
log.restoreComplete(name);
return unlock.thenCompose(ignore -> CompletableFuture.completedFuture(path));
});
restoreMap.put(name, restoreStage);
return restoreStage;
}
static class BackupRequest {
final BackupWriter writer;
final CompletableFuture<Path> future;
BackupRequest(BackupWriter writer, CompletionStage<Path> stage) {
this.writer = writer;
this.future = stage.toCompletableFuture();
}
}
static class Lock {
final String name;
final EmbeddedCacheManager cm;
final boolean isClustered;
volatile ClusteredLock clusteredLock;
volatile AtomicBoolean localLock;
Lock(String name, EmbeddedCacheManager cm) {
this.name = String.format("%s-%s", BackupManagerImpl.class.getSimpleName(), name);
this.cm = cm;
this.isClustered = SecurityActions.getCacheManagerConfiguration(cm).isClustered();
}
CompletionStage<Boolean> lock() {
if (isClustered)
return getClusteredLock().tryLock();
return CompletableFuture.completedFuture(getLocalLock().compareAndSet(false, true));
}
CompletionStage<Void> unlock() {
if (isClustered)
return getClusteredLock().unlock();
getLocalLock().compareAndSet(true, false);
return CompletableFutures.completedNull();
}
private ClusteredLock getClusteredLock() {
if (clusteredLock == null) {
synchronized (this) {
if (clusteredLock == null) {
ClusteredLockManager lockManager = EmbeddedClusteredLockManagerFactory.from(cm);
boolean isDefined = lockManager.isDefined(name);
if (!isDefined) {
lockManager.defineLock(name);
}
clusteredLock = lockManager.get(name);
}
}
}
return clusteredLock;
}
private AtomicBoolean getLocalLock() {
if (localLock == null)
localLock = new AtomicBoolean();
return localLock;
}
@Override
public String toString() {
return "Lock{" +
"name='" + name + '\'' +
", isClustered=" + isClustered +
'}';
}
}
}
| 12,638
| 37.533537
| 142
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/BackupWriter.java
|
package org.infinispan.server.core.backup;
import static org.infinispan.server.core.backup.Constants.CONTAINERS_PROPERTIES_FILE;
import static org.infinispan.server.core.backup.Constants.CONTAINER_KEY;
import static org.infinispan.server.core.backup.Constants.GLOBAL_CONFIG_FILE;
import static org.infinispan.server.core.backup.Constants.MANIFEST_PROPERTIES_FILE;
import static org.infinispan.server.core.backup.Constants.VERSION_KEY;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.configuration.io.ConfigurationWriter;
import org.infinispan.commons.util.Util;
import org.infinispan.commons.util.Version;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.parsing.ParserRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.core.BackupManager;
import org.infinispan.server.core.backup.resources.ContainerResourceFactory;
import org.infinispan.server.core.logging.Log;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.LogFactory;
/**
* Responsible for creating backup files that can be used to restore a container/cache on a new cluster.
*
* @author Ryan Emerson
* @since 12.0
*/
class BackupWriter {
private static final Log log = LogFactory.getLog(BackupWriter.class, Log.class);
private final String name;
private final BlockingManager blockingManager;
private final Map<String, DefaultCacheManager> cacheManagers;
private final ParserRegistry parserRegistry;
private final Path rootDir;
BackupWriter(String name, BlockingManager blockingManager, Map<String, DefaultCacheManager> cacheManagers,
ParserRegistry parserRegistry, Path rootDir) {
this.name = name;
this.blockingManager = blockingManager;
this.cacheManagers = cacheManagers;
this.parserRegistry = parserRegistry;
this.rootDir = rootDir.resolve(name);
}
void cleanup() {
log.backupDeleted(name);
Util.recursiveFileRemove(rootDir);
}
CompletionStage<Path> create(Map<String, BackupManager.Resources> params) {
AggregateCompletionStage<Void> stages = CompletionStages.aggregateCompletionStage();
for (Map.Entry<String, BackupManager.Resources> e : params.entrySet()) {
String containerName = e.getKey();
EmbeddedCacheManager cm = cacheManagers.get(containerName);
stages.dependsOn(createBackup(containerName, cm, e.getValue()));
}
stages.dependsOn(writeManifest(cacheManagers.keySet()));
return blockingManager.thenApplyBlocking(stages.freeze(), Void -> createZip(), "create");
}
/**
* Create a backup of the specified container.
*
* @param containerName the name of container to backup.
* @param cm the container to backup.
* @param params the {@link BackupManager.Resources} object that determines what resources are included in the
* backup for this container.
* @return a {@link CompletionStage} that completes once the backup has finished.
*/
private CompletionStage<Void> createBackup(String containerName, EmbeddedCacheManager cm, BackupManager.Resources params) {
Path containerRoot = rootDir.resolve(CONTAINER_KEY).resolve(containerName);
try {
Files.createDirectories(containerRoot);
} catch (IOException e) {
throw new CacheException("Unable to create directories " + containerRoot);
}
GlobalComponentRegistry gcr = SecurityActions.getGlobalComponentRegistry(cm);
BlockingManager blockingManager = gcr.getComponent(BlockingManager.class);
Collection<ContainerResource> resources = ContainerResourceFactory
.getResources(params, blockingManager, cm, gcr, parserRegistry, containerRoot);
CompletionStage<Void> prepareStage = blockingManager.runBlocking(() -> {
// Prepare and ensure all requested resources are valid before starting the backup process
resources.forEach(ContainerResource::prepareAndValidateBackup);
}, "backupWriter - prepare");
return prepareStage.thenCompose(ignore -> {
AggregateCompletionStage<Void> stages = CompletionStages.aggregateCompletionStage();
for (ContainerResource cr : resources)
stages.dependsOn(cr.backup());
stages.dependsOn(
// Write the global configuration xml
blockingManager.runBlocking(() ->
writeGlobalConfig(SecurityActions.getCacheManagerConfiguration(cm), containerRoot), "backupWriter - writeGlobalConfig")
);
return blockingManager.thenRunBlocking(
stages.freeze(),
() -> {
Properties manifest = new Properties();
resources.forEach(r -> r.writeToManifest(manifest));
storeProperties(manifest, "Container Properties", containerRoot.resolve(CONTAINERS_PROPERTIES_FILE));
},
"backupWriter - createManifest"
);
});
}
private CompletionStage<Void> writeManifest(Set<String> containers) {
return blockingManager.runBlocking(() -> {
Properties manifest = new Properties();
manifest.put(CONTAINER_KEY, String.join(",", containers));
manifest.put(VERSION_KEY, Version.getVersion());
storeProperties(manifest, "Backup Manifest", rootDir.resolve(MANIFEST_PROPERTIES_FILE));
}, "write-manifest");
}
private void writeGlobalConfig(GlobalConfiguration configuration, Path root) {
Path xmlPath = root.resolve(GLOBAL_CONFIG_FILE);
try (ConfigurationWriter writer = ConfigurationWriter.to(Files.newOutputStream(xmlPath)).clearTextSecrets(true).prettyPrint(true).build()) {
parserRegistry.serialize(writer, configuration, Collections.emptyMap());
} catch (Exception e) {
throw new CacheException(String.format("Unable to create global configuration file '%s'", xmlPath), e);
}
}
private Path createZip() {
Path zipFile = rootDir.resolve(name + ".zip");
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(Files.createFile(zipFile)))) {
Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
if (!path.equals(zipFile)) {
String name = rootDir.relativize(path).toString();
zs.putNextEntry(new ZipEntry(name));
Files.copy(path, zs);
zs.closeEntry();
Files.delete(path);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null)
throw new IllegalStateException(exc);
if (!dir.equals(rootDir))
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
throw new CacheException(e);
}
return zipFile;
}
private void storeProperties(Properties properties, String description, Path dest) {
try (OutputStream os = Files.newOutputStream(dest)) {
properties.store(os, description);
} catch (IOException e) {
throw new CacheException(String.format("Unable to create %s file", description), e);
}
}
}
| 8,358
| 42.310881
| 146
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/BackupManagerResources.java
|
package org.infinispan.server.core.backup;
import static org.infinispan.server.core.BackupManager.Resources.Type.CACHES;
import static org.infinispan.server.core.BackupManager.Resources.Type.TEMPLATES;
import static org.infinispan.server.core.BackupManager.Resources.Type.COUNTERS;
import static org.infinispan.server.core.BackupManager.Resources.Type.PROTO_SCHEMAS;
import static org.infinispan.server.core.BackupManager.Resources.Type.TASKS;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.infinispan.server.core.BackupManager;
/**
* @author Ryan Emerson
* @since 12.0
*/
public class BackupManagerResources implements BackupManager.Resources {
final Map<Type, Set<String>> resources;
public BackupManagerResources(Map<Type, Set<String>> resources) {
this.resources = resources;
}
@Override
public Set<Type> includeTypes() {
return resources.keySet();
}
@Override
public Set<String> getQualifiedResources(Type type) {
Set<String> qualified = resources.get(type);
return qualified.isEmpty() ? null : qualified;
}
public static class Builder {
final Map<Type, Set<String>> resources = new HashMap<>();
public Builder includeAll() {
return includeAll(BackupManager.Resources.Type.values());
}
public Builder includeAll(Type... resources) {
for (Type resource : resources)
addResources(resource);
return this;
}
public Builder ignore(Type... resources) {
for (Type resource : resources)
this.resources.remove(resource);
return this;
}
public Builder addCaches(String... caches) {
return addResources(CACHES, caches);
}
public Builder addCacheConfigurations(String... configs) {
return addResources(TEMPLATES, configs);
}
public Builder addCounters(String... counters) {
return addResources(COUNTERS, counters);
}
public Builder addProtoSchemas(String... schemas) {
return addResources(PROTO_SCHEMAS, schemas);
}
public Builder addScripts(String... scripts) {
return addResources(TASKS, scripts);
}
public Builder addResources(Type resource, String... resources) {
return addResources(resource, Arrays.asList(resources));
}
public Builder addResources(Type resource, Collection<String> resources) {
this.resources.compute(resource, (k, v) -> {
Set<String> set = v == null ? new HashSet<>() : v;
set.addAll(resources);
return set;
});
return this;
}
public BackupManagerResources build() {
return new BackupManagerResources(resources);
}
}
}
| 2,864
| 28.234694
| 84
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/BackupReader.java
|
package org.infinispan.server.core.backup;
import static org.infinispan.server.core.backup.Constants.CONTAINERS_PROPERTIES_FILE;
import static org.infinispan.server.core.backup.Constants.CONTAINER_KEY;
import static org.infinispan.server.core.backup.Constants.MANIFEST_PROPERTIES_FILE;
import static org.infinispan.server.core.backup.Constants.VERSION_KEY;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.zip.ZipFile;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.Version;
import org.infinispan.configuration.parsing.ParserRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.core.BackupManager;
import org.infinispan.server.core.backup.resources.ContainerResourceFactory;
import org.infinispan.server.core.logging.Log;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.concurrent.CompletionStages;
/**
* Responsible for reading backup bytes and restoring the contents to the appropriate cache manager.
*
* @author Ryan Emerson
* @since 12.0
*/
class BackupReader {
private static final Log log = LogFactory.getLog(BackupReader.class, Log.class);
private final BlockingManager blockingManager;
private final Map<String, DefaultCacheManager> cacheManagers;
private final ParserRegistry parserRegistry;
public BackupReader(BlockingManager blockingManager, Map<String, DefaultCacheManager> cacheManagers,
ParserRegistry parserRegistry) {
this.blockingManager = blockingManager;
this.cacheManagers = cacheManagers;
this.parserRegistry = parserRegistry;
}
CompletionStage<Void> restore(Path backup, Map<String, BackupManager.Resources> params) {
return blockingManager.runBlocking(() -> {
try (ZipFile zip = new ZipFile(backup.toFile())) {
Properties manifest = readManifestAndValidate(zip);
List<String> backupContainers = Arrays.asList(manifest.getProperty(CONTAINER_KEY).split(","));
Set<String> requestedContainers = new HashSet<>(params.keySet());
requestedContainers.removeAll(backupContainers);
if (!requestedContainers.isEmpty()) {
throw log.unableToFindBackupResource("Containers", requestedContainers);
}
AggregateCompletionStage<Void> stages = CompletionStages.aggregateCompletionStage();
for (Map.Entry<String, BackupManager.Resources> e : params.entrySet()) {
stages.dependsOn(restoreContainer(e.getKey(), e.getValue(), zip));
}
CompletionStages.join(stages.freeze());
} catch (IOException e) {
throw new CacheException(String.format("Unable to read zip file '%s'", backup));
}
}, "process-containers");
}
private CompletionStage<Void> restoreContainer(String containerName, BackupManager.Resources params, ZipFile zip) {
// TODO validate container config
EmbeddedCacheManager cm = cacheManagers.get(containerName);
GlobalComponentRegistry gcr = SecurityActions.getGlobalComponentRegistry(cm);
Path containerRoot = Paths.get(CONTAINER_KEY, containerName);
Properties properties = readProperties(containerRoot.resolve(CONTAINERS_PROPERTIES_FILE), zip);
Collection<ContainerResource> resources = ContainerResourceFactory
.getResources(params, blockingManager, cm, gcr, parserRegistry, containerRoot);
resources.forEach(r -> r.prepareAndValidateRestore(properties));
AggregateCompletionStage<Void> stages = CompletionStages.aggregateCompletionStage();
for (ContainerResource cr : resources)
stages.dependsOn(cr.restore(zip));
return stages.freeze();
}
private Properties readManifestAndValidate(ZipFile zip) {
Path manifestPath = Paths.get(MANIFEST_PROPERTIES_FILE);
Properties properties = readProperties(manifestPath, zip);
String version = properties.getProperty(VERSION_KEY);
if (version == null)
throw new IllegalStateException("Missing manifest version");
int majorVersion = Integer.parseInt(version.split("[\\.\\-]")[0]);
// TODO replace with check that version difference is in the supported range, i.e. across 3 majors etc
if (majorVersion < 12)
throw new CacheException(String.format("Unable to restore from a backup as '%s' is no longer supported in '%s %s'",
version, Version.getBrandName(), Version.getVersion()));
return properties;
}
private Properties readProperties(Path file, ZipFile zip) {
try (InputStream is = zip.getInputStream(zip.getEntry(file.toString()))) {
Properties props = new Properties();
props.load(is);
return props;
} catch (IOException e) {
throw new CacheException("Unable to read properties file", e);
}
}
}
| 5,458
| 42.672
| 124
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/resources/ContainerResourceFactory.java
|
package org.infinispan.server.core.backup.resources;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.configuration.parsing.ParserRegistry;
import org.infinispan.counter.api.CounterManager;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.server.core.BackupManager;
import org.infinispan.server.core.backup.ContainerResource;
import org.infinispan.server.core.logging.Log;
import org.infinispan.util.concurrent.BlockingManager;
/**
* Factory for creating the {@link ContainerResource}s required for a backup/restore operation.
*
* @author Ryan Emerson
* @since 12.0
*/
public class ContainerResourceFactory {
private static final Log log = LogFactory.getLog(ContainerResourceFactory.class, Log.class);
public static Collection<ContainerResource> getResources(BackupManager.Resources params, BlockingManager blockingManager,
EmbeddedCacheManager cm, GlobalComponentRegistry gcr, ParserRegistry parserRegistry,
Path containerRoot) {
return params.includeTypes().stream()
.map(type -> {
switch (type) {
case CACHES:
return new CacheResource(blockingManager, parserRegistry, cm, params, containerRoot);
case TEMPLATES:
return new CacheConfigResource(blockingManager, parserRegistry, cm, params, containerRoot);
case COUNTERS:
CounterManager counterManager = gcr.getComponent(CounterManager.class);
return counterManager == null ?
missingResource(type) :
new CounterResource(counterManager, blockingManager, gcr.getComponent(SerializationContextRegistry.class).getPersistenceCtx(), params, containerRoot);
case PROTO_SCHEMAS:
case TASKS:
ContainerResource cr = InternalCacheResource.create(type, blockingManager, cm, params, containerRoot);
return cr == null ? missingResource(type) : cr;
default:
throw new IllegalStateException();
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
private static ContainerResource missingResource(BackupManager.Resources.Type type) {
log.debugf("Unable to process resource '%s' as the required modules are not on the server's classpath'", type);
return null;
}
}
| 2,859
| 45.885246
| 177
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/resources/InternalCacheResource.java
|
package org.infinispan.server.core.backup.resources;
import static org.infinispan.server.core.BackupManager.Resources.Type.PROTO_SCHEMAS;
import static org.infinispan.server.core.BackupManager.Resources.Type.TASKS;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
import java.util.zip.ZipFile;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.CacheException;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.core.BackupManager;
import org.infinispan.server.core.backup.ContainerResource;
import org.infinispan.util.concurrent.BlockingManager;
/**
* {@link org.infinispan.server.core.backup.ContainerResource} implementation for {@link
* BackupManager.Resources.Type#PROTO_SCHEMAS} and {@link BackupManager.Resources.Type#TASKS}.
*
* @author Ryan Emerson
* @since 12.0
*/
class InternalCacheResource extends AbstractContainerResource {
private static final Map<BackupManager.Resources.Type, String> cacheMap = new HashMap<>(2);
static {
cacheMap.put(PROTO_SCHEMAS, "___protobuf_metadata");
cacheMap.put(TASKS, "___script_cache");
}
private final AdvancedCache<String, String> cache;
private InternalCacheResource(BackupManager.Resources.Type type, AdvancedCache<String, String> cache,
BlockingManager blockingManager, BackupManager.Resources params, Path root) {
super(type, params, blockingManager, root);
this.cache = cache;
}
static ContainerResource create(BackupManager.Resources.Type type, BlockingManager blockingManager, EmbeddedCacheManager cm,
BackupManager.Resources params, Path root) {
String cacheName = cacheMap.get(type);
if (SecurityActions.getCacheConfiguration(cm, cacheName) == null)
return null;
AdvancedCache<String, String> cache = SecurityActions.getUnwrappedCache(cm.getCache(cacheName));
return new InternalCacheResource(type, cache, blockingManager, params, root);
}
@Override
public void prepareAndValidateBackup() {
if (wildcard) {
resources.addAll(cache.keySet());
return;
}
for (String fileName : resources) {
if (!cache.containsKey(fileName))
throw log.unableToFindResource(type.toString(), fileName);
}
}
@Override
public CompletionStage<Void> backup() {
return blockingManager.runBlocking(() -> {
mkdirs(root);
for (Map.Entry<String, String> entry : cache.entrySet()) {
String fileName = entry.getKey();
if (resources.contains(fileName)) {
Path file = root.resolve(fileName);
try {
// ISPN-13591 Create directory structure if resource name contains path separator
Path parent = file.getParent();
if (!parent.equals(root)) {
Files.createDirectories(parent);
}
Files.write(file, entry.getValue().getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new CacheException(String.format("Unable to create %s", file), e);
}
log.debugf("Backup up %s %s", type, fileName);
}
}
}, "write-" + type.toString());
}
@Override
public CompletionStage<Void> restore(ZipFile zip) {
return blockingManager.runBlocking(() -> {
for (String file : resources) {
String zipPath = root.resolve(file).toString();
try (InputStream is = zip.getInputStream(zip.getEntry(zipPath));
BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
String content = reader.lines().collect(Collectors.joining("\n"));
cache.put(file, content);
log.debugf("Restoring %s %s", type, file);
} catch (IOException e) {
throw new CacheException(e);
}
}
}, "restore-" + type.toString());
}
}
| 4,401
| 37.278261
| 127
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/resources/CacheConfigResource.java
|
package org.infinispan.server.core.backup.resources;
import static org.infinispan.server.core.BackupManager.Resources.Type.TEMPLATES;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.configuration.io.ConfigurationReader;
import org.infinispan.commons.configuration.io.NamingStrategy;
import org.infinispan.configuration.ConfigurationManager;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.parsing.CacheParser;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.configuration.parsing.ParserRegistry;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.core.BackupManager;
import org.infinispan.util.concurrent.BlockingManager;
/**
* {@link org.infinispan.server.core.backup.ContainerResource} implementation for {@link
* BackupManager.Resources.Type#TEMPLATES}.
*
* @author Ryan Emerson
* @since 12.0
*/
class CacheConfigResource extends AbstractContainerResource {
private final ParserRegistry parserRegistry;
private final EmbeddedCacheManager cm;
CacheConfigResource(BlockingManager blockingManager, ParserRegistry parserRegistry, EmbeddedCacheManager cm,
BackupManager.Resources params, Path root) {
super(TEMPLATES, params, blockingManager, root);
this.cm = cm;
this.parserRegistry = parserRegistry;
}
@Override
public void prepareAndValidateBackup() {
Set<String> configs = wildcard ? cm.getCacheConfigurationNames() : resources;
for (String configName : configs) {
Configuration config = SecurityActions.getCacheConfiguration(cm, configName);
if (wildcard) {
// For wildcard resources, we ignore internal caches, however explicitly requested internal caches are allowed
if (!config.isTemplate()) {
continue;
}
resources.add(configName);
} else if (config == null) {
throw log.unableToFindResource(type.toString(), configName);
} else if (!config.isTemplate()) {
throw new CacheException(String.format("Unable to backup %s '%s' as it is not a template", type, configName));
}
}
}
@Override
public CompletionStage<Void> backup() {
return blockingManager.runBlocking(() -> {
mkdirs(root);
for (String configName : resources) {
if (!isInternalName(configName)) {
Configuration config = SecurityActions.getCacheConfiguration(cm, configName);
String fileName = configFile(configName);
Path xmlPath = root.resolve(String.format("%s.xml", configName));
try (OutputStream os = Files.newOutputStream(xmlPath)) {
parserRegistry.serialize(os, configName, config);
} catch (IOException e) {
throw new CacheException(String.format("Unable to create backup file '%s'", fileName), e);
}
log.debugf("Backing up template %s: %s", configName, config.toStringConfiguration(configName));
}
}
}, "cache-config-write");
}
@Override
public CompletionStage<Void> restore(ZipFile zip) {
ConfigurationManager configurationManager = SecurityActions.getGlobalComponentRegistry(cm).getComponent(ConfigurationManager.class);
return blockingManager.runBlocking(() -> {
Properties properties = new Properties();
properties.put(CacheParser.IGNORE_DUPLICATES, true);
for (String configName : resources) {
if (!isInternalName(configName)) {
String configFile = configFile(configName);
String zipPath = root.resolve(configFile).toString();
ZipEntry entry = zip.getEntry(zipPath);
try (InputStream is = zip.getInputStream(entry)) {
ConfigurationReader reader = ConfigurationReader.from(is).withProperties(properties).withNamingStrategy(NamingStrategy.KEBAB_CASE).build();
ConfigurationBuilderHolder builderHolder = parserRegistry.parse(reader, configurationManager.toBuilderHolder());
ConfigurationBuilder builder = builderHolder.getNamedConfigurationBuilders().get(configName);
Configuration cfg = builder.template(true).build();
// Only define configurations that don't already exist so that we don't overwrite newer versions of the default
// templates e.g. org.infinispan.DIST_SYNC when upgrading a cluster
log.debugf("Restoring template %s: %s", configName, cfg.toStringConfiguration(configName));
SecurityActions.getOrCreateTemplate(cm, configName, cfg);
} catch (IOException e) {
throw new CacheException(e);
}
}
}
}, "cache-config-read");
}
private String configFile(String config) {
return String.format("%s.xml", config);
}
}
| 5,460
| 43.762295
| 157
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/resources/AbstractContainerResource.java
|
package org.infinispan.server.core.backup.resources;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.protostream.ImmutableSerializationContext;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.server.core.BackupManager;
import org.infinispan.server.core.backup.ContainerResource;
import org.infinispan.server.core.logging.Log;
import org.infinispan.util.concurrent.BlockingManager;
abstract class AbstractContainerResource implements ContainerResource {
protected static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass(), Log.class);
protected final BackupManager.Resources.Type type;
protected final BackupManager.Resources params;
protected final Path root;
protected final BlockingManager blockingManager;
protected final boolean wildcard;
protected final Set<String> resources;
protected AbstractContainerResource(BackupManager.Resources.Type type, BackupManager.Resources params,
BlockingManager blockingManager, Path root) {
this.type = type;
this.params = params;
this.root = root.resolve(type.toString());
this.blockingManager = blockingManager;
Set<String> qualifiedResources = params.getQualifiedResources(type);
this.wildcard = qualifiedResources == null;
this.resources = ConcurrentHashMap.newKeySet();
if (!wildcard)
this.resources.addAll(qualifiedResources);
}
@Override
public void writeToManifest(Properties properties) {
properties.put(type.toString(), String.join(",", resources));
}
@Override
public void prepareAndValidateRestore(Properties properties) {
// Only process specific resources if specified
Set<String> resourcesAvailable = asSet(properties, type);
if (wildcard) {
resources.addAll(resourcesAvailable);
} else {
resourcesAvailable.retainAll(resources);
if (resourcesAvailable.isEmpty()) {
Set<String> missingResources = new HashSet<>(resources);
missingResources.removeAll(resourcesAvailable);
throw log.unableToFindBackupResource(type.toString(), missingResources);
}
}
}
static Set<String> asSet(Properties properties, BackupManager.Resources.Type resource) {
String prop = properties.getProperty(resource.toString());
if (prop == null || prop.isEmpty())
return Collections.emptySet();
String[] resources = prop.split(",");
Set<String> set = new HashSet<>(resources.length);
Collections.addAll(set, resources);
return set;
}
protected void mkdirs(Path path) {
try {
Files.createDirectories(path);
} catch (IOException e) {
throw new CacheException("Unable to create directories " + path);
}
}
protected static void writeMessageStream(Object o, ImmutableSerializationContext serCtx, DataOutputStream output) throws IOException {
// It's necessary to first write the length of each message stream as the Protocol Buffer wire format is not self-delimiting
// https://developers.google.com/protocol-buffers/docs/techniques#streaming
byte[] b = ProtobufUtil.toByteArray(serCtx, o);
output.writeInt(b.length);
output.write(b);
output.flush();
}
protected static <T> T readMessageStream(ImmutableSerializationContext ctx, Class<T> clazz, DataInputStream is) throws IOException {
int length = is.readInt();
byte[] b = new byte[length];
is.readFully(b);
return ProtobufUtil.fromByteArray(ctx, b, clazz);
}
static boolean isInternalName(String name) {
return name.startsWith("org.infinispan") || name.startsWith("example.") || name.equals("memcachedCache") || name.equals("respCache");
}
}
| 4,207
| 37.962963
| 139
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/resources/CounterResource.java
|
package org.infinispan.server.core.backup.resources;
import static org.infinispan.server.core.BackupManager.Resources.Type.COUNTERS;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.marshall.ProtoStreamTypeIds;
import org.infinispan.commons.reactive.RxJavaInterop;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterManager;
import org.infinispan.counter.api.CounterType;
import org.infinispan.counter.api.StrongCounter;
import org.infinispan.counter.api.WeakCounter;
import org.infinispan.protostream.ImmutableSerializationContext;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoTypeId;
import org.infinispan.server.core.BackupManager;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.concurrent.CompletionStages;
import io.reactivex.rxjava3.core.Flowable;
/**
* {@link org.infinispan.server.core.backup.ContainerResource} implementation for {@link
* BackupManager.Resources.Type#COUNTERS}.
*
* @author Ryan Emerson
* @since 12.0
*/
public class CounterResource extends AbstractContainerResource {
private static final String COUNTERS_FILE = "counters.dat";
private final CounterManager counterManager;
private final ImmutableSerializationContext serCtx;
CounterResource(CounterManager counterManager, BlockingManager blockingManager, ImmutableSerializationContext serCtx,
BackupManager.Resources params, Path root) {
super(COUNTERS, params, blockingManager, root);
this.counterManager = counterManager;
this.serCtx = serCtx;
}
@Override
public void prepareAndValidateBackup() {
if (wildcard) {
resources.addAll(counterManager.getCounterNames());
return;
}
for (String counterName : resources) {
if (counterManager.getConfiguration(counterName) == null)
throw log.unableToFindResource(type.toString(), counterName);
}
}
@Override
public CompletionStage<Void> backup() {
return blockingManager.blockingPublisherToVoidStage(
Flowable.using(
() -> {
mkdirs(root);
return new DataOutputStream(Files.newOutputStream(root.resolve(COUNTERS_FILE)));
},
output ->
Flowable.fromIterable(resources)
.map(counter -> {
CounterConfiguration config = counterManager.getConfiguration(counter);
CounterBackupEntry e = new CounterBackupEntry();
e.name = counter;
e.configuration = config;
e.value = config.type() == CounterType.WEAK ?
counterManager.getWeakCounter(counter).getValue() :
CompletionStages.join(counterManager.getStrongCounter(counter).getValue());
return e;
})
.doOnNext(e -> {
writeMessageStream(e, serCtx, output);
log.debugf("Counter added to backup: %s", e);
})
.onErrorResumeNext(RxJavaInterop.cacheExceptionWrapper()),
OutputStream::close
), "write-counters");
}
@Override
public CompletionStage<Void> restore(ZipFile zip) {
return blockingManager.runBlocking(() -> {
Set<String> countersToRestore = resources;
String countersFile = root.resolve(COUNTERS_FILE).toString();
ZipEntry zipEntry = zip.getEntry(countersFile);
if (zipEntry == null) {
if (!countersToRestore.isEmpty())
throw log.unableToFindBackupResource(type.toString(), countersToRestore);
return;
}
try (DataInputStream is = new DataInputStream(zip.getInputStream(zipEntry))) {
while (is.available() > 0) {
CounterBackupEntry entry = readMessageStream(serCtx, CounterBackupEntry.class, is);
if (!countersToRestore.contains(entry.name)) {
log.debugf("Ignoring '%s' counter", entry.name);
continue;
}
CounterConfiguration config = entry.configuration;
counterManager.defineCounter(entry.name, config);
if (config.type() == CounterType.WEAK) {
WeakCounter counter = counterManager.getWeakCounter(entry.name);
counter.add(entry.value - config.initialValue());
} else {
StrongCounter counter = counterManager.getStrongCounter(entry.name);
counter.compareAndSet(config.initialValue(), entry.value);
}
log.debugf("Counter restored: %s", entry);
}
} catch (IOException e) {
throw new CacheException(e);
}
}, "restore-counters");
}
/**
* ProtoStream entity used to represent counter instances.
*/
@ProtoTypeId(ProtoStreamTypeIds.COUNTER_BACKUP_ENTRY)
public static class CounterBackupEntry {
@ProtoField(number = 1)
String name;
@ProtoField(number = 2)
CounterConfiguration configuration;
@ProtoField(number = 3, defaultValue = "-1")
long value;
@Override
public String toString() {
return "CounterBackupEntry{" +
"name='" + name + '\'' +
", configuration=" + configuration +
", value=" + value +
'}';
}
}
}
| 6,111
| 37.929936
| 120
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/backup/resources/CacheResource.java
|
package org.infinispan.server.core.backup.resources;
import static org.infinispan.server.core.BackupManager.Resources.Type.CACHES;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.infinispan.AdvancedCache;
import org.infinispan.cache.impl.InvocationHelper;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.configuration.io.ConfigurationReader;
import org.infinispan.commons.configuration.io.NamingStrategy;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.marshall.MarshallingException;
import org.infinispan.commons.marshall.ProtoStreamTypeIds;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.ConfigurationManager;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.parsing.CacheParser;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.configuration.parsing.ParserRegistry;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.encoding.impl.StorageConfigurationManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.functional.impl.MetaParamsInternalMetadata;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.persistence.PersistenceMarshaller;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.InternalMetadataImpl;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.protostream.ImmutableSerializationContext;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoTypeId;
import org.infinispan.reactive.publisher.PublisherTransformers;
import org.infinispan.reactive.publisher.impl.ClusterPublisherManager;
import org.infinispan.reactive.publisher.impl.DeliveryGuarantee;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.server.core.BackupManager;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.concurrent.CompletionStages;
import org.reactivestreams.Publisher;
import io.reactivex.rxjava3.core.Flowable;
/**
* {@link org.infinispan.server.core.backup.ContainerResource} implementation for {@link
* BackupManager.Resources.Type#CACHES}.
*
* @author Ryan Emerson
* @since 12.0
*/
public class CacheResource extends AbstractContainerResource {
private final EmbeddedCacheManager cm;
private final ParserRegistry parserRegistry;
CacheResource(BlockingManager blockingManager, ParserRegistry parserRegistry, EmbeddedCacheManager cm,
BackupManager.Resources params, Path root) {
super(CACHES, params, blockingManager, root);
this.cm = cm;
this.parserRegistry = parserRegistry;
}
@Override
public void prepareAndValidateBackup() {
InternalCacheRegistry icr = SecurityActions.getGlobalComponentRegistry(cm).getComponent(InternalCacheRegistry.class);
Set<String> caches = wildcard ? cm.getCacheConfigurationNames() : resources;
for (String cache : caches) {
Configuration config = SecurityActions.getCacheConfiguration(cm, cache);
if (wildcard) {
// For wildcard resources, we ignore internal caches, however explicitly requested internal caches are allowed
if (config == null || config.isTemplate() || icr.isInternalCache(cache) || isInternalName(cache)) {
continue;
}
resources.add(cache);
} else if (config == null) {
throw log.unableToFindResource(type.toString(), cache);
} else if (config.isTemplate()) {
throw new CacheException(String.format("Unable to backup %s '%s' as it is a template not a cache", type, cache));
}
}
}
@Override
public CompletionStage<Void> backup() {
AggregateCompletionStage<Void> stages = CompletionStages.aggregateCompletionStage();
for (String cache : resources)
stages.dependsOn(createCacheBackup(cache));
return stages.freeze();
}
@Override
public CompletionStage<Void> restore(ZipFile zip) {
AggregateCompletionStage<Void> stages = CompletionStages.aggregateCompletionStage();
ConfigurationManager configurationManager = SecurityActions.getGlobalComponentRegistry(cm).getComponent(ConfigurationManager.class);
Properties properties = new Properties();
properties.put(CacheParser.IGNORE_DUPLICATES, true);
for (String cacheName : resources) {
stages.dependsOn(blockingManager.runBlocking(() -> {
Path cacheRoot = root.resolve(cacheName);
// Process .xml
String configFile = configFile(cacheName);
String zipPath = cacheRoot.resolve(configFile).toString();
try (InputStream is = zip.getInputStream(zip.getEntry(zipPath))) {
ConfigurationReader reader = ConfigurationReader.from(is).withProperties(properties).withNamingStrategy(NamingStrategy.KEBAB_CASE).withType(MediaType.fromExtension(configFile)).build();
ConfigurationBuilderHolder builderHolder = parserRegistry.parse(reader, configurationManager.toBuilderHolder());
Configuration config = builderHolder.getNamedConfigurationBuilders().get(cacheName).build();
log.debugf("Restoring Cache %s: %s", cacheName, config.toStringConfiguration(cacheName));
// Create the cache
SecurityActions.getOrCreateCache(cm, cacheName, config);
} catch (IOException e) {
throw new CacheException(e);
}
// Process .dat
String dataFile = dataFile(cacheName);
String data = cacheRoot.resolve(dataFile).toString();
ZipEntry zipEntry = zip.getEntry(data);
if (zipEntry == null)
return;
AdvancedCache<Object, Object> cache = cm.getCache(cacheName).getAdvancedCache();
ComponentRegistry cr = SecurityActions.getCacheComponentRegistry(cache);
CommandsFactory commandsFactory = cr.getCommandsFactory();
KeyPartitioner keyPartitioner = cr.getComponent(KeyPartitioner.class);
InvocationHelper invocationHelper = cr.getComponent(InvocationHelper.class);
StorageConfigurationManager scm = cr.getComponent(StorageConfigurationManager.class);
PersistenceMarshaller persistenceMarshaller = cr.getPersistenceMarshaller();
Marshaller userMarshaller = persistenceMarshaller.getUserMarshaller();
boolean keyMarshalling = !scm.getKeyStorageMediaType().isBinary();
boolean valueMarshalling = !scm.getValueStorageMediaType().isBinary();
SerializationContextRegistry ctxRegistry = SecurityActions.getGlobalComponentRegistry(cm).getComponent(SerializationContextRegistry.class);
ImmutableSerializationContext serCtx = ctxRegistry.getPersistenceCtx();
int entries = 0;
try (DataInputStream is = new DataInputStream(zip.getInputStream(zipEntry))) {
while (is.available() > 0) {
CacheBackupEntry entry = readMessageStream(serCtx, CacheBackupEntry.class, is);
Object key = keyMarshalling ? unmarshall(entry.key, userMarshaller) : scm.getKeyWrapper().wrap(entry.key);
Object value = valueMarshalling ? unmarshall(entry.value, userMarshaller) : scm.getValueWrapper().wrap(entry.value);
Metadata metadata = unmarshall(entry.metadata, persistenceMarshaller);
Metadata internalMetadataImpl = new InternalMetadataImpl(metadata, entry.created, entry.lastUsed);
PutKeyValueCommand cmd = commandsFactory.buildPutKeyValueCommand(key, value, keyPartitioner.getSegment(key),
internalMetadataImpl, FlagBitSets.IGNORE_RETURN_VALUES);
cmd.setInternalMetadata(entry.internalMetadata);
invocationHelper.invoke(cmd, 1);
entries++;
}
} catch (IOException e) {
throw new CacheException(e);
}
log.debugf("Cache %s restored %d entries", cacheName, entries);
}, "restore-cache-" + cacheName));
}
return stages.freeze();
}
private CompletionStage<Void> createCacheBackup(String cacheName) {
return blockingManager.supplyBlocking(() -> {
AdvancedCache<?, ?> cache = cm.getCache(cacheName).getAdvancedCache();
Configuration configuration = SecurityActions.getCacheConfiguration(cm, cacheName);
Path cacheRoot = root.resolve(cacheName);
// Create the cache backup dir and parents
mkdirs(cacheRoot);
// Write configuration file
String xmlFileName = configFile(cacheName);
Path xmlPath = cacheRoot.resolve(xmlFileName);
try (OutputStream os = Files.newOutputStream(xmlPath)) {
parserRegistry.serialize(os, cacheName, configuration);
} catch (IOException e) {
throw new CacheException(String.format("Unable to create backup file '%s'", xmlFileName), e);
}
ComponentRegistry cr = SecurityActions.getCacheComponentRegistry(cache);
ClusterPublisherManager<Object, Object> clusterPublisherManager = cr.getClusterPublisherManager().running();
SerializationContextRegistry ctxRegistry = cr.getGlobalComponentRegistry().getComponent(SerializationContextRegistry.class);
ImmutableSerializationContext serCtx = ctxRegistry.getPersistenceCtx();
String dataFileName = dataFile(cacheName);
Path datFile = cacheRoot.resolve(dataFileName);
StorageConfigurationManager scm = cr.getComponent(StorageConfigurationManager.class);
boolean keyMarshalling = !scm.getKeyStorageMediaType().isBinary();
boolean valueMarshalling = !scm.getValueStorageMediaType().isBinary();
PersistenceMarshaller persistenceMarshaller = cr.getPersistenceMarshaller();
Marshaller userMarshaller = persistenceMarshaller.getUserMarshaller();
if (log.isDebugEnabled())
log.debugf("Backing up Cache %s", configuration.toStringConfiguration(cacheName));
int bufferSize = configuration.clustering().stateTransfer().chunkSize();
Publisher<CacheBackupEntry> p =
Flowable.fromPublisher(
clusterPublisherManager.entryPublisher(null, null, null, EnumUtil.EMPTY_BIT_SET,
DeliveryGuarantee.EXACTLY_ONCE, bufferSize, PublisherTransformers.identity()).publisherWithoutSegments()
)
.map(e -> {
CacheBackupEntry be = new CacheBackupEntry();
// A cache might have heterogeneous data, e.g., `respCache`.
// TODO Handle this with proper metadata inspection.
boolean multimapMetadata = e.getMetadata() instanceof MetaParamsInternalMetadata;
be.key = keyMarshalling ? marshall(e.getKey(), userMarshaller) : (byte[]) scm.getKeyWrapper().unwrap(e.getKey());
be.value = valueMarshalling
? marshall(e.getValue(), userMarshaller)
: multimapMetadata
? marshall(e.getValue(), persistenceMarshaller)
: (byte[]) scm.getValueWrapper().unwrap(e.getValue());
be.metadata = marshall(e.getMetadata(), persistenceMarshaller);
be.internalMetadata = e.getInternalMetadata();
be.created = e.getCreated();
be.lastUsed = e.getLastUsed();
return be;
});
DataOutputStream output;
try {
output = new DataOutputStream(Files.newOutputStream(datFile));
} catch (IOException e) {
throw Util.rewrapAsCacheException(e);
}
final AtomicInteger entries = new AtomicInteger();
// Consume the publisher using the BlockingManager to ensure that all entries are subscribed to on a blocking thread
CompletionStage<Void> stage = blockingManager.subscribeBlockingConsumer(p, backup -> {
entries.incrementAndGet();
try {
writeMessageStream(backup, serCtx, output);
} catch (IOException ex) {
throw Util.rewrapAsCacheException(ex);
}
}, "backup-cache-entries");
return stage.whenComplete((Void, t) -> {
if (t == null)
log.debugf("Cache %s backed up %d entries", cacheName, entries.get());
Util.close(output);
});
}, "backup-cache")
.thenCompose(Function.identity());
}
private String configFile(String cache) {
return String.format("%s.xml", cache);
}
private String dataFile(String cache) {
return String.format("%s.dat", cache);
}
private byte[] marshall(Object key, Marshaller marshaller) {
try {
return marshaller.objectToByteBuffer(key);
} catch (IOException | InterruptedException e) {
throw new MarshallingException(e);
}
}
@SuppressWarnings("unchecked")
private static <T> T unmarshall(byte[] bytes, Marshaller marshaller) {
try {
return (T) marshaller.objectFromByteBuffer(bytes);
} catch (ClassNotFoundException | IOException e) {
throw new MarshallingException(e);
}
}
/**
* ProtoStream entity used to represent individual cache entries.
*/
@ProtoTypeId(ProtoStreamTypeIds.CACHE_BACKUP_ENTRY)
public static class CacheBackupEntry {
@ProtoField(number = 1)
byte[] key;
@ProtoField(number = 2)
byte[] value;
@ProtoField(number = 3)
byte[] metadata;
@ProtoField(number = 4)
PrivateMetadata internalMetadata;
@ProtoField(number = 5, defaultValue = "-1")
long created;
@ProtoField(number = 6, defaultValue = "-1")
long lastUsed;
}
}
| 14,957
| 46.037736
| 200
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/logging/Log.java
|
package org.infinispan.server.core.logging;
import static org.jboss.logging.Logger.Level.DEBUG;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.file.Path;
import java.util.Set;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.server.core.dataconversion.TranscodingException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import io.netty.channel.Channel;
import io.netty.handler.ipfilter.IpFilterRule;
/**
* Log abstraction for the server core module. For this module, message ids
* ranging from 5001 to 6000 inclusively have been reserved.
*
* @author Galder Zamarreño
* @since 5.0
*/
@MessageLogger(projectCode = "ISPN")
public interface Log extends BasicLogger {
String LOG_ROOT = "org.infinispan.";
Log CONFIG = Logger.getMessageLogger(Log.class, LOG_ROOT + "CONFIG");
Log SECURITY = Logger.getMessageLogger(Log.class, LOG_ROOT + "SECURITY");
Log SERVER = Logger.getMessageLogger(Log.class, LOG_ROOT + "SERVER");
// @LogMessage(level = WARN)
// @Message(value = "Server channel group did not completely unbind", id = 5004)
// void serverDidNotUnbind();
@LogMessage(level = WARN)
@Message(value = "%s is still bound to %s", id = 5005)
void channelStillBound(Channel ch, SocketAddress address);
// @LogMessage(level = WARN)
// @Message(value = "Channel group did not completely close", id = 5006)
// void serverDidNotClose();
@LogMessage(level = WARN)
@Message(value = "%s is still connected to %s", id = 5007)
void channelStillConnected(Channel ch, SocketAddress address);
@Message(value = "Illegal number of workerThreads: %d", id = 5010)
IllegalArgumentException illegalWorkerThreads(int workerThreads);
@Message(value = "Idle timeout can't be lower than -1: %d", id = 5011)
IllegalArgumentException illegalIdleTimeout(int idleTimeout);
@Message(value = "Receive Buffer Size can't be lower than 0: %d", id = 5012)
IllegalArgumentException illegalReceiveBufferSize(int recvBufSize);
@Message(value = "Send Buffer Size can't be lower than 0: %d", id = 5013)
IllegalArgumentException illegalSendBufferSize(int sendBufSize);
@Message(value = "SSL Enabled but no KeyStore specified", id = 5014)
CacheConfigurationException noSSLKeyManagerConfiguration();
@Message(value = "A password is required to open the KeyStore '%s'", id = 5016)
CacheConfigurationException missingKeyStorePassword(String keyStore);
@Message(value = "A password is required to open the TrustStore '%s'", id = 5017)
CacheConfigurationException missingTrustStorePassword(String trustStore);
@Message(value = "Cannot configure custom KeyStore and/or TrustStore when specifying a SSLContext", id = 5018)
CacheConfigurationException xorSSLContext();
@LogMessage(level = DEBUG)
@Message(value = "Using Netty SocketChannel %s for %s", id = 5025)
void createdSocketChannel(String channelClassName, String configuration);
@LogMessage(level = DEBUG)
@Message(value = "Using Netty EventLoop %s for %s", id = 5026)
void createdNettyEventLoop(String eventLoopClassName, String configuration);
@Message(value = "SSL Enabled but no SNI domain configured", id = 5027)
CacheConfigurationException noSniDomainConfigured();
@LogMessage(level = INFO)
@Message(value = "Native Epoll transport not available, using NIO instead: %s", id = 5028)
void epollNotAvailable(String message);
@Message(value = "No task manager available to register the admin operations handler", id = 5029)
CacheConfigurationException cannotRegisterAdminOperationsHandler();
@Message(value = "Administration task '%s' invoked without required parameter '%s'", id = 5030)
NullPointerException missingRequiredAdminTaskParameter(String name, String parameter);
@Message(value = "The supplied configuration for cache '%s' is missing a named configuration for it: %s", id = 5031)
CacheConfigurationException missingCacheConfiguration(String name, String configuration);
// @Message(value = "Error during transcoding", id = 5032)
// TranscodingException errorDuringTranscoding(@Cause Throwable e);
@Message(value = "Data format '%s' not supported", id = 5033)
TranscodingException unsupportedDataFormat(MediaType contentFormat);
@Message(value = "Cannot create clustered caches in non-clustered servers", id = 5034)
UnsupportedOperationException cannotCreateClusteredCache();
@Message(value = "Class '%s' blocked by deserialization allow list. Include the class name in the server cache manager allow list to authorize.", id = 5035)
CacheException errorDeserializing(String className);
@Message(value = "Illegal number of ioThreads: %d", id = 5036)
IllegalArgumentException illegalIOThreads(int ioThreads);
// @Message(value = "No provider for authorization realm", id = 5037)
// XMLStreamException noProviderForAuthorizationRealm();
@Message(value = "Illegal type for parameter '%s': %s", id = 5038)
IllegalArgumentException illegalParameterType(String parameter, Class<?> type);
@Message(value = "Cannot create cluster backup", id = 5039)
CacheException errorCreatingBackup(@Cause Throwable cause);
@Message(value = "Cannot restore cluster backup '%s'", id = 5040)
CacheException errorRestoringBackup(Path path, @Cause Throwable cause);
@Message(value = "Cannot perform backup, backup currently in progress", id = 5041)
CacheException backupInProgress();
@Message(value = "Cannot restore content, restore currently in progress", id = 5042)
CacheException restoreInProgress();
@LogMessage(level = INFO)
@Message(value = "Starting backup '%s'", id = 5043)
void initiatingBackup(String name);
@LogMessage(level = INFO)
@Message(value = "Backup file created '%s'", id = 5044)
void backupComplete(String backupName);
@LogMessage(level = INFO)
@Message(value = "Starting restore '%s' of '%s'", id = 5045)
void initiatingRestore(String name, Path backup);
@LogMessage(level = INFO)
@Message(value = "Restore '%s' complete", id = 5046)
void restoreComplete(String name);
@Message(value = "%s '%s' not found in the backup archive", id = 5047)
CacheException unableToFindBackupResource(String resource, Set<String> resourceNames);
@Message(value = "%s '%s' does not exist", id = 5048)
CacheException unableToFindResource(String resource, String resourceName);
@Message(value = "Cannot perform backup, backup already exists with name '%s'", id = 5049)
CacheException backupAlreadyExists(String name);
@LogMessage(level = INFO)
@Message(value = "Deleted backup '%s'", id = 5050)
void backupDeleted(String name);
@Message(value = "Cannot perform restore, restore already exists with name '%s'", id = 5051)
CacheException restoreAlreadyExists(String name);
@LogMessage(level = INFO)
@Message(value = "Rejected connection from '%s' using rule '%s'", id = 5052)
void ipFilterConnectionRejection(InetSocketAddress remoteAddress, IpFilterRule rule);
@Message(value = "The supplied configuration for cache '%s' must contain a single cache configuration for it: %s", id = 5053)
CacheConfigurationException configurationMustContainSingleCache(String name, String configuration);
@LogMessage(level = INFO)
@Message(value = "Native IOUring transport not available, using NIO instead: %s", id = 5054)
void ioUringNotAvailable(String message);
@LogMessage(level = INFO)
@Message(value = "Using transport: %s", id = 5055)
void usingTransport(String transportName);
@Message(value = "Cannot enable authentication without specifying a SaslAuthenticationProvider", id = 5056)
CacheConfigurationException saslAuthenticationProvider();
@Message(value = "The specified allowedMechs [%s] contains mechs which are unsupported by the underlying factories [%s]", id = 5057)
CacheConfigurationException invalidAllowedMechs(Set<String> allowedMechs, Set<String> allMechs);
@Message(value = "A serverName must be specified when enabling authentication", id = 5058)
CacheConfigurationException missingServerName();
@Message(value = "EXTERNAL SASL mechanism not allowed without SSL client certificate", id = 5059)
SecurityException externalMechNotAllowedWithoutSSLClientCert();
// Out-of-order log messages. Moved here from the server-hotrod module
@Message(value = "Factory '%s' not found in server", id = 6016)
IllegalStateException missingKeyValueFilterConverterFactory(String name);
@LogMessage(level = WARN)
@Message(value = "Removed unclosed iterator '%s'", id = 28026)
void removedUnclosedIterator(String iteratorId);
@LogMessage(level = INFO)
@Message(value = "Flushed cache for security realm '%s'", id = 28027)
void flushRealmCache(String name);
}
| 9,239
| 43.637681
| 159
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/XMLTranscoder.java
|
package org.infinispan.server.core.dataconversion;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_UNKNOWN;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_WWW_FORM_URLENCODED;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.Collections;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.configuration.io.ConfigurationReader;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.OneToManyTranscoder;
import org.infinispan.commons.dataconversion.StandardConversions;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.server.core.dataconversion.xml.XStreamEngine;
import org.infinispan.server.core.logging.Log;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;
import com.thoughtworks.xstream.security.ForbiddenClassException;
import com.thoughtworks.xstream.security.NoTypePermission;
/**
* Basic XML transcoder supporting conversions from XML to commons formats.
*
* @since 9.2
*/
public class XMLTranscoder extends OneToManyTranscoder {
private static final Log logger = LogFactory.getLog(XMLTranscoder.class, Log.class);
private final XStreamEngine xstream;
public XMLTranscoder() {
this(XMLTranscoder.class.getClassLoader(), new ClassAllowList(Collections.emptyList()));
}
public XMLTranscoder(ClassAllowList classAllowList) {
this(XMLTranscoder.class.getClassLoader(), classAllowList);
}
public XMLTranscoder(ClassLoader classLoader, ClassAllowList allowList) {
super(APPLICATION_XML, APPLICATION_OBJECT, APPLICATION_OCTET_STREAM, TEXT_PLAIN, APPLICATION_WWW_FORM_URLENCODED, APPLICATION_UNKNOWN);
xstream = new XStreamEngine();
xstream.addPermission(NoTypePermission.NONE);
xstream.addPermission(type -> allowList.isSafeClass(type.getName()));
xstream.setClassLoader(classLoader);
xstream.setMode(XStream.NO_REFERENCES);
}
@Override
public Object doTranscode(Object content, MediaType contentType, MediaType destinationType) {
if (destinationType.match(APPLICATION_XML)) {
if (contentType.match(APPLICATION_XML)) {
return StandardConversions.convertCharset(content, contentType.getCharset(), destinationType.getCharset());
}
if (contentType.match(APPLICATION_OBJECT)) {
String xmlString = xstream.toXML(content);
return xmlString.getBytes(destinationType.getCharset());
}
if (contentType.match(TEXT_PLAIN) || contentType.match(APPLICATION_WWW_FORM_URLENCODED)) {
String inputText = StandardConversions.convertTextToObject(content, contentType);
if (isWellFormed(inputText.getBytes())) return inputText.getBytes();
String xmlString = xstream.toXML(inputText);
return xmlString.getBytes(destinationType.getCharset());
} else if (contentType.match(APPLICATION_OCTET_STREAM) || contentType.match(APPLICATION_UNKNOWN)) {
String inputText = StandardConversions.convertTextToObject(content, contentType);
if (isWellFormed(inputText.getBytes())) return inputText.getBytes();
String xmlString = xstream.toXML(inputText);
return xmlString.getBytes(destinationType.getCharset());
}
}
if (destinationType.match(APPLICATION_OCTET_STREAM) || destinationType.match(APPLICATION_UNKNOWN)) {
return StandardConversions.convertTextToOctetStream(content, contentType);
}
if (destinationType.match(TEXT_PLAIN)) {
return StandardConversions.convertCharset(content, contentType.getCharset(), destinationType.getCharset());
}
if (destinationType.match(APPLICATION_OBJECT)) {
try {
Reader xmlReader = content instanceof byte[] ?
new InputStreamReader(new ByteArrayInputStream((byte[]) content)) :
new StringReader(content.toString());
return xstream.fromXML(xmlReader);
} catch (ForbiddenClassException e) {
throw logger.errorDeserializing(e.getMessage());
} catch (XStreamException e) {
throw new CacheException(e);
}
}
throw logger.unsupportedDataFormat(contentType);
}
private boolean isWellFormed(byte[] content) {
ByteArrayInputStream is = new ByteArrayInputStream(content);
try (ConfigurationReader reader = ConfigurationReader.from(is).build()) {
// Consume all the stream
while (reader.hasNext()) {
reader.nextElement();
}
return true;
} catch (Exception e) {
return false;
}
}
}
| 5,203
| 44.252174
| 141
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/JsonTranscoder.java
|
package org.infinispan.server.core.dataconversion;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_SERIALIZED_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_UNKNOWN;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_WWW_FORM_URLENCODED;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.dataconversion.OneToManyTranscoder;
import org.infinispan.commons.dataconversion.StandardConversions;
import org.infinispan.server.core.dataconversion.deserializer.Deserializer;
import org.infinispan.server.core.dataconversion.deserializer.SEntity;
import org.infinispan.server.core.dataconversion.json.SecureTypeResolverBuilder;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
/**
* @since 9.2
*/
public class JsonTranscoder extends OneToManyTranscoder {
protected final static Log logger = LogFactory.getLog(JsonTranscoder.class, Log.class);
public static final String TYPE_PROPERTY = "_type";
private final ObjectMapper objectMapper;
private static final JsonFactory JSON_FACTORY = new JsonFactory();
public JsonTranscoder() {
this(JsonTranscoder.class.getClassLoader(), new ClassAllowList(Collections.emptyList()));
}
public JsonTranscoder(ClassAllowList allowList) {
this(JsonTranscoder.class.getClassLoader(), allowList);
}
public JsonTranscoder(ClassLoader classLoader, ClassAllowList allowList) {
super(APPLICATION_JSON, APPLICATION_OBJECT, APPLICATION_OCTET_STREAM, APPLICATION_SERIALIZED_OBJECT, TEXT_PLAIN, APPLICATION_WWW_FORM_URLENCODED, APPLICATION_UNKNOWN);
this.objectMapper = new ObjectMapper().setDefaultTyping(
new SecureTypeResolverBuilder(ObjectMapper.DefaultTyping.NON_FINAL, allowList) {
{
init(JsonTypeInfo.Id.CLASS, null);
inclusion(JsonTypeInfo.As.PROPERTY);
typeProperty(TYPE_PROPERTY);
}
@Override
public boolean useForType(JavaType t) {
return !t.isContainerType() && super.useForType(t);
}
});
TypeFactory typeFactory = TypeFactory.defaultInstance().withClassLoader(classLoader);
this.objectMapper.setTypeFactory(typeFactory);
}
@Override
public Object doTranscode(Object content, MediaType contentType, MediaType destinationType) {
if (destinationType.match(APPLICATION_OCTET_STREAM) || destinationType.match(APPLICATION_UNKNOWN)) {
return StandardConversions.convertTextToOctetStream(content, contentType);
}
boolean outputString = destinationType.hasStringType();
Charset contentCharset = contentType.getCharset();
Charset destinationCharset = destinationType.getCharset();
if (destinationType.match(APPLICATION_JSON)) {
if (contentType.match(APPLICATION_JSON)) {
return convertCharset(content, contentCharset, destinationCharset, outputString);
}
try {
if (contentType.match(APPLICATION_SERIALIZED_OBJECT) && content instanceof byte[]) {
return convertJavaSerializedToJson((byte[]) content, destinationCharset, outputString);
} else if (content instanceof String || content instanceof byte[]) {
return convertTextToJson(content, contentCharset, destinationCharset, outputString);
}
logger.jsonObjectConversionDeprecated();
if (outputString) {
return objectMapper.writeValueAsString(content);
}
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(out, destinationCharset)) {
objectMapper.writeValue(osw, content);
return out.toByteArray();
}
} catch (IOException e) {
throw logger.cannotConvertContent(content, contentType, destinationType, e);
}
}
if (destinationType.match(APPLICATION_OBJECT)) {
logger.jsonObjectConversionDeprecated();
try {
String destinationClassName = destinationType.getClassType();
Class<?> destinationClass = Object.class;
if (destinationClassName != null) destinationClass = Class.forName(destinationClassName);
if (content instanceof byte[]) {
return objectMapper.readValue((byte[]) content, destinationClass);
}
return objectMapper.readValue((String) content, destinationClass);
} catch (IOException | ClassNotFoundException e) {
throw new CacheException(e);
}
}
if (destinationType.match(TEXT_PLAIN)) {
return convertCharset(content, contentCharset, destinationCharset, outputString);
}
throw logger.unsupportedContent(JsonTranscoder.class.getSimpleName(), content);
}
private Object convertJavaSerializedToJson(byte[] content, Charset destinationCharset, boolean outputAsString) {
try {
Deserializer deserializer = new Deserializer(new ByteArrayInputStream(content), true);
SEntity entity = deserializer.readObject();
String json = entity.json().toString();
return outputAsString ? json : StandardConversions.convertCharset(json, StandardCharsets.UTF_8, destinationCharset);
} catch (IOException e) {
throw logger.cannotConvertContent(content, APPLICATION_SERIALIZED_OBJECT, APPLICATION_JSON, e);
}
}
private Object convertTextToJson(Object content, Charset contentCharset, Charset destinationCharset, boolean asString) throws IOException {
byte[] bytes = content instanceof byte[] ? (byte[]) content : content.toString().getBytes(contentCharset);
if (bytes.length == 0) return bytes;
if (isValidJson(bytes, contentCharset)) {
return convertCharset(bytes, contentCharset, destinationCharset, asString);
} else {
throw logger.invalidJson(new String(bytes));
}
}
public static boolean isValidJson(byte[] content, Charset charset) {
try (InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(content), charset);
BufferedReader reader = new BufferedReader(isr);
JsonParser parser = JSON_FACTORY.createParser(reader)) {
parser.nextToken();
while (parser.hasCurrentToken()) parser.nextToken();
} catch (IOException e) {
return false;
}
return true;
}
private Object convertCharset(Object content, Charset contentCharset, Charset destinationCharset, boolean outputAsString) {
byte[] bytes = StandardConversions.convertCharset(content, contentCharset, destinationCharset);
return outputAsString ? new String(bytes, destinationCharset) : bytes;
}
}
| 7,938
| 45.426901
| 173
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/TranscodingException.java
|
package org.infinispan.server.core.dataconversion;
public class TranscodingException extends RuntimeException {
public TranscodingException(String message) {
super(message);
}
}
| 192
| 20.444444
| 60
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/xml/MXParserDriver.java
|
package org.infinispan.server.core.dataconversion.xml;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import org.infinispan.commons.configuration.io.xml.MXParser;
import com.thoughtworks.xstream.core.util.XmlHeaderAwareReader;
import com.thoughtworks.xstream.io.AbstractDriver;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.StreamException;
import com.thoughtworks.xstream.io.xml.CompactWriter;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.0
**/
public class MXParserDriver extends AbstractDriver {
public MXParserDriver() {}
@Override
public HierarchicalStreamReader createReader(Reader reader) {
return new MXParserReader(reader, new MXParser(), getNameCoder());
}
@Override
public HierarchicalStreamReader createReader(InputStream in) {
try {
return createReader(new XmlHeaderAwareReader(in));
} catch (IOException e) {
throw new StreamException(e);
}
}
@Override
public HierarchicalStreamWriter createWriter(Writer writer) {
return new CompactWriter(writer, getNameCoder());
}
@Override
public HierarchicalStreamWriter createWriter(OutputStream out) {
return createWriter(new OutputStreamWriter(out));
}
}
| 1,473
| 27.901961
| 72
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/xml/MXParserReader.java
|
package org.infinispan.server.core.dataconversion.xml;
import java.io.IOException;
import java.io.Reader;
import org.infinispan.commons.configuration.io.xml.MXParser;
import com.thoughtworks.xstream.converters.ErrorWriter;
import com.thoughtworks.xstream.io.StreamException;
import com.thoughtworks.xstream.io.naming.NameCoder;
import com.thoughtworks.xstream.io.xml.AbstractPullReader;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
public class MXParserReader extends AbstractPullReader {
private final MXParser parser;
private final Reader reader;
public MXParserReader(Reader reader, MXParser parser) {
this(reader, parser, new XmlFriendlyNameCoder());
}
public MXParserReader(Reader reader, MXParser parser, NameCoder nameCoder) {
super(nameCoder);
this.parser = parser;
this.reader = reader;
try {
parser.setInput(this.reader);
} catch (Exception e) {
throw new StreamException(e);
}
this.moveDown();
}
protected int pullNextEvent() {
try {
switch (this.parser.next()) {
case 0:
case 2:
return 1;
case 1:
case 3:
return 2;
case 4:
return 3;
case 9:
return 4;
default:
return 0;
}
} catch (Exception e) {
throw new StreamException(e);
}
}
protected String pullElementName() {
return this.parser.getName();
}
protected String pullText() {
return this.parser.getText();
}
public String getAttribute(String name) {
return this.parser.getAttributeValue(null, this.encodeAttribute(name));
}
public String getAttribute(int index) {
return this.parser.getAttributeValue(index);
}
public int getAttributeCount() {
return this.parser.getAttributeCount();
}
public String getAttributeName(int index) {
return this.decodeAttribute(this.parser.getAttributeName(index));
}
public void appendErrors(ErrorWriter errorWriter) {
errorWriter.add("line number", String.valueOf(this.parser.getLineNumber()));
}
public void close() {
try {
this.reader.close();
} catch (IOException var2) {
throw new StreamException(var2);
}
}
}
| 2,364
| 24.430108
| 82
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/xml/XStreamEngine.java
|
package org.infinispan.server.core.dataconversion.xml;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.basic.BigDecimalConverter;
import com.thoughtworks.xstream.converters.basic.BigIntegerConverter;
import com.thoughtworks.xstream.converters.basic.BooleanConverter;
import com.thoughtworks.xstream.converters.basic.ByteConverter;
import com.thoughtworks.xstream.converters.basic.CharConverter;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.converters.basic.DoubleConverter;
import com.thoughtworks.xstream.converters.basic.FloatConverter;
import com.thoughtworks.xstream.converters.basic.IntConverter;
import com.thoughtworks.xstream.converters.basic.LongConverter;
import com.thoughtworks.xstream.converters.basic.NullConverter;
import com.thoughtworks.xstream.converters.basic.ShortConverter;
import com.thoughtworks.xstream.converters.basic.StringConverter;
import com.thoughtworks.xstream.converters.basic.URIConverter;
import com.thoughtworks.xstream.converters.basic.URLConverter;
import com.thoughtworks.xstream.converters.collections.ArrayConverter;
import com.thoughtworks.xstream.converters.collections.BitSetConverter;
import com.thoughtworks.xstream.converters.collections.CharArrayConverter;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.converters.collections.MapConverter;
import com.thoughtworks.xstream.converters.collections.SingletonCollectionConverter;
import com.thoughtworks.xstream.converters.collections.SingletonMapConverter;
import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter;
import com.thoughtworks.xstream.converters.extended.FileConverter;
import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter;
import com.thoughtworks.xstream.converters.extended.JavaClassConverter;
import com.thoughtworks.xstream.converters.extended.JavaFieldConverter;
import com.thoughtworks.xstream.converters.extended.JavaMethodConverter;
import com.thoughtworks.xstream.converters.extended.LocaleConverter;
import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
import com.thoughtworks.xstream.converters.reflection.SerializableConverter;
/**
* Adapter for the XStream XML Engine with pre-defined configurations.
*
* @since 13.0
*/
public class XStreamEngine extends XStream {
public XStreamEngine() {
super(new MXParserDriver());
}
@Override
protected void setupConverters() {
registerConverter(new ReflectionConverter(getMapper(), getReflectionProvider()), PRIORITY_VERY_LOW);
registerConverter(new SerializableConverter(getMapper(), getReflectionProvider(), getClassLoaderReference()), PRIORITY_LOW);
registerConverter(new ExternalizableConverter(getMapper(), getClassLoaderReference()), PRIORITY_LOW);
registerConverter(new NullConverter(), PRIORITY_VERY_HIGH);
registerConverter(new IntConverter(), PRIORITY_NORMAL);
registerConverter(new FloatConverter(), PRIORITY_NORMAL);
registerConverter(new DoubleConverter(), PRIORITY_NORMAL);
registerConverter(new LongConverter(), PRIORITY_NORMAL);
registerConverter(new ShortConverter(), PRIORITY_NORMAL);
registerConverter((Converter) new CharConverter(), PRIORITY_NORMAL);
registerConverter(new BooleanConverter(), PRIORITY_NORMAL);
registerConverter(new ByteConverter(), PRIORITY_NORMAL);
registerConverter(new StringConverter(), PRIORITY_NORMAL);
registerConverter(new DateConverter(), PRIORITY_NORMAL);
registerConverter(new BitSetConverter(), PRIORITY_NORMAL);
registerConverter(new URIConverter(), PRIORITY_NORMAL);
registerConverter(new URLConverter(), PRIORITY_NORMAL);
registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL);
registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL);
registerConverter(new ArrayConverter(getMapper()), PRIORITY_NORMAL);
registerConverter(new CharArrayConverter(), PRIORITY_NORMAL);
registerConverter(new CollectionConverter(getMapper()), PRIORITY_NORMAL);
registerConverter(new MapConverter(getMapper()), PRIORITY_NORMAL);
registerConverter(new SingletonCollectionConverter(getMapper()), PRIORITY_NORMAL);
registerConverter(new SingletonMapConverter(getMapper()), PRIORITY_NORMAL);
registerConverter((Converter) new EncodedByteArrayConverter(), PRIORITY_NORMAL);
registerConverter(new FileConverter(), PRIORITY_NORMAL);
registerConverter(new JavaClassConverter(getClassLoaderReference()), PRIORITY_NORMAL);
registerConverter(new JavaMethodConverter(getClassLoaderReference()), PRIORITY_NORMAL);
registerConverter(new JavaFieldConverter(getClassLoaderReference()), PRIORITY_NORMAL);
registerConverter(new LocaleConverter(), PRIORITY_NORMAL);
registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL);
}
}
| 5,096
| 58.964706
| 130
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/deserializer/SPrim.java
|
package org.infinispan.server.core.dataconversion.deserializer;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* Based on Serialisys by Eamonn McManus
*/
public class SPrim extends SEntity {
private static final Map<Class<?>, String> PRIMITIVES = new HashMap<>();
static {
for (Class<?> c : new Class<?>[]{
Boolean.class, Byte.class, Character.class, Double.class,
Float.class, Integer.class, Long.class, Short.class
}) {
try {
Field type = c.getField("TYPE");
Class<?> prim = (Class<?>) type.get(null);
PRIMITIVES.put(c, prim.getName());
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
private final Object value;
/**
* Create a representation of the given wrapped primitive object.
*
* @param x a wrapped primitive object, for example an Integer if the represented primitive is an int.
*/
SPrim(Object x) {
super(PRIMITIVES.get(x.getClass()));
this.value = x;
}
/**
* The value of the primitive object, wrapped in the corresponding wrapper type, for example Integer if the primitive
* is an int.
*/
public Object getValue() {
return value;
}
@Override
public Json json() {
return Json.make(value);
}
}
| 1,431
| 24.571429
| 120
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/deserializer/SObject.java
|
package org.infinispan.server.core.dataconversion.deserializer;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Stack;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* Based on Serialisys by Eamonn McManus
*/
public class SObject extends SEntity {
private final Map<String, SEntity> fields = new LinkedHashMap<>();
SObject(String type) {
super(type);
}
void setField(String name, SEntity value) {
fields.put(name, value);
}
public SEntity getField(String name) {
return fields.get(name);
}
@Override
public Json json() {
Stack<SEntity> stack = SEntity.items.get();
if (stack.contains(this)) {
return Json.object(); // Return a placeholder to avoid circularity
} else {
stack.push(this);
Json json = Json.object();
for (Map.Entry<String, SEntity> entry : fields.entrySet()) {
SEntity v = entry.getValue();
json.set(entry.getKey(), v == null ? Json.nil() : v.json());
}
stack.pop();
return json;
}
}
}
| 1,109
| 23.666667
| 75
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/deserializer/SString.java
|
package org.infinispan.server.core.dataconversion.deserializer;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* Based on Serialisys by Eamonn McManus
*/
public class SString extends SEntity {
private final String s;
SString(String s) {
super("String");
this.s = s;
}
public String getValue() {
return s;
}
@Override
public Json json() {
return Json.make(s);
}
}
| 435
| 16.44
| 63
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/deserializer/SEntity.java
|
package org.infinispan.server.core.dataconversion.deserializer;
import java.util.Stack;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* Based on Serialisys by Eamonn McManus
*/
public abstract class SEntity {
protected static final ThreadLocal<Stack<SEntity>> items = ThreadLocal.withInitial(Stack::new);
private final String type;
SEntity(String type) {
this.type = type;
}
public abstract Json json();
String getType() {
return type;
}
}
| 500
| 19.04
| 98
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/deserializer/SArray.java
|
package org.infinispan.server.core.dataconversion.deserializer;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* Based on Serialisys by Eamonn McManus
*/
public class SArray extends SEntity {
private final SEntity[] array;
SArray(String type, int size) {
super(type);
this.array = new SEntity[size];
}
void set(int i, SEntity object) {
array[i] = object;
}
@Override
public Json json() {
Json json = Json.array();
for (SEntity obj : array) {
json.add(obj.json());
}
return json;
}
}
| 583
| 18.466667
| 63
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/deserializer/Deserializer.java
|
package org.infinispan.server.core.dataconversion.deserializer;
import static java.io.ObjectStreamConstants.SC_BLOCK_DATA;
import static java.io.ObjectStreamConstants.SC_EXTERNALIZABLE;
import static java.io.ObjectStreamConstants.SC_SERIALIZABLE;
import static java.io.ObjectStreamConstants.SC_WRITE_METHOD;
import static java.io.ObjectStreamConstants.STREAM_MAGIC;
import static java.io.ObjectStreamConstants.STREAM_VERSION;
import static java.io.ObjectStreamConstants.TC_ARRAY;
import static java.io.ObjectStreamConstants.TC_BLOCKDATA;
import static java.io.ObjectStreamConstants.TC_BLOCKDATALONG;
import static java.io.ObjectStreamConstants.TC_CLASS;
import static java.io.ObjectStreamConstants.TC_CLASSDESC;
import static java.io.ObjectStreamConstants.TC_ENDBLOCKDATA;
import static java.io.ObjectStreamConstants.TC_ENUM;
import static java.io.ObjectStreamConstants.TC_EXCEPTION;
import static java.io.ObjectStreamConstants.TC_LONGSTRING;
import static java.io.ObjectStreamConstants.TC_NULL;
import static java.io.ObjectStreamConstants.TC_OBJECT;
import static java.io.ObjectStreamConstants.TC_PROXYCLASSDESC;
import static java.io.ObjectStreamConstants.TC_REFERENCE;
import static java.io.ObjectStreamConstants.TC_RESET;
import static java.io.ObjectStreamConstants.TC_STRING;
import static java.io.ObjectStreamConstants.baseWireHandle;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.io.StreamCorruptedException;
import java.io.WriteAbortedException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* Based on Serialisys by Eamonn McManus
*/
public class Deserializer {
private static final SEntity END = new SString("END");
private final PrimitiveClassDescFactory primitiveClassDescFactory = new PrimitiveClassDescFactory();
private final DataInputStream din;
private final List<SEntity> handles = new ArrayList<>();
private final Map<String, ClassDesc> classDescriptions = new HashMap<>();
public Deserializer(InputStream in, boolean header) throws IOException {
this.din = new DataInputStream(in);
if (header) {
if (din.readShort() != STREAM_MAGIC || din.readShort() != STREAM_VERSION)
throw new StreamCorruptedException("Bad stream header");
}
}
public SEntity readObject() throws IOException {
SEntity entity = readObjectOrEnd();
if (entity == END) throw new StreamCorruptedException("Unexpected end-block-data");
return entity;
}
private SString readString() throws IOException {
return (SString) readObject();
}
private SEntity readObjectOrEnd() throws IOException {
while (true) {
int code = din.readByte();
switch (code) {
case TC_OBJECT:
return newObject();
case TC_CLASS:
return newClass();
case TC_ARRAY:
return newArray();
case TC_STRING:
return newString();
case TC_LONGSTRING:
return newLongString();
case TC_ENUM:
return newEnum();
case TC_CLASSDESC:
case TC_PROXYCLASSDESC:
classDesc(code);
break;
case TC_REFERENCE:
return prevObject();
case TC_NULL:
return null;
case TC_EXCEPTION:
exception();
break;
case TC_RESET:
reset();
break;
case TC_BLOCKDATA:
return blockDataShort();
case TC_BLOCKDATALONG:
return blockDataLong();
case TC_ENDBLOCKDATA:
return END;
default:
throw new StreamCorruptedException("Bad type code: " + code);
}
}
}
private SEntity newObject() throws IOException {
ObjectClassDesc desc = classDesc();
SObject t = new SObject(desc.getType());
newHandle(t);
for (ObjectClassDesc cd : desc.getHierarchy())
classData(t, cd);
return t;
}
private void classData(SObject t, ObjectClassDesc cd) throws IOException {
int flags = cd.getFlags();
if ((flags & SC_SERIALIZABLE) != 0) {
for (FieldDesc fieldDesc : cd.getFields()) {
t.setField(fieldDesc.getName(), fieldDesc.read());
}
if ((flags & SC_WRITE_METHOD) != 0) {
objectAnnotation(t);
}
} else if ((flags & SC_EXTERNALIZABLE) != 0) {
if ((flags & SC_BLOCK_DATA) == 0) throw new IOException("Can't handle externalContents");
objectAnnotation(t);
}
}
private void objectAnnotation(SObject t) throws IOException {
while (readObjectOrEnd() != END) {
// Discard annotations
}
}
private ClassDesc newClass() throws IOException {
ClassDesc desc = classDesc();
newHandle(desc);
return desc;
}
private ObjectClassDesc classDesc() throws IOException {
int code = din.readByte();
return classDesc(code);
}
private ObjectClassDesc classDesc(int code) throws IOException {
return classDesc0(code);
}
private ObjectClassDesc classDesc0(int code) throws IOException {
switch (code) {
case TC_CLASSDESC:
return newPlainClassDesc();
case TC_PROXYCLASSDESC:
return newProxyClassDesc();
case TC_NULL:
return null;
case TC_REFERENCE:
return (ObjectClassDesc) prevObject();
default:
throw new StreamCorruptedException("Bad class descriptor");
}
}
private ObjectClassDesc newPlainClassDesc() throws IOException {
String className = din.readUTF();
long serialVersionUID = din.readLong();
int flags = din.readByte();
ObjectClassDesc desc;
if (className.startsWith("[")) desc = getArrayClassDesc(className, flags, serialVersionUID);
else desc = getObjectClassDesc(className, flags, serialVersionUID);
newHandle(desc);
int nfields = din.readShort();
FieldDesc[] fields = new FieldDesc[nfields];
for (int i = 0; i < nfields; i++)
fields[i] = fieldDesc();
desc.setFields(fields);
classAnnotation(desc);
ObjectClassDesc superDesc = classDesc();
desc.setSuperClassDesc(superDesc);
return desc;
}
private ObjectClassDesc getObjectClassDesc(String className, int flags, Long serialVersionUID) {
ObjectClassDesc desc = (ObjectClassDesc) classDescriptions.get(className);
if (desc != null) {
if (desc.getSerialVersionUID() == null) desc.setSerialVersionUID(serialVersionUID);
if (!desc.getName().equals(className) || desc.getFlags() != flags)
throw new IllegalStateException("name/flags/serialVersionUID don't match");
return desc;
} else {
desc = new ObjectClassDesc(className, flags, serialVersionUID);
classDescriptions.put(desc.getName(), desc);
return desc;
}
}
private ArrayClassDesc getArrayClassDesc(String className, int flags, Long serialVersionUID) throws IOException {
ArrayClassDesc desc = (ArrayClassDesc) classDescriptions.get(className);
if (desc != null) {
if (desc.getSerialVersionUID() == null) desc.setSerialVersionUID(serialVersionUID);
if (!desc.getName().equals(className) || desc.getFlags() != flags)
throw new IllegalStateException("name/flags/serialVersionUID don't match");
return desc;
} else {
desc = new ArrayClassDesc(className, flags, serialVersionUID);
classDescriptions.put(desc.getName(), desc);
return desc;
}
}
private ObjectClassDesc newProxyClassDesc() throws IOException {
ObjectClassDesc desc = new ObjectClassDesc("<Proxy>", SC_SERIALIZABLE, 1L);
newHandle(desc);
// Discard the interfaces
int count = din.readInt();
for (int i = 0; i < count; i++) din.readUTF();
classAnnotation(desc);
ObjectClassDesc superDesc = classDesc();
desc.setSuperClassDesc(superDesc);
return desc;
}
private void classAnnotation(ClassDesc desc) throws IOException {
while (readObjectOrEnd() != END) {
// Discard the annotations
}
}
private FieldDesc fieldDesc() throws IOException {
char c = (char) din.readByte();
final boolean primitive;
switch (c) {
case 'B':
case 'C':
case 'D':
case 'F':
case 'I':
case 'J':
case 'S':
case 'Z':
primitive = true;
break;
case 'L':
case '[':
primitive = false;
break;
default:
throw new StreamCorruptedException("Bad field type " + (int) c);
}
String name = din.readUTF();
FieldDesc desc;
if (primitive) desc = new PrimitiveFieldDesc(name, c);
else {
String className = readString().getValue();
if (className.startsWith("L")) {
className = className.substring(1, className.length() - 1);
}
className = className.replaceAll("/", ".");
desc = new ReferenceFieldDesc(name, className);
}
return desc;
}
private SArray newArray() throws IOException {
ArrayClassDesc classDesc = (ArrayClassDesc) classDesc();
int size = din.readInt();
SArray array = new SArray(classDesc.getType(), size);
newHandle(array);
ClassDesc componentClassDesc = classDesc.getComponentClassDesc();
for (int i = 0; i < size; i++)
array.set(i, componentClassDesc.read());
return array;
}
private SString newString() throws IOException {
SString s = new SString(din.readUTF());
newHandle(s);
return s;
}
private SString newLongString() throws IOException {
long len = din.readLong();
StringBuilder sb = new StringBuilder();
while (len > 0) {
int slice = (int) Math.min(len, 65535);
byte[] blen = {(byte) (slice >> 8), (byte) slice};
InputStream lenis = new ByteArrayInputStream(blen);
InputStream seqis = new SequenceInputStream(lenis, din);
DataInputStream ddin = new DataInputStream(seqis);
String s = ddin.readUTF();
assert s.length() == slice;
sb.append(s);
len -= slice;
}
return new SString(sb.toString());
}
private SObject newEnum() throws IOException {
ObjectClassDesc classDesc = classDesc();
SObject enumConst = new SObject(classDesc.getType());
newHandle(enumConst);
SString constName = readString();
classDesc.getEnumValues().add(constName.getValue());
enumConst.setField("<name>", constName);
return enumConst;
}
private void exception() throws IOException {
reset();
IOException exc = new IOException(readObject().toString());
reset();
throw new WriteAbortedException("Writing aborted", exc);
}
private SBlockData blockDataShort() throws IOException {
int len = din.readUnsignedByte();
return blockData(len);
}
private SBlockData blockDataLong() throws IOException {
int len = din.readInt();
return blockData(len);
}
private SBlockData blockData(int len) throws IOException {
byte[] data = new byte[len];
din.readFully(data);
return new SBlockData(data);
}
private void newHandle(SEntity o) {
handles.add(o);
}
private SEntity prevObject() throws IOException {
int h = din.readInt();
int i = h - baseWireHandle;
if (i < 0 || i > handles.size()) throw new StreamCorruptedException("Bad handle: " + h);
return handles.get(i);
}
private void reset() {
handles.clear();
}
public abstract static class ClassDesc extends SEntity {
private final String name;
ClassDesc(String name) {
super(name);
this.name = name;
}
@Override
public Json json() {
throw new UnsupportedOperationException();
}
public abstract String toString();
abstract SEntity read() throws IOException;
abstract Class<?> arrayComponentClass();
public String getName() {
return name;
}
}
public class ObjectClassDesc extends ClassDesc {
private final int flags;
private final List<ObjectClassDesc> hierarchy = new ArrayList<>();
private final Set<String> enumValues = new HashSet<>();
private Long serialVersionUID;
private FieldDesc[] fields = new FieldDesc[0];
private ObjectClassDesc superClassDesc;
ObjectClassDesc(String name, int flags, Long serialVersionUID) {
super(name);
this.flags = flags;
this.serialVersionUID = serialVersionUID;
}
public Long getSerialVersionUID() {
return serialVersionUID;
}
public void setSerialVersionUID(Long serialVersionUID) {
this.serialVersionUID = serialVersionUID;
}
SEntity read() throws IOException {
return readObject();
}
Class<?> arrayComponentClass() {
if (getType().equals("java.lang.String")) return String.class;
else return SEntity.class;
}
public String toString() {
return getType();
}
public FieldDesc[] getFields() {
return fields;
}
public void setFields(FieldDesc[] fields) {
this.fields = fields;
}
public int getFlags() {
return flags;
}
public void setSuperClassDesc(ObjectClassDesc superClassDesc) {
this.superClassDesc = superClassDesc;
}
public List<ObjectClassDesc> getHierarchy() {
if (hierarchy.isEmpty()) {
if (superClassDesc != null) hierarchy.addAll(superClassDesc.getHierarchy());
hierarchy.add(this);
}
return hierarchy;
}
public Set<String> getEnumValues() {
return enumValues;
}
}
public class ArrayClassDesc extends ObjectClassDesc {
private final ClassDesc componentClassDesc;
private final Class<?> arrayClass;
ArrayClassDesc(String name, int flags, long serialVersionUID) throws IOException {
super(name, flags, serialVersionUID);
String componentName = name.substring(1);
if (componentName.startsWith("[")) componentClassDesc = getArrayClassDesc(componentName, flags, null);
else if (componentName.startsWith("L")) {
componentName = componentName.substring(1, componentName.length() - 1);
componentClassDesc = getObjectClassDesc(componentName, flags, null);
} else {
if (componentName.length() > 1) throw new StreamCorruptedException("Bad array type " + name);
char typeCode = componentName.charAt(0);
componentClassDesc = primitiveClassDescFactory.forTypeCode(typeCode);
}
Class<?> componentClass = componentClassDesc.arrayComponentClass();
arrayClass = Array.newInstance(componentClass, 0).getClass();
}
Class<?> arrayComponentClass() {
return arrayClass;
}
public ClassDesc getComponentClassDesc() {
return componentClassDesc;
}
}
class PrimitiveClassDescFactory {
private final Map<Character, PrimitiveClassDesc> DESCRIPTORS = new HashMap<>();
{
String primitives = "BByte CChar DDouble FFloat IInt JLong SShort ZBoolean";
for (String prim : primitives.split(" ")) {
char typeCode = prim.charAt(0);
String readWhat = prim.substring(1);
Method readMethod;
try {
readMethod = DataInputStream.class.getMethod("read" + readWhat);
} catch (Exception e) {
throw new RuntimeException("No read method for " + readWhat, e);
}
Class<?> componentClass;
try {
Class<?> arrayClass = Class.forName("[" + typeCode);
componentClass = arrayClass.getComponentType();
} catch (Exception e) {
throw new RuntimeException("No array class for " + typeCode, e);
}
PrimitiveClassDesc desc = new PrimitiveClassDesc(typeCode, readMethod, componentClass);
DESCRIPTORS.put(typeCode, desc);
}
}
PrimitiveClassDesc forTypeCode(char c) throws IOException {
PrimitiveClassDesc desc = DESCRIPTORS.get(c);
if (desc == null) throw new StreamCorruptedException("Bad type code " + (int) c);
return desc;
}
}
public class PrimitiveClassDesc extends ClassDesc {
private final Method readMethod;
private final Class<?> componentClass;
PrimitiveClassDesc(char typeCode, Method readMethod, Class<?> componentClass) {
super(String.valueOf(typeCode));
this.readMethod = readMethod;
this.componentClass = componentClass;
}
SEntity read() throws IOException {
try {
Object wrapped = readMethod.invoke(din);
return new SPrim(wrapped);
} catch (IllegalAccessException e) {
throw new RuntimeException("Read method invoke failed", e);
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof IOException) throw (IOException) t;
else if (t instanceof RuntimeException) throw (RuntimeException) t;
else if (t instanceof Error) throw (Error) t;
else throw new RuntimeException(t.toString(), t);
}
}
Class<?> arrayComponentClass() {
return componentClass;
}
public String toString() {
return componentClass.getName();
}
}
public abstract static class FieldDesc {
private final String name;
FieldDesc(String name) {
this.name = name;
}
abstract SEntity read() throws IOException;
public abstract String toString();
public String getName() {
return this.name;
}
public abstract String getTypeName();
}
public class ReferenceFieldDesc extends FieldDesc {
private final String className;
ReferenceFieldDesc(String name, String className) {
super(name);
this.className = className;
}
SEntity read() throws IOException {
return readObject();
}
public String toString() {
return className + " " + getName();
}
@Override
public String getTypeName() {
return className;
}
}
public class PrimitiveFieldDesc extends FieldDesc {
private final PrimitiveClassDesc classDesc;
PrimitiveFieldDesc(String name, char type) throws IOException {
super(name);
classDesc = primitiveClassDescFactory.forTypeCode(type);
}
SEntity read() throws IOException {
return classDesc.read();
}
public String toString() {
return classDesc + " " + getName();
}
@Override
public String getTypeName() {
return classDesc.toString();
}
}
}
| 19,643
| 31.523179
| 116
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/deserializer/SBlockData.java
|
package org.infinispan.server.core.dataconversion.deserializer;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* Based on Serialisys by Eamonn McManus
*/
public class SBlockData extends SEntity {
private final byte[] data;
SBlockData(byte[] data) {
super("byte[]");
this.data = data;
}
@Override
public Json json() {
return Json.make("byte[" + data.length + "]");
}
}
| 427
| 19.380952
| 63
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/json/SecureTypeResolverBuilder.java
|
package org.infinispan.server.core.dataconversion.json;
import java.util.Collection;
import org.infinispan.commons.configuration.ClassAllowList;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
/**
* Builder that can produce {@link SecureTypeIdResolver} from an existing TypeIdResolver.
*
* @since 9.3
*
* @deprecated JSON to POJO conversion is deprecated and will be removed in a future version.
*/
@Deprecated
public class SecureTypeResolverBuilder extends ObjectMapper.DefaultTypeResolverBuilder {
private final ClassAllowList allowList;
protected SecureTypeResolverBuilder(ObjectMapper.DefaultTyping defaultTyping, ClassAllowList allowList) {
super(defaultTyping, LaissezFaireSubTypeValidator.instance);
this.allowList = allowList;
}
protected TypeIdResolver idResolver(MapperConfig<?> config,
JavaType baseType, PolymorphicTypeValidator subtypeValidator,
Collection<NamedType> subtypes, boolean forSer, boolean forDeser) {
TypeIdResolver result = super.idResolver(config, baseType, subtypeValidator, subtypes, forSer, forDeser);
return new SecureTypeIdResolver(result, allowList);
}
}
| 1,603
| 40.128205
| 111
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/dataconversion/json/SecureTypeIdResolver.java
|
package org.infinispan.server.core.dataconversion.json;
import java.io.IOException;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
/**
* Jackson TypeIdResolver that checks the serialization allow list before deserializing JSON types.
*
* @since 9.3
*
* @deprecated JSON to POJO conversion is deprecated and will be removed in a future version.
*/
@Deprecated
public class SecureTypeIdResolver implements TypeIdResolver {
protected final static Log logger = LogFactory.getLog(SecureTypeIdResolver.class, Log.class);
private TypeIdResolver internalTypeIdResolver;
private final ClassAllowList classAllowList;
SecureTypeIdResolver(TypeIdResolver typeIdResolver, ClassAllowList classAllowList) {
this.internalTypeIdResolver = typeIdResolver;
this.classAllowList = classAllowList;
}
@Override
public void init(JavaType baseType) {
internalTypeIdResolver.init(baseType);
}
@Override
public String idFromValue(Object value) {
return internalTypeIdResolver.idFromValue(value);
}
@Override
public String idFromValueAndType(Object value, Class<?> suggestedType) {
return internalTypeIdResolver.idFromValueAndType(value, suggestedType);
}
@Override
public String idFromBaseType() {
return internalTypeIdResolver.idFromBaseType();
}
@Override
public String getDescForKnownTypeIds() {
return internalTypeIdResolver.getDescForKnownTypeIds();
}
@Override
public JavaType typeFromId(DatabindContext databindContext, String id) throws IOException {
JavaType javaType = internalTypeIdResolver.typeFromId(databindContext, id);
Class<?> clazz = javaType.getRawClass();
String className = clazz.getName();
if (!classAllowList.isSafeClass(className)) {
throw logger.errorDeserializing(className);
}
return javaType;
}
@Override
public JsonTypeInfo.Id getMechanism() {
return internalTypeIdResolver.getMechanism();
}
}
| 2,307
| 29.773333
| 99
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/factories/NettyEventLoopFactory.java
|
package org.infinispan.server.core.factories;
import static org.infinispan.factories.KnownComponentNames.getDefaultThreadPrio;
import static org.infinispan.factories.KnownComponentNames.getDefaultThreads;
import static org.infinispan.factories.KnownComponentNames.shortened;
import static org.infinispan.server.core.transport.NettyTransport.buildEventLoop;
import java.util.concurrent.ThreadFactory;
import org.infinispan.commons.executors.ThreadPoolExecutorFactory;
import org.infinispan.factories.AbstractComponentFactory;
import org.infinispan.factories.AutoInstantiableFactory;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.threads.DefaultThreadFactory;
import org.infinispan.factories.threads.NonBlockingThreadFactory;
import org.infinispan.factories.threads.NonBlockingThreadPoolExecutorFactory;
import org.infinispan.server.core.transport.NonRecursiveEventLoopGroup;
import io.netty.channel.EventLoopGroup;
@DefaultFactoryFor(classes = EventLoopGroup.class)
public class NettyEventLoopFactory extends AbstractComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String componentName) {
ThreadFactory threadFactory = globalConfiguration.nonBlockingThreadPool().threadFactory();
if (threadFactory == null) {
threadFactory = new NonBlockingThreadFactory("ISPN-non-blocking-thread-group",
getDefaultThreadPrio(KnownComponentNames.NON_BLOCKING_EXECUTOR), DefaultThreadFactory.DEFAULT_PATTERN,
globalConfiguration.transport().nodeName(), shortened(KnownComponentNames.NON_BLOCKING_EXECUTOR));
}
ThreadPoolExecutorFactory<?> tpef = globalConfiguration.nonBlockingThreadPool().threadPoolFactory();
int threadAmount = tpef instanceof NonBlockingThreadPoolExecutorFactory ?
((NonBlockingThreadPoolExecutorFactory) tpef).maxThreads() :
getDefaultThreads(KnownComponentNames.NON_BLOCKING_EXECUTOR);
// Unfortunately, netty doesn't allow us to specify a max number of queued tasks and rejection policy at the same
// time and the former has actually been deprecated, so we do not honor these settings when running in the server
// which means the non blocking executor may have an unbounded queue, depending upon netty implementation
return new NonRecursiveEventLoopGroup(buildEventLoop(threadAmount, threadFactory,
"non-blocking-thread-netty"));
}
}
| 2,526
| 56.431818
| 119
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/factories/NettyIOFactory.java
|
package org.infinispan.server.core.factories;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.factories.AbstractComponentFactory;
import org.infinispan.factories.AutoInstantiableFactory;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.util.concurrent.BlockingTaskAwareExecutorServiceImpl;
import io.netty.channel.EventLoopGroup;
/**
* Factory to create netty io event loop and replace the non blocking executor with it
*
* @author Pedro Ruivo
* @author William Burns
* @since 13.0
*/
@DefaultFactoryFor(names = KnownComponentNames.NON_BLOCKING_EXECUTOR)
public class NettyIOFactory extends AbstractComponentFactory implements AutoInstantiableFactory {
@Inject
protected BasicComponentRegistry basicComponentRegistry;
@Override
public Object construct(String componentName) {
if (componentName.equals(KnownComponentNames.NON_BLOCKING_EXECUTOR)) {
ComponentRef<EventLoopGroup> ref = basicComponentRegistry.getComponent(EventLoopGroup.class);
// This means our event loop can't have a cyclical dependency on us otherwise we will get stuck
EventLoopGroup runningEventLoopGroup = ref.running();
return new BlockingTaskAwareExecutorServiceImpl(runningEventLoopGroup, globalComponentRegistry.getTimeService());
} else {
throw new CacheConfigurationException("Unknown named executor " + componentName);
}
}
}
| 1,677
| 40.95
| 122
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/AdminOperationParameter.java
|
package org.infinispan.server.core.admin;
import java.util.Map;
import java.util.Optional;
/**
* AdminOperationParameters
*
* @author Tristan Tarrant
* @since 9.1
*/
public enum AdminOperationParameter {
CACHE_NAME,
CACHE_TEMPLATE,
FLAGS;
public String require(Map<String, String> params) {
return params.computeIfAbsent(name(), k -> {
throw new IllegalArgumentException("Required argument '" + k + "' is missing");
});
}
public Optional<String> optional(Map<String, String> params) {
return Optional.ofNullable(params.get(name()));
}
}
| 594
| 21.037037
| 88
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/AdminServerTask.java
|
package org.infinispan.server.core.admin;
import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.infinispan.commons.api.CacheContainerAdmin.AdminFlag;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.core.logging.Log;
import org.infinispan.tasks.Task;
import org.infinispan.tasks.TaskContext;
import org.infinispan.util.logging.LogFactory;
/**
* Common base for admin server tasks
*
* @author Tristan Tarrant
* @since 9.0
*/
public abstract class AdminServerTask<T> implements Task {
protected static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass(), Log.class);
@Override
public final String getName() {
return "@@" + getTaskContextName() + "@" + getTaskOperationName();
}
@Override
public String getType() {
return AdminServerTask.class.getSimpleName();
}
public final T execute(TaskContext taskContext) {
Map<String, ?> raw = taskContext.getParameters().orElse(Collections.emptyMap());
Map<String, List<String>> parameters = raw.entrySet().stream().collect(
Collectors.toMap(Map.Entry::getKey, entry -> {
Object value = entry.getValue();
if (value instanceof String) {
return Collections.singletonList((String) value);
} else if (value instanceof String[]) {
return Arrays.asList((String[]) value);
} else if (value instanceof List) {
return (List)value;
} else if (value instanceof byte[]) {
return Collections.singletonList(new String((byte[]) value, StandardCharsets.UTF_8));
} else {
throw log.illegalParameterType(entry.getKey(), value.getClass());
}
}));
List<String> sFlags = parameters.remove("flags");
return execute(
taskContext.getCacheManager(),
parameters,
sFlags != null ? AdminFlag.fromString(sFlags.get(0)) : EnumSet.noneOf(AdminFlag.class)
);
}
protected String requireParameter(Map<String, List<String>> parameters, String parameter) {
List<String> v = parameters.get(parameter);
if (v == null) {
throw log.missingRequiredAdminTaskParameter(getName(), parameter);
} else {
return v.get(0);
}
}
protected String getParameter(Map<String, List<String>> parameters, String parameter) {
List<String> v = parameters.get(parameter);
return v == null ? null : v.get(0);
}
protected abstract T execute(EmbeddedCacheManager cacheManager, Map<String, List<String>> parameters, EnumSet<AdminFlag> adminFlags);
public abstract String getTaskContextName();
public abstract String getTaskOperationName();
}
| 2,982
| 34.511905
| 136
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/AdminOperation.java
|
package org.infinispan.server.core.admin;
/**
* AdminOperations
* @author Tristan Tarrant
* @since 9.1
*/
public enum AdminOperation {
CACHE_CREATE,
CACHE_REMOVE;
}
| 176
| 13.75
| 41
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/AdminOperationsHandler.java
|
package org.infinispan.server.core.admin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import javax.security.auth.Subject;
import org.infinispan.commons.CacheException;
import org.infinispan.security.Security;
import org.infinispan.tasks.Task;
import org.infinispan.tasks.TaskContext;
import org.infinispan.tasks.spi.TaskEngine;
import org.infinispan.util.concurrent.BlockingManager;
/**
* AdminOperationsHandler is a special {@link TaskEngine} which can handle admin tasks
*
* @author Tristan Tarrant
* @since 9.1
*/
public abstract class AdminOperationsHandler implements TaskEngine {
final Map<String, AdminServerTask> tasks;
protected AdminOperationsHandler(AdminServerTask<?>... tasks) {
this.tasks = new HashMap<>(tasks.length);
for (AdminServerTask<?> task : tasks) {
this.tasks.put(task.getName(), task);
}
}
@Override
public String getName() {
return this.getClass().getSimpleName();
}
@Override
public List<Task> getTasks() {
return new ArrayList(tasks.values());
}
@Override
public <T> CompletionStage<T> runTask(String taskName, TaskContext context, BlockingManager blockingManager) {
AdminServerTask<T> task = tasks.get(taskName);
Subject subject = context.getSubject().orElse(Security.getSubject());
return blockingManager.supplyBlocking(() -> {
try {
return Security.doAs(subject, () -> task.execute(context));
} catch (CacheException e) {
throw e;
} catch (Exception e) {
throw new CacheException(e);
}
}, taskName);
}
@Override
public boolean handles(String taskName) {
return tasks.containsKey(taskName);
}
}
| 1,826
| 27.546875
| 113
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/embeddedserver/CacheReindexTask.java
|
package org.infinispan.server.core.admin.embeddedserver;
import static org.infinispan.util.concurrent.CompletionStages.join;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.Cache;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.query.Search;
import org.infinispan.server.core.admin.AdminServerTask;
/**
* Admin operation to reindex a cache
* Parameters:
* <ul>
* <li><strong>name</strong> the name of the cache to reindex</li>
* <li><strong>flags</strong> unused</li>
* </ul>
*
* @author Tristan Tarrant
* @since 9.1
*/
public class CacheReindexTask extends AdminServerTask<Void> {
private static final Set<String> PARAMETERS = Collections.singleton("name");
@Override
public String getTaskContextName() {
return "cache";
}
@Override
public String getTaskOperationName() {
return "reindex";
}
@Override
public Set<String> getParameters() {
return PARAMETERS;
}
@Override
protected Void execute(EmbeddedCacheManager cacheManager, Map<String, List<String>> parameters, EnumSet<CacheContainerAdmin.AdminFlag> adminFlags) {
if(!adminFlags.isEmpty())
throw new UnsupportedOperationException();
String name = requireParameter(parameters, "name");
Cache<Object, Object> cache = cacheManager.getCache(name);
join(Search.getIndexer(cache).run());
return null;
}
}
| 1,555
| 25.827586
| 151
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/embeddedserver/CacheGetOrCreateTask.java
|
package org.infinispan.server.core.admin.embeddedserver;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* Admin operation to create a cache
* Parameters:
* <ul>
* <li><strong>name</strong> the name of the cache to create</li>
* <li><strong>template</strong> the name of the template to use</li>
* <li><strong>configuration</strong> the XML configuration to use</li>
* <li><strong>flags</strong> any flags, e.g. PERMANENT</li>
* </ul>
*
* @author Tristan Tarrant
* @since 9.2
*/
public class CacheGetOrCreateTask extends CacheCreateTask {
@Override
public String getTaskContextName() {
return "cache";
}
@Override
public String getTaskOperationName() {
return "getorcreate";
}
@Override
protected Void execute(EmbeddedCacheManager cacheManager, Map<String, List<String>> parameters, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
String name = requireParameter(parameters, "name");
String template = getParameter(parameters, "template");
String configuration = getParameter(parameters, "configuration");
if (configuration != null) {
Configuration config = getConfigurationBuilder(name, configuration).build();
cacheManager.administration().withFlags(flags).getOrCreateCache(name, config);
} else {
cacheManager.administration().withFlags(flags).getOrCreateCache(name, template);
}
return null;
}
}
| 1,629
| 30.960784
| 146
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/embeddedserver/TemplateNamesTask.java
|
package org.infinispan.server.core.admin.embeddedserver;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.core.admin.AdminServerTask;
/**
* Admin operation to obtain a list of caches
*
* @author Tristan Tarrant
* @since 9.2
*/
public class TemplateNamesTask extends AdminServerTask<byte[]> {
@Override
public String getTaskContextName() {
return "cache";
}
@Override
public String getTaskOperationName() {
return "templates";
}
@Override
public Set<String> getParameters() {
return Collections.emptySet();
}
@Override
protected byte[] execute(EmbeddedCacheManager cacheManager, Map<String, List<String>> parameters, EnumSet<CacheContainerAdmin.AdminFlag> adminFlags) {
Set<String> cacheNames = cacheManager.getCacheConfigurationNames();
StringBuilder sb = new StringBuilder("[");
for(String s : cacheNames) {
if (sb.length() > 1)
sb.append(',');
sb.append('"');
sb.append(s);
sb.append('"');
}
sb.append(']');
return sb.toString().getBytes(StandardCharsets.UTF_8);
}
}
| 1,370
| 25.882353
| 153
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/embeddedserver/CacheCreateTask.java
|
package org.infinispan.server.core.admin.embeddedserver;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.configuration.parsing.ParserRegistry;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.core.admin.AdminServerTask;
/**
* Admin operation to create a cache
* Parameters:
* <ul>
* <li><strong>name</strong> the name of the cache to create</li>
* <li><strong>flags</strong> any flags, e.g. PERMANENT</li>
* </ul>
*
* @author Tristan Tarrant
* @since 9.1
*/
public class CacheCreateTask extends AdminServerTask<Void> {
private static final Set<String> PARAMETERS;
static {
Set<String> params = new HashSet<>(3);
params.add("name");
params.add("template");
params.add("configuration");
PARAMETERS = Collections.unmodifiableSet(params);
}
@Override
public String getTaskContextName() {
return "cache";
}
@Override
public String getTaskOperationName() {
return "create";
}
@Override
public Set<String> getParameters() {
return PARAMETERS;
}
@Override
protected Void execute(EmbeddedCacheManager cacheManager, Map<String, List<String>> parameters, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
String name = requireParameter(parameters, "name");
String template = getParameter(parameters, "template");
String configuration = getParameter(parameters, "configuration");
if (configuration != null) {
Configuration config = getConfigurationBuilder(name, configuration).build();
if (!cacheManager.getCacheManagerConfiguration().isClustered() && config.clustering().cacheMode().isClustered()) {
throw log.cannotCreateClusteredCache();
}
cacheManager.administration().withFlags(flags).createCache(name, config);
} else {
cacheManager.administration().withFlags(flags).createCache(name, template);
}
return null;
}
protected ConfigurationBuilder getConfigurationBuilder(String name, String configuration) {
ParserRegistry parser = new ParserRegistry();
ConfigurationBuilderHolder builderHolder = parser.parse(configuration, null); // Use type auto-detection
Map<String, ConfigurationBuilder> builders = builderHolder.getNamedConfigurationBuilders();
if (builders.size() == 0) {
throw log.missingCacheConfiguration(name, configuration);
} else if (builders.size() > 1) {
throw log.configurationMustContainSingleCache(name, configuration);
}
return builders.values().iterator().next();
}
}
| 2,964
| 34.297619
| 146
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/embeddedserver/CacheRemoveTask.java
|
package org.infinispan.server.core.admin.embeddedserver;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.core.admin.AdminServerTask;
/**
* Admin operation to remove a cache
* Parameters:
* <ul>
* <li><strong>name</strong> the name of the cache to remove</li>
* <li><strong>flags</strong> </li>
* </ul>
*
* @author Tristan Tarrant
* @since 9.1
*/
public class CacheRemoveTask extends AdminServerTask<Void> {
private static final Set<String> PARAMETERS = Collections.singleton("name");
@Override
public String getTaskContextName() {
return "cache";
}
@Override
public String getTaskOperationName() {
return "remove";
}
@Override
public Set<String> getParameters() {
return PARAMETERS;
}
@Override
protected Void execute(EmbeddedCacheManager cacheManager, Map<String, List<String>> parameters, EnumSet<CacheContainerAdmin.AdminFlag> adminFlags) {
String name = requireParameter(parameters,"name");
cacheManager.administration().withFlags(adminFlags).removeCache(name);
return null;
}
}
| 1,292
| 25.387755
| 151
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/embeddedserver/CacheUpdateConfigurationAttributeTask.java
|
package org.infinispan.server.core.admin.embeddedserver;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.Cache;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.commons.configuration.attributes.Attribute;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.core.admin.AdminServerTask;
/**
* Administrative operation to update a specific configuration attribute for a given cache with the following parameters:
* Parameters:
* <ul>
* <li><strong>name</strong> specifies the cache for which its configuration attribute will be updated.</li>
* <li><strong>attribute</strong> the path of the attribute we want to change, e.g. `indexing.indexed-entities`.</li>
* <li><strong>value</strong> the new value to apply to the attribute, e.g. `org.infinispan.Developer org.infinispan.Engineer`</li>
* <li><strong>flags</strong> any flags, e.g. PERMANENT</li>
* </ul>
* <p>
* Note: the attribute is supposed to be mutable in order to be mutated by this operation.
*
* @author Fabio Massimo Ercoli
* @since 14.0.7
*/
public class CacheUpdateConfigurationAttributeTask extends AdminServerTask<Void> {
private static final Set<String> PARAMETERS = Set.of("name", "attribute", "value");
@Override
public String getTaskContextName() {
return "cache";
}
@Override
public String getTaskOperationName() {
return "updateConfigurationAttribute";
}
@Override
public Set<String> getParameters() {
return PARAMETERS;
}
@Override
protected Void execute(EmbeddedCacheManager cacheManager, Map<String, List<String>> parameters,
EnumSet<CacheContainerAdmin.AdminFlag> flags) {
String cacheName = requireParameter(parameters, "name");
String attributeName = requireParameter(parameters, "attribute");
String attributeValue = requireParameter(parameters, "value");
Cache<Object, Object> cache = cacheManager.getCache(cacheName);
Configuration config = cache.getCacheConfiguration();
Attribute<?> attribute = config.findAttribute(attributeName);
attribute.fromString(attributeValue);
flags.add(CacheContainerAdmin.AdminFlag.UPDATE);
// doing what is done on CacheGetOrCreateTask
cacheManager.administration().withFlags(flags).getOrCreateCache(cacheName, config);
return null;
}
}
| 2,515
| 35.463768
| 134
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/embeddedserver/EmbeddedServerAdminOperationHandler.java
|
package org.infinispan.server.core.admin.embeddedserver;
import org.infinispan.server.core.admin.AdminOperationsHandler;
/**
* EmbeddedServerAdminOperationHandler is an implementation of {@link AdminOperationsHandler} which uses
* {@link org.infinispan.commons.api.CacheContainerAdmin} to apply changes to the cache manager configuration
*
* @since 9.1
*/
public class EmbeddedServerAdminOperationHandler extends AdminOperationsHandler {
public EmbeddedServerAdminOperationHandler() {
super(
new CacheCreateTask(),
new CacheGetOrCreateTask(),
new CacheNamesTask(),
new CacheRemoveTask(),
new CacheReindexTask(),
new CacheUpdateIndexSchemaTask(),
new CacheUpdateConfigurationAttributeTask(),
new TemplateCreateTask(),
new TemplateRemoveTask(),
new TemplateNamesTask()
);
}
}
| 920
| 31.892857
| 109
|
java
|
null |
infinispan-main/server/core/src/main/java/org/infinispan/server/core/admin/embeddedserver/CacheUpdateIndexSchemaTask.java
|
package org.infinispan.server.core.admin.embeddedserver;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.Cache;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.query.impl.ComponentRegistryUtils;
import org.infinispan.search.mapper.mapping.SearchMapping;
import org.infinispan.server.core.admin.AdminServerTask;
/**
* Administrative operation to update the index schema for a cache with the following parameters:
* Parameters:
* <ul>
* <li><strong>name</strong> specifies the cache for which its index schema will be updated.</li>
* <li><strong>flags</strong> unused</li>
* </ul>
*
* @author Fabio Massimo Ercoli
* @since 14.0
*/
public class CacheUpdateIndexSchemaTask extends AdminServerTask<Void> {
private static final Set<String> PARAMETERS = Collections.singleton("name");
@Override
public String getTaskContextName() {
return "cache";
}
@Override
public String getTaskOperationName() {
return "updateindexschema";
}
@Override
public Set<String> getParameters() {
return PARAMETERS;
}
@Override
protected Void execute(EmbeddedCacheManager cacheManager, Map<String, List<String>> parameters, EnumSet<CacheContainerAdmin.AdminFlag> adminFlags) {
if(!adminFlags.isEmpty())
throw new UnsupportedOperationException();
String name = requireParameter(parameters, "name");
Cache<Object, Object> cache = cacheManager.getCache(name);
SearchMapping searchMapping = ComponentRegistryUtils.getSearchMapping(cache);
searchMapping.restart();
return null;
}
}
| 1,755
| 28.762712
| 151
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.