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/core/src/main/java/org/infinispan/configuration/global/GlobalStatePathConfiguration.java
|
package org.infinispan.configuration.global;
import org.infinispan.commons.configuration.attributes.Attribute;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.configuration.parsing.ParseUtils;
public class GlobalStatePathConfiguration {
public static final AttributeDefinition<String> PATH = AttributeDefinition.builder("path", null, String.class)
.initializer(() -> System.getProperty("user.dir"))
.immutable().build();
public static final AttributeDefinition<String> RELATIVE_TO = AttributeDefinition.builder("relativeTo", null, String.class).immutable().build();
private final Attribute<String> path;
private final Attribute<String> relativeTo;
private final String elementName;
private final String location;
public static AttributeSet attributeDefinitionSet() {
return new AttributeSet(GlobalStateConfiguration.class, PATH, RELATIVE_TO);
}
private final AttributeSet attributes;
public GlobalStatePathConfiguration(AttributeSet attributes, String elementName) {
this.attributes = attributes.checkProtection();
this.path = attributes.attribute(PATH);
this.relativeTo = attributes.attribute(RELATIVE_TO);
this.elementName = elementName;
this.location = ParseUtils.resolvePath(path.get(), relativeTo.get());
}
public AttributeSet attributes() {
return attributes;
}
public String getLocation() {
return location;
}
public String path() {
return path.get();
}
public String relativeTo() {
return relativeTo.get();
}
String elementName() {
return elementName;
}
public boolean isModified() {
return path.isModified() || relativeTo.isModified();
}
}
| 1,841
| 30.220339
| 147
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/global/StackConfigurationBuilder.java
|
package org.infinispan.configuration.global;
import static org.infinispan.configuration.global.StackConfiguration.EXTENDS;
import static org.infinispan.configuration.global.StackConfiguration.NAME;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.remoting.transport.jgroups.EmbeddedJGroupsChannelConfigurator;
import org.infinispan.remoting.transport.jgroups.JGroupsChannelConfigurator;
/*
* @since 10.0
*/
public class StackConfigurationBuilder extends AbstractGlobalConfigurationBuilder implements StackBuilder<StackConfiguration> {
private final AttributeSet attributes;
private final JGroupsConfigurationBuilder jgroups;
private EmbeddedJGroupsChannelConfigurator configurator;
StackConfigurationBuilder(String name, JGroupsConfigurationBuilder jgroups) {
super(jgroups.getGlobalConfig());
this.jgroups = jgroups;
attributes = StackConfiguration.attributeDefinitionSet();
attributes.attribute(NAME).set(name);
}
public AttributeSet attributes() {
return attributes;
}
public StackConfigurationBuilder extend(String extend) {
attributes.attribute(EXTENDS).set(extend);
return this;
}
public StackConfigurationBuilder channelConfigurator(EmbeddedJGroupsChannelConfigurator configurator) {
String extend = attributes.attribute(EXTENDS).get();
this.configurator = extend == null ? configurator :
new EmbeddedJGroupsChannelConfigurator(
configurator.getName(),
configurator.getUncombinedProtocolStack(),
configurator.getUncombinedRemoteSites(),
extend
);
return this;
}
@Override
public StackConfiguration create() {
return new StackConfiguration(attributes.protect(), configurator);
}
@Override
public StackConfigurationBuilder read(StackConfiguration template, Combine combine) {
attributes.read(template.attributes(), combine);
this.configurator = template.configurator();
return this;
}
@Override
public JGroupsChannelConfigurator getConfigurator() {
return configurator;
}
}
| 2,232
| 33.890625
| 127
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/Schema.java
|
package org.infinispan.configuration.parsing;
import org.infinispan.commons.configuration.io.ConfigurationSchemaVersion;
import org.infinispan.commons.util.Version;
/**
* Schema.
*
* @author Tristan Tarrant
* @since 8.1
*/
public class Schema implements ConfigurationSchemaVersion {
private final String uri;
private final int major;
private final int minor;
public Schema(String uri, int major, int minor) {
this.uri = uri;
this.major = major;
this.minor = minor;
}
@Override
public String getURI() {
return uri;
}
@Override
public int getMajor() {
return major;
}
@Override
public int getMinor() {
return minor;
}
@Override
public boolean since(int major, int minor) {
return (this.major > major) || ((this.major == major) && (this.minor >= minor));
}
public static Schema fromNamespaceURI(String namespaceURI) {
int major = Integer.parseInt(Version.getMajor());
int minor = Integer.parseInt(Version.getMinor());
if (namespaceURI.startsWith("uri:") || namespaceURI.startsWith("urn:")) {
int colon = namespaceURI.lastIndexOf(':');
String uri = namespaceURI.substring(0, colon);
String version = namespaceURI.substring(colon + 1);
String[] split = version.split("\\.");
try {
major = Integer.parseInt(split[0]);
minor = Integer.parseInt(split[1]);
} catch (NumberFormatException e) {
// Ignore
}
return new Schema(uri, major, minor);
} else {
return new Schema("", major, minor);
}
}
}
| 1,646
| 24.734375
| 86
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/ParserScope.java
|
package org.infinispan.configuration.parsing;
/**
* ParserScope indicates the configuration parser scope.
* @author Tristan Tarrant
* @since 9.0
*/
public enum ParserScope {
/**
* The top-level scope at which cache containers, jgroups and threads are defined
*/
GLOBAL,
/**
* The cache-container scope
*/
CACHE_CONTAINER,
/**
* The cache scope
*/
CACHE,
/**
* The cache template scope
*/
CACHE_TEMPLATE
}
| 465
| 17.64
| 84
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/SFSToSIFSConfigurationBuilder.java
|
package org.infinispan.configuration.parsing;
import org.infinispan.commons.configuration.attributes.Attribute;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.persistence.sifs.configuration.DataConfiguration;
import org.infinispan.persistence.sifs.configuration.IndexConfiguration;
import org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration;
import org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfigurationBuilder;
import org.infinispan.util.logging.Log;
public class SFSToSIFSConfigurationBuilder extends SoftIndexFileStoreConfigurationBuilder {
public SFSToSIFSConfigurationBuilder(PersistenceConfigurationBuilder builder) {
super(builder);
}
@Override
public SoftIndexFileStoreConfiguration create() {
return new SFSToSIFSConfiguration(attributes.protect(), async.create(), index.create(), data.create());
}
@Override
public void validate(GlobalConfiguration globalConfig) {
// Without global state we need to make sure the index location is set to something based on the data location.
// The user may have configured only the path for the SingleFileStore
if (!globalConfig.globalState().enabled()) {
Attribute<String> indexLocation = index.attributes().attribute(IndexConfiguration.INDEX_LOCATION);
if (!indexLocation.isModified()) {
Attribute<String> dataLocation = data.attributes().attribute(DataConfiguration.DATA_LOCATION);
if (dataLocation.isModified()) {
String indexLocationString = dataLocation.get() + "-index";
Log.CONFIG.debugf("Setting index location for migrated FileStore to %s", indexLocationString);
indexLocation.set(indexLocationString);
}
}
}
super.validate(globalConfig);
}
}
| 1,940
| 47.525
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/Element.java
|
package org.infinispan.configuration.parsing;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commons.configuration.io.NamingStrategy;
/**
* An enumeration of all the recognized XML element local names, by name.
*
* @author Pete Muir
*/
public enum Element {
// must be first
UNKNOWN(null),
// KEEP THESE IN ALPHABETICAL ORDER!
ADVANCED_EXTERNALIZER,
ADVANCED_EXTERNALIZERS,
ALLOW_LIST,
ASYNC,
AUTHORIZATION,
BACKUP,
BACKUPS,
BACKUP_FOR,
BINARY,
BLOCKING_BOUNDED_QUEUE_THREAD_POOL,
CACHE_CONTAINER,
CACHES,
CACHED_THREAD_POOL,
CLASS,
CLUSTERING,
CLUSTER_LOADER,
CLUSTER_STORE,
CLUSTER_PERMISSION_MAPPER,
CLUSTER_ROLE_MAPPER,
COMMON_NAME_PRINCIPAL_TRANSFORMER,
COMMON_NAME_ROLE_MAPPER,
COMPATIBILITY,
CUSTOM_INTERCEPTORS,
CUSTOM_CONFIGURATION_STORAGE,
CUSTOM_PERMISSION_MAPPER,
CUSTOM_ROLE_MAPPER,
DATA,
DATA_CONTAINER,
DEFAULT,
DISTRIBUTED_CACHE,
DISTRIBUTED_CACHE_CONFIGURATION,
ENCODING,
EVICTION,
EXPIRATION,
FILE_STORE,
GROUPS,
GROUPER,
GLOBAL,
GLOBAL_STATE,
HASH,
HEAP,
JGROUPS,
IDENTITY_ROLE_MAPPER,
IMMUTABLE_CONFIGURATION_STORAGE,
INDEX,
INDEXED_ENTITIES,
INDEXED_ENTITY,
INDEXING,
INDEX_READER,
INDEX_SHARDING,
INDEX_WRITER,
INDEX_MERGE,
INTERCEPTOR,
INVALIDATION_CACHE,
INVALIDATION_CACHE_CONFIGURATION,
JMX,
JMX_STATISTICS,
KEY_DATA_TYPE("key"),
KEY_TRANSFORMER,
KEY_TRANSFORMERS,
L1,
LOADER,
LOCAL_CACHE,
LOCAL_CACHE_CONFIGURATION,
PERSISTENCE,
PERSISTENT_LOCATION,
LOCKING,
MANAGED_CONFIGURATION_STORAGE,
MEMORY,
METRICS,
MODULES,
OBJECT,
OFF_HEAP,
NAME_REWRITER,
NON_BLOCKING_BOUNDED_QUEUE_THREAD_POOL,
OVERLAY_CONFIGURATION_STORAGE,
PARTITION_HANDLING,
PROPERTIES,
PROPERTY,
QUERY,
RECOVERY,
REGEX,
REGEX_PRINCIPAL_TRANSFORMER,
REMOTE_SITE,
REMOTE_SITES,
REPLICATED_CACHE,
REPLICATED_CACHE_CONFIGURATION,
ROLE,
ROLES,
ROOT,
SERIALIZATION_CONTEXT_INITIALIZER("context-initializer"),
SERIALIZATION_CONTEXT_INITIALIZERS("context-initializers"),
SHARED_PERSISTENT_LOCATION,
SCHEDULED_THREAD_POOL,
SECURITY,
SERIALIZATION,
SHUTDOWN,
SINGLE_FILE_STORE,
SITE,
SITES,
STATE_TRANSFER,
STACK,
STACKS,
STACK_FILE,
STORE,
STORE_AS_BINARY,
STORE_MIGRATOR,
SYNC,
TAKE_OFFLINE,
TEMPORARY_LOCATION,
THREADS,
THREAD_FACTORIES,
THREAD_FACTORY,
THREAD_POOLS,
TRANSACTION,
TRANSPORT,
UNSAFE,
VALUE_DATA_TYPE("value"),
VERSIONING,
VOLATILE_CONFIGURATION_STORAGE,
@Deprecated
WHITE_LIST,
WRITE_BEHIND,
CASE_PRINCIPAL_TRANSFORMER;
private final String name;
Element(final String name) {
this.name = name;
}
Element() {
this.name = NamingStrategy.KEBAB_CASE.convert(name()).toLowerCase();
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Element> MAP;
static {
final Map<String, Element> map = new HashMap<>(8);
for (Element element : values()) {
final String name = element.getLocalName();
if (name != null) map.put(name, element);
}
MAP = map;
}
public static Element forName(String localName) {
final Element element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
public static boolean isCacheElement(String localName) {
final Element element = forName(localName);
return element == LOCAL_CACHE
|| element == LOCAL_CACHE_CONFIGURATION
|| element == INVALIDATION_CACHE
|| element == INVALIDATION_CACHE_CONFIGURATION
|| element == REPLICATED_CACHE
|| element == REPLICATED_CACHE_CONFIGURATION
|| element == DISTRIBUTED_CACHE
|| element == DISTRIBUTED_CACHE_CONFIGURATION;
}
@Override
public String toString() {
return name;
}
}
| 4,311
| 21
| 76
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/SFSToSIFSConfiguration.java
|
package org.infinispan.configuration.parsing;
import org.infinispan.commons.configuration.BuiltBy;
import org.infinispan.commons.configuration.ConfigurationFor;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.configuration.cache.AsyncStoreConfiguration;
import org.infinispan.persistence.sifs.configuration.DataConfiguration;
import org.infinispan.persistence.sifs.configuration.IndexConfiguration;
import org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration;
@BuiltBy(SFSToSIFSConfigurationBuilder.class)
@ConfigurationFor(SFSToSIFSStore.class)
public class SFSToSIFSConfiguration extends SoftIndexFileStoreConfiguration {
public SFSToSIFSConfiguration(AttributeSet attributes, AsyncStoreConfiguration async,
IndexConfiguration indexConfiguration, DataConfiguration dataConfiguration) {
super(attributes, async, indexConfiguration, dataConfiguration);
}
}
| 948
| 48.947368
| 88
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/ParseUtils.java
|
package org.infinispan.configuration.parsing;
import static org.infinispan.commons.util.StringPropertyReplacer.replaceProperties;
import static org.infinispan.util.logging.Log.CONFIG;
import java.io.File;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.configuration.io.ConfigurationReader;
import org.infinispan.commons.configuration.io.ConfigurationReaderException;
import org.infinispan.commons.util.Util;
/**
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public final class ParseUtils {
private ParseUtils() {
}
public static Element nextElement(ConfigurationReader reader) throws ConfigurationReaderException {
if (reader.nextElement() == ConfigurationReader.ElementType.END_ELEMENT) {
return null;
}
return Element.forName(reader.getLocalName());
}
/**
* Get an exception reporting an unexpected XML element.
*
* @param reader the stream reader
* @return the exception
*/
public static ConfigurationReaderException unexpectedElement(final ConfigurationReader reader) {
return new ConfigurationReaderException("Unexpected element '" + reader.getLocalName() + "' encountered", reader.getLocation());
}
public static <T extends Enum<T>> ConfigurationReaderException unexpectedElement(final ConfigurationReader reader, T element) {
return unexpectedElement(reader, element.toString());
}
public static ConfigurationReaderException unexpectedElement(final ConfigurationReader reader, String element) {
return new ConfigurationReaderException("Unexpected element '" + element + "' encountered", reader.getLocation());
}
/**
* Get an exception reporting an unexpected end tag for an XML element.
*
* @param reader the stream reader
* @return the exception
*/
public static ConfigurationReaderException unexpectedEndElement(final ConfigurationReader reader) {
return new ConfigurationReaderException("Unexpected end of element '" + reader.getLocalName() + "' encountered", reader.getLocation());
}
/**
* Get an exception reporting an unexpected XML attribute.
*
* @param reader the stream reader
* @param index the attribute index
* @return the exception
*/
public static ConfigurationReaderException unexpectedAttribute(final ConfigurationReader reader, final int index) {
return new ConfigurationReaderException("Unexpected attribute '" + reader.getAttributeName(index) + "' encountered",
reader.getLocation());
}
/**
* Get an exception reporting an unexpected XML attribute.
*
* @param reader the stream reader
* @param name the attribute name
* @return the exception
*/
public static ConfigurationReaderException unexpectedAttribute(final ConfigurationReader reader, final String name) {
return new ConfigurationReaderException("Unexpected attribute '" + name + "' encountered",
reader.getLocation());
}
/**
* Get an exception reporting an invalid XML attribute value.
*
* @param reader the stream reader
* @param index the attribute index
* @return the exception
*/
public static ConfigurationReaderException invalidAttributeValue(final ConfigurationReader reader, final int index) {
return new ConfigurationReaderException("Invalid value '" + reader.getAttributeValue(index) + "' for attribute '"
+ reader.getAttributeName(index) + "'", reader.getLocation());
}
/**
* Get an exception reporting a missing, required XML attribute.
*
* @param reader the stream reader
* @param required a set of enums whose toString method returns the attribute name
* @return the exception
*/
public static ConfigurationReaderException missingRequired(final ConfigurationReader reader, final Set<?> required) {
final StringBuilder b = new StringBuilder();
Iterator<?> iterator = required.iterator();
while (iterator.hasNext()) {
final Object o = iterator.next();
b.append(o.toString());
if (iterator.hasNext()) {
b.append(", ");
}
}
return new ConfigurationReaderException("Missing required attribute(s): " + b, reader.getLocation());
}
/**
* Get an exception reporting a missing, required XML child element.
*
* @param reader the stream reader
* @param required a set of enums whose toString method returns the attribute name
* @return the exception
*/
public static ConfigurationReaderException missingRequiredElement(final ConfigurationReader reader, final Set<?> required) {
final StringBuilder b = new StringBuilder();
Iterator<?> iterator = required.iterator();
while (iterator.hasNext()) {
final Object o = iterator.next();
b.append(o.toString());
if (iterator.hasNext()) {
b.append(", ");
}
}
return new ConfigurationReaderException("Missing required element(s): " + b, reader.getLocation());
}
/**
* Checks that the current element has no attributes, throwing an {@link ConfigurationReaderException} if one is
* found.
*
* @param reader the reader
* @throws ConfigurationReaderException if an error occurs
*/
public static void requireNoAttributes(final ConfigurationReader reader) throws ConfigurationReaderException {
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
}
/**
* Consumes the remainder of the current element, throwing an {@link ConfigurationReaderException} if it contains
* any child elements.
*
* @param reader the reader
* @throws ConfigurationReaderException if an error occurs
*/
public static void requireNoContent(final ConfigurationReader reader) throws ConfigurationReaderException {
if (reader.hasNext() && reader.nextElement() != ConfigurationReader.ElementType.END_ELEMENT) {
throw unexpectedElement(reader);
}
}
/**
* Get an exception reporting that an attribute of a given name has already been declared in this scope.
*
* @param reader the stream reader
* @param name the name that was redeclared
* @return the exception
*/
public static ConfigurationReaderException duplicateAttribute(final ConfigurationReader reader, final String name) {
return new ConfigurationReaderException("An attribute named '" + name + "' has already been declared", reader.getLocation());
}
/**
* Get an exception reporting that an element of a given type and name has already been declared in this scope.
*
* @param reader the stream reader
* @param name the name that was redeclared
* @return the exception
*/
public static ConfigurationReaderException duplicateNamedElement(final ConfigurationReader reader, final String name) {
return new ConfigurationReaderException("An element of this type named '" + name + "' has already been declared",
reader.getLocation());
}
/**
* Read an element which contains only a single boolean attribute.
*
* @param reader the reader
* @param attributeName the attribute name, usually "value"
* @return the boolean value
* @throws ConfigurationReaderException if an error occurs or if the element does not contain the specified
* attribute, contains other attributes, or contains child elements.
*/
public static boolean readBooleanAttributeElement(final ConfigurationReader reader, final String attributeName)
throws ConfigurationReaderException {
requireSingleAttribute(reader, attributeName);
final boolean value = Boolean.parseBoolean(reader.getAttributeValue(0));
requireNoContent(reader);
return value;
}
/**
* Read an element which contains only a single string attribute.
*
* @param reader the reader
* @param attributeName the attribute name, usually "value" or "name"
* @return the string value
* @throws ConfigurationReaderException if an error occurs or if the element does not contain the specified
* attribute, contains other attributes, or contains child elements.
*/
public static String readStringAttributeElement(final ConfigurationReader reader, final String attributeName)
throws ConfigurationReaderException {
final String value = requireSingleAttribute(reader, attributeName);
requireNoContent(reader);
return value;
}
/**
* Require that the current element have only a single attribute with the given name.
*
* @param reader the reader
* @param attributeName the attribute name
* @throws ConfigurationReaderException if an error occurs
*/
public static String requireSingleAttribute(final ConfigurationReader reader, final String attributeName)
throws ConfigurationReaderException {
final int count = reader.getAttributeCount();
if (count == 0) {
throw missingRequired(reader, Collections.singleton(attributeName));
}
requireNoNamespaceAttribute(reader, 0);
if (!attributeName.equals(reader.getAttributeName(0))) {
throw unexpectedAttribute(reader, 0);
}
if (count > 1) {
throw unexpectedAttribute(reader, 1);
}
return reader.getAttributeValue(0);
}
public static String requireSingleAttribute(final ConfigurationReader reader, final Enum<?> attribute)
throws ConfigurationReaderException {
return requireSingleAttribute(reader, attribute.toString());
}
/**
* Require all the named attributes, returning their values in order.
*
* @param reader the reader
* @param attributeNames the attribute names
* @return the attribute values in order
* @throws ConfigurationReaderException if an error occurs
*/
public static String[] requireAttributes(final ConfigurationReader reader, boolean replace, final String... attributeNames)
throws ConfigurationReaderException {
final int length = attributeNames.length;
final String[] result = new String[length];
for (int i = 0; i < length; i++) {
final String name = attributeNames[i];
final String value = reader.getAttributeValue(name);
if (value == null) {
throw missingRequired(reader, Collections.singleton(name));
}
result[i] = replace ? replaceProperties(value) : value;
}
return result;
}
public static String[] requireAttributes(final ConfigurationReader reader, final String... attributeNames)
throws ConfigurationReaderException {
return requireAttributes(reader, false, attributeNames);
}
public static String[] requireAttributes(final ConfigurationReader reader, final Enum<?>... attributes)
throws ConfigurationReaderException {
String[] attributeNames = new String[attributes.length];
for (int i = 0; i < attributes.length; i++) {
attributeNames[i] = attributes[i].toString();
}
return requireAttributes(reader, true, attributeNames);
}
public static boolean isNoNamespaceAttribute(final ConfigurationReader reader, final int index) {
String namespace = reader.getAttributeNamespace(index);
return namespace == null || namespace.isEmpty();
}
public static void requireNoNamespaceAttribute(final ConfigurationReader reader, final int index)
throws ConfigurationReaderException {
if (!isNoNamespaceAttribute(reader, index)) {
throw unexpectedAttribute(reader, index);
}
}
public static Namespace[] getNamespaceAnnotations(Class<?> cls) {
Namespaces namespacesAnnotation = cls.getAnnotation(Namespaces.class);
if (namespacesAnnotation != null) {
return namespacesAnnotation.value();
}
Namespace namespaceAnnotation = cls.getAnnotation(Namespace.class);
if (namespaceAnnotation != null) {
return new Namespace[]{namespaceAnnotation};
}
return null;
}
public static String[] getListAttributeValue(String value) {
return value.split("\\s+");
}
public static String resolvePath(String path, String relativeTo) {
if (path == null) {
return null;
} else if (new File(path).isAbsolute()) {
return path;
} else if (relativeTo != null) {
return new File(new File(relativeTo), path).getAbsolutePath();
} else {
return path;
}
}
public static String requireAttributeProperty(final ConfigurationReader reader, int i) throws ConfigurationReaderException {
String property = reader.getAttributeValue(i);
Object value = reader.getProperty(property);
if (value == null) {
throw CONFIG.missingRequiredProperty(property, reader.getAttributeName(i), reader.getLocation());
} else {
return value.toString();
}
}
public static void ignoreAttribute(ConfigurationReader reader, String attributeName) {
CONFIG.ignoreAttribute(attributeName, reader.getLocation());
}
public static void ignoreAttribute(ConfigurationReader reader, int attributeIndex) {
ignoreAttribute(reader, reader.getAttributeName(attributeIndex));
}
public static void ignoreAttribute(ConfigurationReader reader, Enum<?> attribute) {
CONFIG.ignoreAttribute(attribute, reader.getLocation());
}
public static void ignoreElement(ConfigurationReader reader, Enum<?> element) {
CONFIG.ignoreXmlElement(element, reader.getLocation());
}
public static CacheConfigurationException elementRemoved(ConfigurationReader reader, String newElementName) {
return CONFIG.elementRemovedUseOther(reader.getLocalName(), newElementName, reader.getLocation());
}
public static CacheConfigurationException elementRemoved(ConfigurationReader reader) {
return CONFIG.elementRemoved(reader.getLocalName(), reader.getLocation());
}
public static CacheConfigurationException attributeRemoved(ConfigurationReader reader, int attributeIndex, String newAttributeName) {
String attributeName = reader.getAttributeName(attributeIndex);
return CONFIG.attributeRemovedUseOther(attributeName, newAttributeName, reader.getLocation());
}
public static CacheConfigurationException attributeRemoved(ConfigurationReader reader, int attributeIndex) {
String attributeName = reader.getAttributeName(attributeIndex);
return CONFIG.attributeRemoved(attributeName, reader.getLocation());
}
public static void parseAttributes(ConfigurationReader reader, Builder<?> builder) {
AttributeSet attributes = builder.attributes();
attributes.touch();
int major = reader.getSchema().getMajor();
int minor = reader.getSchema().getMinor();
for (int i = 0; i < reader.getAttributeCount(); i++) {
String name = reader.getAttributeName(i);
String value = reader.getAttributeValue(i);
org.infinispan.commons.configuration.attributes.Attribute<Object> attribute = attributes.attribute(name);
if (attribute == null) {
if (attributes.isRemoved(name, major, minor)) {
CONFIG.ignoreAttribute(name, reader.getLocation());
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
} else {
try {
attribute.fromString(value);
if (attribute.getAttributeDefinition().isDeprecated(major, minor)) {
CONFIG.attributeDeprecated(attribute.name(), attributes.getName(), major, minor);
}
} catch (IllegalArgumentException e) {
throw CONFIG.invalidAttributeValue(reader.getLocalName(), name, value, reader.getLocation(), e.getLocalizedMessage());
}
}
}
}
public static Integer parseInt(ConfigurationReader reader, int i, String value) {
try {
return Integer.parseInt(value);
} catch (IllegalArgumentException e) {
throw CONFIG.invalidAttributeValue(reader.getLocalName(), reader.getAttributeName(i), value, reader.getLocation(), e.getLocalizedMessage());
}
}
public static long parseLong(ConfigurationReader reader, int i, String value) {
try {
return Long.parseLong(value);
} catch (IllegalArgumentException e) {
throw CONFIG.invalidAttributeValue(reader.getLocalName(), reader.getAttributeName(i), value, reader.getLocation(), e.getLocalizedMessage());
}
}
public static <T extends Enum<T>> T parseEnum(ConfigurationReader reader, int i, Class<T> enumClass, String value) {
try {
return Enum.valueOf(enumClass, value);
} catch (IllegalArgumentException e) {
throw CONFIG.invalidAttributeEnumValue(reader.getLocalName(), reader.getAttributeName(i), value, EnumSet.allOf(enumClass).toString(), reader.getLocation());
}
}
public static boolean parseBoolean(ConfigurationReader reader, int i, String value) {
try {
return Util.parseBoolean(value);
} catch (IllegalArgumentException e) {
throw CONFIG.invalidAttributeValue(reader.getLocalName(), reader.getAttributeName(i), value, reader.getLocation(), e.getLocalizedMessage());
}
}
}
| 18,341
| 41.458333
| 168
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/ParsedCacheMode.java
|
package org.infinispan.configuration.parsing;
import static org.infinispan.util.logging.Log.CONFIG;
import java.util.ArrayList;
import java.util.List;
public enum ParsedCacheMode {
LOCAL("l", "local"),
REPL("r", "repl", "replication"),
DIST("d", "dist", "distribution"),
INVALIDATION("i", "invl", "invalidation");
private final List<String> synonyms;
ParsedCacheMode(String... synonyms) {
this.synonyms = new ArrayList<String>();
for (String synonym : synonyms) {
this.synonyms.add(synonym.toUpperCase());
}
}
public boolean matches(String candidate) {
String c = candidate.toUpperCase();
for (String synonym : synonyms) {
if (c.equals(synonym))
return true;
}
if (c.toUpperCase().startsWith(name().toUpperCase().substring(0, 1))) {
CONFIG.randomCacheModeSynonymsDeprecated(candidate, name(), synonyms);
return true;
}
return false;
}
}
| 977
| 22.853659
| 79
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/CacheParser.java
|
package org.infinispan.configuration.parsing;
import static org.infinispan.configuration.parsing.ParseUtils.ignoreAttribute;
import static org.infinispan.configuration.parsing.ParseUtils.ignoreElement;
import static org.infinispan.configuration.parsing.Parser.NAMESPACE;
import static org.infinispan.util.logging.Log.CONFIG;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import org.infinispan.commons.configuration.BuiltBy;
import org.infinispan.commons.configuration.ConfiguredBy;
import org.infinispan.commons.configuration.io.ConfigurationReader;
import org.infinispan.commons.configuration.io.NamingStrategy;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.util.GlobUtils;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.AbstractStoreConfigurationBuilder;
import org.infinispan.configuration.cache.AsyncStoreConfigurationBuilder;
import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder;
import org.infinispan.configuration.cache.BackupConfigurationBuilder;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.CacheType;
import org.infinispan.configuration.cache.ClusterLoaderConfigurationBuilder;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.ContentTypeConfigurationBuilder;
import org.infinispan.configuration.cache.CustomStoreConfigurationBuilder;
import org.infinispan.configuration.cache.EncodingConfigurationBuilder;
import org.infinispan.configuration.cache.GroupsConfigurationBuilder;
import org.infinispan.configuration.cache.IndexMergeConfigurationBuilder;
import org.infinispan.configuration.cache.IndexStartupMode;
import org.infinispan.configuration.cache.IndexStorage;
import org.infinispan.configuration.cache.IndexWriterConfigurationBuilder;
import org.infinispan.configuration.cache.IndexingConfigurationBuilder;
import org.infinispan.configuration.cache.IndexingMode;
import org.infinispan.configuration.cache.InterceptorConfiguration;
import org.infinispan.configuration.cache.InterceptorConfigurationBuilder;
import org.infinispan.configuration.cache.MemoryConfigurationBuilder;
import org.infinispan.configuration.cache.PartitionHandlingConfigurationBuilder;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.configuration.cache.SecurityConfigurationBuilder;
import org.infinispan.configuration.cache.SingleFileStoreConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.configuration.cache.StoreConfigurationBuilder;
import org.infinispan.configuration.cache.TransactionConfiguration;
import org.infinispan.conflict.EntryMergePolicy;
import org.infinispan.conflict.MergePolicy;
import org.infinispan.eviction.EvictionStrategy;
import org.infinispan.eviction.EvictionType;
import org.infinispan.expiration.TouchMode;
import org.infinispan.partitionhandling.PartitionHandling;
import org.infinispan.persistence.cluster.ClusterLoader;
import org.infinispan.persistence.file.SingleFileStore;
import org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfigurationBuilder;
import org.infinispan.transaction.LockingMode;
import org.kohsuke.MetaInfServices;
/**
* This class implements the parser for Infinispan/AS7/EAP/JDG schema files
*
* @author Tristan Tarrant
* @author Galder Zamarreño
* @since 12.0
*/
@MetaInfServices(ConfigurationParser.class)
@Namespace(root = "local-cache")
@Namespace(root = "local-cache-configuration")
@Namespace(root = "distributed-cache")
@Namespace(root = "distributed-cache-configuration")
@Namespace(root = "replicated-cache")
@Namespace(root = "replicated-cache-configuration")
@Namespace(uri = NAMESPACE + "*", root = "local-cache")
@Namespace(uri = NAMESPACE + "*", root = "local-cache-configuration")
@Namespace(uri = NAMESPACE + "*", root = "distributed-cache")
@Namespace(uri = NAMESPACE + "*", root = "distributed-cache-configuration")
@Namespace(uri = NAMESPACE + "*", root = "replicated-cache")
@Namespace(uri = NAMESPACE + "*", root = "replicated-cache-configuration")
public class CacheParser implements ConfigurationParser {
public static final String NAMESPACE = "urn:infinispan:config:";
public static final String IGNORE_DUPLICATES = "org.infinispan.parser.ignoreDuplicates";
public CacheParser() {
}
@Override
public void readElement(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
Element element = Element.forName(reader.getLocalName());
String name = reader.getAttributeValue(Attribute.NAME.getLocalName());
switch (element) {
case LOCAL_CACHE: {
parseLocalCache(reader, holder, name,false);
break;
}
case LOCAL_CACHE_CONFIGURATION: {
parseLocalCache(reader, holder, name, true);
break;
}
case INVALIDATION_CACHE: {
parseInvalidationCache(reader, holder, name,false);
break;
}
case INVALIDATION_CACHE_CONFIGURATION: {
parseInvalidationCache(reader, holder, name, true);
break;
}
case REPLICATED_CACHE: {
parseReplicatedCache(reader, holder, name, false);
break;
}
case REPLICATED_CACHE_CONFIGURATION: {
parseReplicatedCache(reader, holder, name, true);
break;
}
case DISTRIBUTED_CACHE: {
parseDistributedCache(reader, holder, name, false);
break;
}
case DISTRIBUTED_CACHE_CONFIGURATION: {
parseDistributedCache(reader, holder, name, true);
break;
}
default:
throw ParseUtils.unexpectedElement(reader);
}
}
private void parseModules(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
while (reader.inTag()) {
reader.handleAny(holder);
}
}
protected void parseLocalCache(ConfigurationReader reader, ConfigurationBuilderHolder holder, String name, boolean template) {
holder.pushScope(template ? ParserScope.CACHE_TEMPLATE : ParserScope.CACHE);
if (!template && GlobUtils.isGlob(name))
throw CONFIG.wildcardsNotAllowedInCacheNames(name);
String configuration = reader.getAttributeValue(Attribute.CONFIGURATION.getLocalName());
ConfigurationBuilder builder = getConfigurationBuilder(reader, holder, name, template, configuration);
builder.clustering().cacheMode(CacheMode.LOCAL);
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
this.parseCacheAttribute(reader, i, attribute, value, builder);
}
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
this.parseCacheElement(reader, element, holder);
}
holder.popScope();
}
private void parseCacheAttribute(ConfigurationReader reader,
int index, Attribute attribute, String value, ConfigurationBuilder builder) {
switch (attribute) {
case NAME:
case CONFIGURATION:
// Handled by the caller
break;
case START:
case JNDI_NAME:
case MODULE: {
ignoreAttribute(reader, index);
break;
}
case SIMPLE_CACHE:
builder.simpleCache(ParseUtils.parseBoolean(reader, index, value));
break;
case STATISTICS: {
builder.statistics().enabled(ParseUtils.parseBoolean(reader, index, value));
break;
}
case STATISTICS_AVAILABLE: {
builder.statistics().available(ParseUtils.parseBoolean(reader, index, value));
break;
}
case SPIN_DURATION: {
if (reader.getSchema().since(10, 0)) {
throw ParseUtils.attributeRemoved(reader, index);
} else {
ignoreAttribute(reader, index);
}
break;
}
case UNRELIABLE_RETURN_VALUES: {
builder.unsafe().unreliableReturnValues(ParseUtils.parseBoolean(reader, index, value));
break;
}
default: {
if (ParseUtils.isNoNamespaceAttribute(reader, index)) {
throw ParseUtils.unexpectedAttribute(reader, index);
}
}
}
}
private void parseSharedStateCacheElement(ConfigurationReader reader, Element element, ConfigurationBuilderHolder holder) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
switch (element) {
case STATE_TRANSFER: {
this.parseStateTransfer(reader, builder);
break;
}
default: {
this.parseCacheElement(reader, element, holder);
}
}
}
private void parseBackups(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
ParseUtils.parseAttributes(reader, builder.sites());
while (reader.inTag()) {
Map.Entry<String, String> item = reader.getMapItem(Attribute.SITE);
Element element = Element.forName(item.getValue());
if (element == Element.BACKUP) {
this.parseBackup(reader, builder, item.getKey());
} else {
throw ParseUtils.unexpectedElement(reader);
}
reader.endMapItem();
}
}
private void parsePartitionHandling(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
PartitionHandlingConfigurationBuilder ph = builder.clustering().partitionHandling();
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case ENABLED: {
if (reader.getSchema().since(11, 0))
throw ParseUtils.attributeRemoved(reader, i, Attribute.WHEN_SPLIT.getLocalName());
ignoreAttribute(reader, i);
break;
}
case WHEN_SPLIT: {
ph.whenSplit(ParseUtils.parseEnum(reader, i, PartitionHandling.class, value));
break;
}
case MERGE_POLICY: {
MergePolicy mp = MergePolicy.fromString(value);
EntryMergePolicy mergePolicy = mp == MergePolicy.CUSTOM ? Util.getInstance(value, holder.getClassLoader()) : mp;
ph.mergePolicy(mergePolicy);
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
ParseUtils.requireNoContent(reader);
}
private void parseBackup(ConfigurationReader reader, ConfigurationBuilder builder, String site) {
BackupConfigurationBuilder backup = builder.sites().addBackup().site(site);
ParseUtils.parseAttributes(reader, backup);
if (backup.site() == null) {
throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.SITE));
}
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case TAKE_OFFLINE: {
parseTakeOffline(reader, backup);
break;
}
case STATE_TRANSFER: {
parseXSiteStateTransfer(reader, backup);
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
private void parseTakeOffline(ConfigurationReader reader, BackupConfigurationBuilder backup) {
ParseUtils.parseAttributes(reader, backup.takeOffline());
ParseUtils.requireNoContent(reader);
}
private void parseXSiteStateTransfer(ConfigurationReader reader, BackupConfigurationBuilder backup) {
ParseUtils.parseAttributes(reader, backup.stateTransfer());
ParseUtils.requireNoContent(reader);
}
private void parseBackupFor(ConfigurationReader reader, ConfigurationBuilder builder) {
ParseUtils.parseAttributes(reader, builder.sites().backupFor());
ParseUtils.requireNoContent(reader);
}
private void parseCacheSecurity(ConfigurationReader reader, ConfigurationBuilder builder) {
SecurityConfigurationBuilder securityBuilder = builder.security();
ParseUtils.requireNoAttributes(reader);
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case AUTHORIZATION: {
parseCacheAuthorization(reader, securityBuilder.authorization().enable());
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
private void parseCacheAuthorization(ConfigurationReader reader, AuthorizationConfigurationBuilder authzBuilder) {
for (int i = 0; i < reader.getAttributeCount(); i++) {
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case ENABLED: {
authzBuilder.enabled(Boolean.parseBoolean(reader.getAttributeValue(i)));
break;
}
case ROLES: {
for(String role : reader.getListAttributeValue(i)) {
authzBuilder.role(role);
}
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
ParseUtils.requireNoContent(reader);
}
protected final void parseCacheElement(ConfigurationReader reader, Element element, ConfigurationBuilderHolder holder) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
switch (element) {
case LOCKING: {
this.parseLocking(reader, builder);
break;
}
case TRANSACTION: {
this.parseTransaction(reader, builder, holder);
break;
}
case EVICTION: {
if (reader.getSchema().since(10, 0)) {
throw ParseUtils.elementRemoved(reader, Element.MEMORY.getLocalName());
} else {
this.parseEviction(reader, builder);
}
break;
}
case EXPIRATION: {
this.parseExpiration(reader, builder);
break;
}
case ENCODING: {
this.parseDataType(reader, builder, holder);
break;
}
case PERSISTENCE: {
this.parsePersistence(reader, holder);
break;
}
case QUERY: {
this.parseQuery(reader, holder);
break;
}
case INDEXING: {
this.parseIndexing(reader, holder);
break;
}
case CUSTOM_INTERCEPTORS: {
CONFIG.customInterceptorsDeprecated();
this.parseCustomInterceptors(reader, holder);
break;
}
case VERSIONING: {
parseVersioning(reader, holder);
break;
}
case COMPATIBILITY: {
if (!reader.getSchema().since(10, 0)) {
parseCompatibility(reader, holder);
}
break;
}
case STORE_AS_BINARY: {
parseStoreAsBinary(reader, holder);
break;
}
case MODULES: {
if (reader.getSchema().since(9, 0)) {
throw ParseUtils.elementRemoved(reader);
} else {
parseModules(reader, holder);
}
break;
}
case DATA_CONTAINER: {
if (reader.getSchema().since(10, 0)) {
throw ParseUtils.elementRemoved(reader);
} else {
parseDataContainer(reader);
}
break;
}
case MEMORY: {
parseMemory(reader, holder);
break;
}
case BACKUPS: {
this.parseBackups(reader, holder);
break;
}
case BACKUP_FOR: {
this.parseBackupFor(reader, builder);
break;
}
case PARTITION_HANDLING: {
this.parsePartitionHandling(reader, holder);
break;
}
case SECURITY: {
this.parseCacheSecurity(reader, builder);
break;
}
default: {
reader.handleAny(holder);
}
}
}
private void parseDataContainer(final ConfigurationReader reader) {
ignoreElement(reader, Element.DATA_CONTAINER);
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case CLASS:
case KEY_EQUIVALENCE:
case VALUE_EQUIVALENCE:
ignoreAttribute(reader, i);
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
Properties properties = new Properties();
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case PROPERTY: {
ignoreElement(reader, element);
parseProperty(reader, properties);
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
private void parseMemory(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
MemoryConfigurationBuilder memoryBuilder = holder.getCurrentConfigurationBuilder().memory();
if (reader.getSchema().since(11, 0)) {
ParseUtils.parseAttributes(reader, memoryBuilder);
}
if (reader.getSchema().since(15, 0)) {
ParseUtils.requireNoContent(reader);
} else {
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
CONFIG.warnUsingDeprecatedMemoryConfigs(element.getLocalName());
switch (element) {
case OFF_HEAP:
memoryBuilder.storageType(StorageType.OFF_HEAP);
parseOffHeapMemoryAttributes(reader, holder);
break;
case OBJECT:
memoryBuilder.storageType(StorageType.OBJECT);
parseObjectMemoryAttributes(reader, holder);
break;
case BINARY:
memoryBuilder.storageType(StorageType.BINARY);
parseBinaryMemoryAttributes(reader, holder);
break;
default:
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
private void parseOffHeapMemoryAttributes(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
MemoryConfigurationBuilder memoryBuilder = holder.getCurrentConfigurationBuilder().memory();
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case SIZE:
memoryBuilder.size(ParseUtils.parseLong(reader, i, value));
break;
case EVICTION:
memoryBuilder.evictionType(ParseUtils.parseEnum(reader, i, EvictionType.class, value));
break;
case ADDRESS_COUNT:
if (reader.getSchema().since(10, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
ignoreAttribute(reader, i);
}
break;
case STRATEGY:
memoryBuilder.evictionStrategy(ParseUtils.parseEnum(reader, i, EvictionStrategy.class, value));
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
ParseUtils.requireNoContent(reader);
}
private void parseObjectMemoryAttributes(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
MemoryConfigurationBuilder memoryBuilder = holder.getCurrentConfigurationBuilder().memory();
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case SIZE:
memoryBuilder.size(ParseUtils.parseLong(reader, i, value));
break;
case STRATEGY:
memoryBuilder.evictionStrategy(ParseUtils.parseEnum(reader, i, EvictionStrategy.class, value));
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
ParseUtils.requireNoContent(reader);
}
private void parseBinaryMemoryAttributes(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
MemoryConfigurationBuilder memoryBuilder = holder.getCurrentConfigurationBuilder().memory();
ParseUtils.parseAttributes(reader, memoryBuilder.legacyBuilder());
ParseUtils.requireNoContent(reader);
}
private void parseStoreAsBinary(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
CONFIG.configDeprecatedUseOther(Element.STORE_AS_BINARY, Element.MEMORY, reader.getLocation());
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
Boolean binaryKeys = null;
Boolean binaryValues = null;
builder.memory().storageType(StorageType.BINARY);
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case STORE_KEYS_AS_BINARY:
binaryKeys = ParseUtils.parseBoolean(reader, i, value);
break;
case STORE_VALUES_AS_BINARY:
binaryValues = ParseUtils.parseBoolean(reader, i, value);
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
if (binaryKeys != null && !binaryKeys && binaryValues != null && !binaryValues)
builder.memory().storageType(StorageType.OBJECT); // explicitly disable
ParseUtils.requireNoContent(reader);
}
private void parseCompatibility(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
EncodingConfigurationBuilder encoding = builder.encoding();
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case ENABLED:
if (ParseUtils.parseBoolean(reader, i, value)) {
encoding.key().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
encoding.value().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
}
break;
case MARSHALLER:
CONFIG.marshallersNotSupported();
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
ParseUtils.requireNoContent(reader);
}
private void parseVersioning(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case VERSIONING_SCHEME:
if (reader.getSchema().since(10, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
CONFIG.ignoredAttribute("versioning", "9.0", attribute.getLocalName(), reader.getLocation().getLineNumber());
}
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
ParseUtils.requireNoContent(reader);
}
private void parseCustomInterceptors(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
ParseUtils.requireNoAttributes(reader);
while (reader.inTag()) {
Map.Entry<String, String> item = reader.getMapItem(Attribute.CLASS);
Element element = Element.forName(item.getValue());
switch (element) {
case INTERCEPTOR: {
parseInterceptor(reader, holder, item.getKey());
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
reader.endMapItem();
}
}
private void parseInterceptor(ConfigurationReader reader, ConfigurationBuilderHolder holder, String klass) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
InterceptorConfigurationBuilder interceptorBuilder = builder.customInterceptors().addInterceptor();
interceptorBuilder.interceptorClass(Util.loadClass(klass, holder.getClassLoader()));
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case AFTER:
interceptorBuilder.after(Util.loadClass(value, holder.getClassLoader()));
break;
case BEFORE:
interceptorBuilder.before(Util.loadClass(value, holder.getClassLoader()));
break;
case CLASS:
// Already seen
break;
case INDEX:
interceptorBuilder.index(ParseUtils.parseInt(reader, i, value));
break;
case POSITION:
interceptorBuilder.position(InterceptorConfiguration.Position.valueOf(value.toUpperCase()));
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
interceptorBuilder.withProperties(parseProperties(reader, Element.INTERCEPTOR));
}
private void parseLocking(ConfigurationReader reader, ConfigurationBuilder builder) {
ParseUtils.parseAttributes(reader, builder.locking());
ParseUtils.requireNoContent(reader);
}
private void parseTransaction(ConfigurationReader reader, ConfigurationBuilder builder, ConfigurationBuilderHolder holder) {
if (!reader.getSchema().since(9, 0)) {
CacheMode cacheMode = builder.clustering().cacheMode();
if (!cacheMode.isSynchronous()) {
CONFIG.unsupportedAsyncCacheMode(cacheMode, cacheMode.toSync());
builder.clustering().cacheMode(cacheMode.toSync());
}
}
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case STOP_TIMEOUT: {
builder.transaction().cacheStopTimeout(ParseUtils.parseLong(reader, i, value));
break;
}
case MODE: {
TransactionMode txMode = ParseUtils.parseEnum(reader, i, TransactionMode.class, value);
builder.transaction().transactionMode(txMode.getMode());
builder.transaction().useSynchronization(!txMode.isXAEnabled() && txMode.getMode().isTransactional());
builder.transaction().recovery().enabled(txMode.isRecoveryEnabled());
builder.invocationBatching().enable(txMode.isBatchingEnabled());
break;
}
case LOCKING: {
builder.transaction().lockingMode(ParseUtils.parseEnum(reader, i, LockingMode.class, value));
break;
}
case TRANSACTION_MANAGER_LOOKUP_CLASS: {
builder.transaction().transactionManagerLookup(Util.getInstance(value, holder.getClassLoader()));
break;
}
case REAPER_WAKE_UP_INTERVAL: {
builder.transaction().reaperWakeUpInterval(ParseUtils.parseLong(reader, i, value));
break;
}
case COMPLETED_TX_TIMEOUT: {
builder.transaction().completedTxTimeout(ParseUtils.parseLong(reader, i, value));
break;
}
case TRANSACTION_PROTOCOL: {
if (reader.getSchema().since(11, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
CONFIG.ignoredAttribute("transaction protocol", "11.0", attribute.getLocalName(), reader.getLocation().getLineNumber());
}
break;
}
case AUTO_COMMIT: {
builder.transaction().autoCommit(ParseUtils.parseBoolean(reader, i, value));
break;
}
case RECOVERY_INFO_CACHE_NAME: {
builder.transaction().recovery().recoveryInfoCacheName(value);
break;
}
case NOTIFICATIONS: {
builder.transaction().notifications(ParseUtils.parseBoolean(reader, i, value));
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
ParseUtils.requireNoContent(reader);
}
private final void parseDataType(ConfigurationReader reader, ConfigurationBuilder builder, ConfigurationBuilderHolder holder) {
EncodingConfigurationBuilder encodingBuilder = builder.encoding();
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
if (attribute == Attribute.MEDIA_TYPE && reader.getSchema().since(11, 0)) {
encodingBuilder.mediaType(value);
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case KEY_DATA_TYPE:
ContentTypeConfigurationBuilder keyBuilder = encodingBuilder.key();
parseContentType(reader, holder, keyBuilder);
ParseUtils.requireNoContent(reader);
break;
case VALUE_DATA_TYPE:
ContentTypeConfigurationBuilder valueBuilder = encodingBuilder.value();
parseContentType(reader, holder, valueBuilder);
ParseUtils.requireNoContent(reader);
break;
default:
throw ParseUtils.unexpectedElement(reader);
}
}
}
private void parseContentType(ConfigurationReader reader, ConfigurationBuilderHolder holder, ContentTypeConfigurationBuilder builder) {
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case MEDIA_TYPE:
builder.mediaType(value);
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
private void parseEviction(ConfigurationReader reader, ConfigurationBuilder builder) {
CONFIG.configDeprecatedUseOther(Element.EVICTION, Element.MEMORY, reader.getLocation());
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case STRATEGY:
case THREAD_POLICY:
case TYPE:
ignoreAttribute(reader, i);
break;
case MAX_ENTRIES:
case SIZE:
long size = ParseUtils.parseLong(reader, i, value);
if (size >= 0) {
builder.memory().size(size);
}
break;
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
ParseUtils.requireNoContent(reader);
}
private void parseExpiration(ConfigurationReader reader, ConfigurationBuilder builder) {
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case MAX_IDLE: {
builder.expiration().maxIdle(ParseUtils.parseLong(reader, i, value));
break;
}
case LIFESPAN: {
builder.expiration().lifespan(ParseUtils.parseLong(reader, i, value));
break;
}
case INTERVAL: {
builder.expiration().wakeUpInterval(ParseUtils.parseLong(reader, i, value));
break;
}
case TOUCH: {
if (reader.getSchema().since(12, 1)) {
builder.expiration().touch(ParseUtils.parseEnum(reader, i, TouchMode.class, value));
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
ParseUtils.requireNoContent(reader);
}
protected void parseInvalidationCache(ConfigurationReader reader, ConfigurationBuilderHolder holder, String name, boolean template) {
holder.pushScope(template ? ParserScope.CACHE_TEMPLATE : ParserScope.CACHE);
if (!template && GlobUtils.isGlob(name))
throw CONFIG.wildcardsNotAllowedInCacheNames(name);
String configuration = reader.getAttributeValue(Attribute.CONFIGURATION.getLocalName());
ConfigurationBuilder builder = getConfigurationBuilder(reader, holder, name, template, configuration);
builder.clustering().cacheType(CacheType.INVALIDATION);
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case KEY_PARTITIONER: {
builder.clustering().hash().keyPartitioner(Util.getInstance(value, holder.getClassLoader()));
break;
}
default: {
this.parseClusteredCacheAttribute(reader, i, attribute, value, builder, CacheType.INVALIDATION);
}
}
}
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
default: {
this.parseCacheElement(reader, element, holder);
}
}
}
holder.popScope();
}
private void parseSegmentedCacheAttribute(ConfigurationReader reader,
int index, Attribute attribute, String value, ConfigurationBuilder builder, ClassLoader classLoader, CacheType type)
{
switch (attribute) {
case SEGMENTS: {
builder.clustering().hash().numSegments(ParseUtils.parseInt(reader, index, value));
break;
}
case CONSISTENT_HASH_FACTORY: {
if (reader.getSchema().since(11, 0)) {
CONFIG.debug("Consistent hash customization has been deprecated and will be removed");
}
builder.clustering().hash().consistentHashFactory(Util.getInstance(value, classLoader));
break;
}
case KEY_PARTITIONER: {
if (reader.getSchema().since(8, 2)) {
builder.clustering().hash().keyPartitioner(Util.getInstance(value, classLoader));
} else {
throw ParseUtils.unexpectedAttribute(reader, index);
}
break;
}
default: {
this.parseClusteredCacheAttribute(reader, index, attribute, value, builder, type);
}
}
}
private void parseClusteredCacheAttribute(ConfigurationReader reader,
int index, Attribute attribute, String value, ConfigurationBuilder builder, CacheType type)
{
switch (attribute) {
case ASYNC_MARSHALLING: {
if (reader.getSchema().since(9, 0)) {
throw ParseUtils.attributeRemoved(reader, index);
} else {
CONFIG.ignoredReplicationQueueAttribute(attribute.getLocalName(), reader.getLocation().getLineNumber());
}
break;
}
case MODE: {
Mode mode = ParseUtils.parseEnum(reader, index, Mode.class, value);
builder.clustering().cacheSync(mode.isSynchronous());
break;
}
case QUEUE_SIZE:
case QUEUE_FLUSH_INTERVAL: {
if (reader.getSchema().since(11, 0)) {
throw ParseUtils.attributeRemoved(reader, index);
} else {
CONFIG.ignoredReplicationQueueAttribute(attribute.getLocalName(), reader.getLocation().getLineNumber());
}
break;
}
case REMOTE_TIMEOUT: {
builder.clustering().remoteTimeout(ParseUtils.parseLong(reader, index, value));
break;
}
default: {
this.parseCacheAttribute(reader, index, attribute, value, builder);
}
}
}
protected void parseReplicatedCache(ConfigurationReader reader, ConfigurationBuilderHolder holder, String name, boolean template) {
holder.pushScope(template ? ParserScope.CACHE_TEMPLATE : ParserScope.CACHE);
if (!template && GlobUtils.isGlob(name))
throw CONFIG.wildcardsNotAllowedInCacheNames(name);
String configuration = reader.getAttributeValue(Attribute.CONFIGURATION.getLocalName());
ConfigurationBuilder builder = getConfigurationBuilder(reader, holder, name, template, configuration);
builder.clustering().cacheType(CacheType.REPLICATION);
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
parseSegmentedCacheAttribute(reader, i, attribute, value, builder, holder.getClassLoader(), CacheType.REPLICATION);
}
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
default: {
this.parseSharedStateCacheElement(reader, element, holder);
}
}
}
holder.popScope();
}
private void parseStateTransfer(ConfigurationReader reader, ConfigurationBuilder builder) {
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case AWAIT_INITIAL_TRANSFER: {
builder.clustering().stateTransfer().awaitInitialTransfer(ParseUtils.parseBoolean(reader, i, value));
break;
}
case ENABLED: {
builder.clustering().stateTransfer().fetchInMemoryState(ParseUtils.parseBoolean(reader, i, value));
break;
}
case TIMEOUT: {
builder.clustering().stateTransfer().timeout(ParseUtils.parseLong(reader, i, value));
break;
}
case CHUNK_SIZE: {
builder.clustering().stateTransfer().chunkSize(ParseUtils.parseInt(reader, i, value));
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
ParseUtils.requireNoContent(reader);
}
protected void parseDistributedCache(ConfigurationReader reader, ConfigurationBuilderHolder holder, String name, boolean template) {
holder.pushScope(template ? ParserScope.CACHE_TEMPLATE : ParserScope.CACHE);
if (!template && GlobUtils.isGlob(name))
throw CONFIG.wildcardsNotAllowedInCacheNames(name);
String configuration = reader.getAttributeValue(Attribute.CONFIGURATION.getLocalName());
ConfigurationBuilder builder = getConfigurationBuilder(reader, holder, name, template, configuration);
builder.clustering().cacheType(CacheType.DISTRIBUTION);
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case OWNERS: {
builder.clustering().hash().numOwners(ParseUtils.parseInt(reader, i, value));
break;
}
case L1_LIFESPAN: {
long lifespan = ParseUtils.parseLong(reader, i, value);
if (lifespan > 0)
builder.clustering().l1().enable().lifespan(lifespan);
else
builder.clustering().l1().disable();
break;
}
case INVALIDATION_CLEANUP_TASK_FREQUENCY: {
builder.clustering().l1().cleanupTaskFrequency(ParseUtils.parseLong(reader, i, value));
break;
}
case CAPACITY:
if (reader.getSchema().since(13, 0)) {
throw CONFIG.attributeRemoved(Attribute.CAPACITY.getLocalName(), reader.getLocation());
}
CONFIG.configDeprecatedUseOther(Attribute.CAPACITY, Attribute.CAPACITY_FACTOR, reader.getLocation());
case CAPACITY_FACTOR: {
builder.clustering().hash().capacityFactor(Float.parseFloat(value));
break;
}
default: {
this.parseSegmentedCacheAttribute(reader, i, attribute, value, builder, holder.getClassLoader(), CacheType.DISTRIBUTION);
}
}
}
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case GROUPS: {
parseGroups(reader, holder);
break;
}
default: {
this.parseSharedStateCacheElement(reader, element, holder);
}
}
}
holder.popScope();
}
private void parseGroups(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
GroupsConfigurationBuilder groups = builder.clustering().hash().groups();
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case ENABLED:
if (ParseUtils.parseBoolean(reader, i, value)) {
groups.enabled();
} else {
groups.disabled();
}
break;
case GROUPER:
// JSON/YAML
for(String grouper : reader.getListAttributeValue(i)) {
groups.addGrouper(Util.getInstance(grouper, holder.getClassLoader()));
}
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case GROUPER:
if (reader.getAttributeCount() == 1) {
groups.addGrouper(Util.getInstance(ParseUtils.readStringAttributeElement(reader, "class"), holder.getClassLoader()));
} else {
groups.addGrouper(Util.getInstance(reader.getElementText(), holder.getClassLoader()));
reader.nextElement();
}
break;
default:
throw ParseUtils.unexpectedElement(reader);
}
}
}
private ConfigurationBuilder getConfigurationBuilder(ConfigurationReader reader, ConfigurationBuilderHolder holder, String name, boolean template, String baseConfigurationName) {
if (!reader.getProperties().containsKey(IGNORE_DUPLICATES) && holder.getNamedConfigurationBuilders().containsKey(name)) {
throw CONFIG.duplicateCacheName(name);
}
ConfigurationBuilder builder = holder.newConfigurationBuilder(name);
builder.configuration(baseConfigurationName).template(template);
return builder;
}
private void parsePersistence(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
ParseUtils.parseAttributes(reader, builder.persistence());
// clear in order to override any configuration defined in default cache
builder.persistence().clearStores();
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case CLUSTER_LOADER:
CONFIG.warnUsingDeprecatedClusterLoader();
parseClusterLoader(reader, holder);
break;
case FILE_STORE:
parseFileStore(reader, holder);
break;
case STORE:
parseCustomStore(reader, holder);
break;
case LOADER:
ignoreElement(reader, element);
break;
case SINGLE_FILE_STORE:
CONFIG.warnUsingDeprecatedClusterLoader();
parseSingleFileStore(reader, holder);
break;
default:
reader.handleAny(holder);
}
}
}
private void parseClusterLoader(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
ClusterLoaderConfigurationBuilder cclb = builder.persistence().addClusterLoader();
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
String attrName = reader.getAttributeName(i);
Attribute attribute = Attribute.forName(attrName);
switch (attribute) {
case REMOTE_TIMEOUT:
cclb.remoteCallTimeout(ParseUtils.parseLong(reader, i, value));
break;
default:
parseStoreAttribute(reader, i, cclb);
break;
}
}
parseStoreElements(reader, cclb);
}
protected void parseFileStore(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
SoftIndexFileStoreConfigurationBuilder fileStoreBuilder = null;
PersistenceConfigurationBuilder persistence = holder.getCurrentConfigurationBuilder().persistence();
AbstractStoreConfigurationBuilder<?, ?> actualStoreConfig;
int majorSchema = reader.getSchema().getMajor();
boolean legacyFileStore = false;
if (majorSchema < 13) {
parseSingleFileStore(reader, holder);
return;
} else if (majorSchema == 13) {
fileStoreBuilder = persistence.addStore(SFSToSIFSConfigurationBuilder.class);
actualStoreConfig = fileStoreBuilder;
legacyFileStore = true;
} else {
fileStoreBuilder = persistence.addSoftIndexFileStore();
actualStoreConfig = fileStoreBuilder;
}
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case RELATIVE_TO: {
if (reader.getSchema().since(11, 0))
throw ParseUtils.attributeRemoved(reader, i);
ignoreAttribute(reader, i);
break;
}
case PATH: {
fileStoreBuilder.dataLocation(value);
fileStoreBuilder.indexLocation(value);
break;
}
case FRAGMENTATION_FACTOR:
case MAX_ENTRIES: {
if (legacyFileStore) {
ignoreAttribute(reader, i);
} else {
throw ParseUtils.attributeRemoved(reader, i);
}
break;
}
case OPEN_FILES_LIMIT:
if (fileStoreBuilder != null) {
fileStoreBuilder.openFilesLimit(ParseUtils.parseInt(reader, i, value));
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
break;
case COMPACTION_THRESHOLD:
if (fileStoreBuilder != null) {
fileStoreBuilder.compactionThreshold(Double.parseDouble(value));
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
break;
case PURGE: {
actualStoreConfig.purgeOnStartup(ParseUtils.parseBoolean(reader, i, value));
break;
}
default: {
parseStoreAttribute(reader, i, actualStoreConfig);
}
}
}
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case DATA:
if (fileStoreBuilder != null) {
parseData(reader, fileStoreBuilder);
} else {
throw ParseUtils.unexpectedElement(reader);
}
break;
case INDEX:
if (fileStoreBuilder != null) {
parseIndex(reader, fileStoreBuilder);
} else {
throw ParseUtils.unexpectedElement(reader);
}
break;
default:
parseStoreElement(reader, actualStoreConfig);
}
}
}
private void parseData(ConfigurationReader reader, SoftIndexFileStoreConfigurationBuilder builder) {
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case PATH: {
builder.dataLocation(value);
break;
}
case RELATIVE_TO: {
if (reader.getSchema().since(13, 0))
throw ParseUtils.attributeRemoved(reader, i);
ignoreAttribute(reader, i);
break;
}
case MAX_FILE_SIZE:
builder.maxFileSize(ParseUtils.parseInt(reader, i, value));
break;
case SYNC_WRITES:
builder.syncWrites(ParseUtils.parseBoolean(reader, i, value));
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
ParseUtils.requireNoContent(reader);
}
private void parseIndex(ConfigurationReader reader, SoftIndexFileStoreConfigurationBuilder builder) {
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case PATH: {
builder.indexLocation(value);
break;
}
case RELATIVE_TO: {
if (reader.getSchema().since(13, 0))
throw ParseUtils.attributeRemoved(reader, i);
ignoreAttribute(reader, i);
break;
}
case SEGMENTS:
builder.indexSegments(ParseUtils.parseInt(reader, i, value));
break;
case INDEX_QUEUE_LENGTH:
builder.indexQueueLength(ParseUtils.parseInt(reader, i, value));
break;
case MIN_NODE_SIZE:
builder.minNodeSize(ParseUtils.parseInt(reader, i, value));
break;
case MAX_NODE_SIZE:
builder.maxNodeSize(ParseUtils.parseInt(reader, i, value));
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
ParseUtils.requireNoContent(reader);
}
protected void parseSingleFileStore(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
SingleFileStoreConfigurationBuilder storeBuilder = holder.getCurrentConfigurationBuilder().persistence().addSingleFileStore();
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case RELATIVE_TO: {
if (reader.getSchema().since(11, 0))
throw ParseUtils.attributeRemoved(reader, i);
ignoreAttribute(reader, i);
break;
}
case PATH: {
storeBuilder.location(value);
break;
}
case MAX_ENTRIES: {
storeBuilder.maxEntries(ParseUtils.parseInt(reader, i, value));
break;
}
case FRAGMENTATION_FACTOR: {
storeBuilder.fragmentationFactor(Float.parseFloat(value));
break;
}
default: {
parseStoreAttribute(reader, i, storeBuilder);
}
}
}
this.parseStoreElements(reader, storeBuilder);
}
/**
* This method is public static so that it can be reused by custom cache store/loader configuration parsers
*/
public static void parseStoreAttribute(ConfigurationReader reader, int index, AbstractStoreConfigurationBuilder<?, ?> storeBuilder) {
// Stores before 10.0 were non segmented by default
if (reader.getSchema().getMajor() < 10) {
storeBuilder.segmented(false);
}
String value = reader.getAttributeValue(index);
Attribute attribute = Attribute.forName(reader.getAttributeName(index));
switch (attribute) {
case SHARED: {
storeBuilder.shared(ParseUtils.parseBoolean(reader, index, value));
break;
}
case READ_ONLY: {
storeBuilder.ignoreModifications(ParseUtils.parseBoolean(reader, index, value));
break;
}
case PRELOAD: {
storeBuilder.preload(ParseUtils.parseBoolean(reader, index, value));
break;
}
case FETCH_STATE: {
if (reader.getSchema().since(14, 0)) {
throw ParseUtils.attributeRemoved(reader, index);
} else {
ignoreAttribute(reader, index);
}
break;
}
case PURGE: {
storeBuilder.purgeOnStartup(ParseUtils.parseBoolean(reader, index, value));
break;
}
case SINGLETON: {
if (reader.getSchema().since(10, 0)) {
throw ParseUtils.attributeRemoved(reader, index);
} else {
ignoreAttribute(reader, index);
}
break;
}
case TRANSACTIONAL: {
storeBuilder.transactional(ParseUtils.parseBoolean(reader, index, value));
break;
}
case MAX_BATCH_SIZE: {
storeBuilder.maxBatchSize(ParseUtils.parseInt(reader, index, value));
break;
}
case SEGMENTED: {
storeBuilder.segmented(ParseUtils.parseBoolean(reader, index, value));
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, index);
}
}
}
private void parseStoreElements(ConfigurationReader reader, StoreConfigurationBuilder<?, ?> storeBuilder) {
while (reader.inTag()) {
parseStoreElement(reader, storeBuilder);
}
}
public static void parseStoreElement(ConfigurationReader reader, StoreConfigurationBuilder<?, ?> storeBuilder) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case WRITE_BEHIND: {
parseStoreWriteBehind(reader, storeBuilder.async().enable());
break;
}
case PROPERTY: {
parseStoreProperty(reader, storeBuilder);
break;
}
case PROPERTIES: {
parseStoreProperties(reader, storeBuilder);
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
public static void parseStoreWriteBehind(ConfigurationReader reader, AsyncStoreConfigurationBuilder<?> storeBuilder) {
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case FLUSH_LOCK_TIMEOUT:
case SHUTDOWN_TIMEOUT: {
if (reader.getSchema().since(9, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
ignoreAttribute(reader, i);
}
break;
}
case MODIFICATION_QUEUE_SIZE: {
storeBuilder.modificationQueueSize(ParseUtils.parseInt(reader, i, value));
break;
}
case FAIL_SILENTLY:
storeBuilder.failSilently(ParseUtils.parseBoolean(reader, i, value));
break;
case THREAD_POOL_SIZE: {
if (reader.getSchema().since(11, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
ignoreAttribute(reader, i);
}
break;
}
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
ParseUtils.requireNoContent(reader);
}
public static void parseStoreProperty(ConfigurationReader reader, StoreConfigurationBuilder<?, ?> storeBuilder) {
String property = ParseUtils.requireSingleAttribute(reader, Attribute.NAME.getLocalName());
String value = reader.getElementText();
storeBuilder.addProperty(property, value);
}
public static void parseStoreProperties(ConfigurationReader reader, StoreConfigurationBuilder<?, ?> storeBuilder) {
for (int i = 0; i < reader.getAttributeCount(); i++) {
storeBuilder.addProperty(reader.getAttributeName(i, NamingStrategy.IDENTITY), reader.getAttributeValue(i));
}
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
if (element != Element.PROPERTY) {
throw ParseUtils.unexpectedElement(reader, element);
}
parseStoreProperty(reader, storeBuilder);
}
}
private void parseCustomStore(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
Boolean fetchPersistentState = null;
Boolean ignoreModifications = null;
Boolean purgeOnStartup = null;
Boolean preload = null;
Boolean shared = null;
Boolean transactional = null;
Boolean segmented = null;
Object store = null;
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case CLASS:
store = Util.getInstance(value, holder.getClassLoader());
break;
case FETCH_STATE:
fetchPersistentState = ParseUtils.parseBoolean(reader, i, value);
break;
case READ_ONLY:
ignoreModifications = ParseUtils.parseBoolean(reader, i, value);
break;
case PURGE:
purgeOnStartup = ParseUtils.parseBoolean(reader, i, value);
break;
case PRELOAD:
preload = ParseUtils.parseBoolean(reader, i, value);
break;
case SHARED:
shared = ParseUtils.parseBoolean(reader, i, value);
break;
case SINGLETON:
if (reader.getSchema().since(10, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
ignoreAttribute(reader, i);
}
break;
case TRANSACTIONAL:
transactional = ParseUtils.parseBoolean(reader, i, value);
break;
case SEGMENTED:
segmented = ParseUtils.parseBoolean(reader, i, value);
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
if (store != null) {
if (store instanceof SingleFileStore) {
SingleFileStoreConfigurationBuilder sfs = builder.persistence().addSingleFileStore();
if (fetchPersistentState != null)
sfs.fetchPersistentState(fetchPersistentState);
if (ignoreModifications != null)
sfs.ignoreModifications(ignoreModifications);
if (purgeOnStartup != null)
sfs.purgeOnStartup(purgeOnStartup);
if (preload != null)
sfs.preload(preload);
if (shared != null)
sfs.shared(shared);
if (transactional != null)
sfs.transactional(transactional);
if (segmented != null)
sfs.segmented(segmented);
parseStoreElements(reader, sfs);
} else if (store instanceof ClusterLoader) {
ClusterLoaderConfigurationBuilder cscb = builder.persistence().addClusterLoader();
parseStoreElements(reader, cscb);
} else {
ConfiguredBy annotation = store.getClass().getAnnotation(ConfiguredBy.class);
Class<? extends StoreConfigurationBuilder> builderClass = null;
if (annotation != null) {
Class<?> configuredBy = annotation.value();
if (configuredBy != null) {
BuiltBy builtBy = configuredBy.getAnnotation(BuiltBy.class);
builderClass = builtBy.value().asSubclass(StoreConfigurationBuilder.class);
}
}
StoreConfigurationBuilder configBuilder;
// If they don't specify a builder just use the custom configuration builder and set the class
if (builderClass == null) {
configBuilder = builder.persistence().addStore(CustomStoreConfigurationBuilder.class).customStoreClass(
store.getClass());
} else {
configBuilder = builder.persistence().addStore(builderClass);
}
if (fetchPersistentState != null)
configBuilder.fetchPersistentState(fetchPersistentState);
if (ignoreModifications != null)
configBuilder.ignoreModifications(ignoreModifications);
if (purgeOnStartup != null)
configBuilder.purgeOnStartup(purgeOnStartup);
if (preload != null)
configBuilder.preload(preload);
if (shared != null)
configBuilder.shared(shared);
if (transactional != null)
configBuilder.transactional(transactional);
if (segmented != null)
configBuilder.segmented(segmented);
parseStoreElements(reader, configBuilder);
}
}
}
private void parseQuery(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case DEFAULT_MAX_RESULTS:
builder.query().defaultMaxResults(ParseUtils.parseInt(reader, i, value));
break;
case HIT_COUNT_ACCURACY:
builder.query().hitCountAccuracy(ParseUtils.parseInt(reader, i, value));
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
// no nested properties at the moment
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
private void parseIndexing(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
boolean selfEnable = reader.getSchema().since(11, 0);
IndexingConfigurationBuilder indexing = builder.indexing();
indexing.attributes().touch(); // To handle inheritance corrrectly
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case ENABLED:
if (reader.getSchema().since(11, 0)) {
indexing.enabled(ParseUtils.parseBoolean(reader, i, value));
selfEnable = false;
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
break;
case STORAGE:
indexing.storage(IndexStorage.requireValid(value, CONFIG));
break;
case STARTUP_MODE:
indexing.startupMode(IndexStartupMode.requireValid(value, CONFIG));
break;
case PATH:
indexing.path(value);
break;
case INDEXING_MODE:
indexing.indexingMode(IndexingMode.requireValid(value));
break;
case INDEXED_ENTITIES:
indexing.addIndexedEntities(reader.getListAttributeValue(i));
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
if (selfEnable) {
// The presence of the <indexing> element without any explicit enabling or disabling results in auto-enabling indexing since 11.0
indexing.enable();
}
Properties indexingProperties = new Properties();
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case KEY_TRANSFORMERS: {
parseKeyTransformers(reader, holder, builder);
break;
}
case INDEXED_ENTITIES: {
parseIndexedEntities(reader, holder, builder);
break;
}
case PROPERTY: {
if (reader.getSchema().since(12, 0)) {
CONFIG.deprecatedIndexProperties();
}
parseProperty(reader, indexingProperties);
break;
}
case INDEX_READER: {
parseIndexReader(reader, builder);
break;
}
case INDEX_WRITER: {
parseIndexWriter(reader, builder);
break;
}
case INDEX_SHARDING: {
parseIndexSharding(reader, builder);
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
private void parseKeyTransformers(ConfigurationReader reader, ConfigurationBuilderHolder holder, ConfigurationBuilder builder) {
ParseUtils.requireNoAttributes(reader);
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case KEY_TRANSFORMER: {
parseKeyTransformer(reader, holder, builder);
break;
}
default:
throw ParseUtils.unexpectedElement(reader);
}
}
}
private void parseKeyTransformer(ConfigurationReader reader, ConfigurationBuilderHolder holder, ConfigurationBuilder builder) {
String[] attrs = ParseUtils.requireAttributes(reader, Attribute.KEY.getLocalName(), Attribute.TRANSFORMER.getLocalName());
Class<?> keyClass = Util.loadClass(attrs[0], holder.getClassLoader());
Class<?> transformerClass = Util.loadClass(attrs[1], holder.getClassLoader());
builder.indexing().addKeyTransformer(keyClass, transformerClass);
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case KEY:
case TRANSFORMER:
// Already handled
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
ParseUtils.requireNoContent(reader);
}
private void parseIndexReader(ConfigurationReader reader, ConfigurationBuilder builder) {
ParseUtils.parseAttributes(reader, builder.indexing().reader());
ParseUtils.requireNoContent(reader);
}
private void parseIndexWriter(ConfigurationReader reader, ConfigurationBuilder builder) {
IndexWriterConfigurationBuilder indexWriterBuilder = builder.indexing().writer();
ParseUtils.parseAttributes(reader, indexWriterBuilder);
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
if (element == Element.INDEX_MERGE) {
parseIndexWriterMerge(reader, builder);
} else {
throw ParseUtils.unexpectedElement(reader);
}
}
}
private void parseIndexSharding(ConfigurationReader reader, ConfigurationBuilder builder) {
ParseUtils.parseAttributes(reader, builder.indexing().sharding());
ParseUtils.requireNoContent(reader);
}
private void parseIndexWriterMerge(ConfigurationReader reader, ConfigurationBuilder builder) {
IndexMergeConfigurationBuilder mergeBuilder = builder.indexing().writer().merge();
ParseUtils.parseAttributes(reader, mergeBuilder);
ParseUtils.requireNoContent(reader);
}
private void parseIndexedEntities(ConfigurationReader reader, ConfigurationBuilderHolder holder, ConfigurationBuilder builder) {
ParseUtils.requireNoAttributes(reader);
String[] entities = reader.readArray(Element.INDEXED_ENTITIES, Element.INDEXED_ENTITY);
builder.indexing().addIndexedEntities(entities);
}
private static void parseProperty(ConfigurationReader reader, Properties properties) {
int attributes = reader.getAttributeCount();
ParseUtils.requireAttributes(reader, Attribute.NAME.getLocalName());
String key = null;
String propertyValue = null;
for (int i = 0; i < attributes; i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case NAME: {
key = value;
break;
}
case VALUE: {
propertyValue = value;
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
if (propertyValue == null) {
propertyValue = reader.getElementText();
}
properties.setProperty(key, propertyValue);
}
public static Properties parseProperties(final ConfigurationReader reader, Enum<?> outerElement) {
return parseProperties(reader, outerElement.toString(), Element.PROPERTIES.toString(), Element.PROPERTY.toString());
}
public static Properties parseProperties(final ConfigurationReader reader, Enum<?> outerElement, Enum<?> collectionElement, Enum<?> itemElement) {
return parseProperties(reader, outerElement.toString(), collectionElement.toString(), itemElement.toString());
}
public static Properties parseProperties(final ConfigurationReader reader, String outerElement, String collectionElement, String itemElement) {
Properties properties = new Properties();
while (reader.hasNext()) {
ConfigurationReader.ElementType type = reader.nextElement();
String element = reader.getLocalName();
if (element.equals(collectionElement)) {
// JSON/YAML map properties to attributes
for (int i = 0; i < reader.getAttributeCount(); i++) {
properties.setProperty(reader.getAttributeName(i), reader.getAttributeValue(i));
}
} else if (element.equals(itemElement)) {
if (type == ConfigurationReader.ElementType.START_ELEMENT) {
parseProperty(reader, properties);
}
} else if (type == ConfigurationReader.ElementType.END_ELEMENT && reader.getLocalName().equals(outerElement)) {
return properties;
} else {
throw ParseUtils.unexpectedElement(reader);
}
}
return properties;
}
public enum TransactionMode {
NONE(org.infinispan.transaction.TransactionMode.NON_TRANSACTIONAL, false, false, false),
BATCH(org.infinispan.transaction.TransactionMode.TRANSACTIONAL, false, false, true),
NON_XA(org.infinispan.transaction.TransactionMode.TRANSACTIONAL, false, false, false),
NON_DURABLE_XA(org.infinispan.transaction.TransactionMode.TRANSACTIONAL, true, false, false),
FULL_XA(org.infinispan.transaction.TransactionMode.TRANSACTIONAL, true, true, false),
;
private final org.infinispan.transaction.TransactionMode mode;
private final boolean xaEnabled;
private final boolean recoveryEnabled;
private final boolean batchingEnabled;
TransactionMode(org.infinispan.transaction.TransactionMode mode, boolean xaEnabled, boolean recoveryEnabled, boolean batchingEnabled) {
this.mode = mode;
this.xaEnabled = xaEnabled;
this.recoveryEnabled = recoveryEnabled;
this.batchingEnabled = batchingEnabled;
}
public static TransactionMode fromConfiguration(TransactionConfiguration transactionConfiguration, boolean batchingEnabled) {
org.infinispan.transaction.TransactionMode mode = transactionConfiguration.transactionMode();
boolean recoveryEnabled = transactionConfiguration.recovery().enabled();
boolean xaEnabled = !batchingEnabled && !transactionConfiguration.useSynchronization();
if (mode == org.infinispan.transaction.TransactionMode.NON_TRANSACTIONAL) {
return NONE;
}
for(TransactionMode txMode : TransactionMode.values()) {
if (txMode.mode == mode && txMode.xaEnabled == xaEnabled && txMode.recoveryEnabled == recoveryEnabled && txMode.batchingEnabled == batchingEnabled)
return txMode;
}
throw CONFIG.unknownTransactionConfiguration(mode, xaEnabled, recoveryEnabled, batchingEnabled);
}
public org.infinispan.transaction.TransactionMode getMode() {
return this.mode;
}
public boolean isXAEnabled() {
return this.xaEnabled;
}
public boolean isRecoveryEnabled() {
return this.recoveryEnabled;
}
public boolean isBatchingEnabled() {
return batchingEnabled;
}
}
public enum Mode {
SYNC(true),
ASYNC(false),
;
private final boolean sync;
Mode(boolean sync) {
this.sync = sync;
}
public boolean isSynchronous() {
return this.sync;
}
}
@Override
public Namespace[] getNamespaces() {
return ParseUtils.getNamespaceAnnotations(getClass());
}
}
| 78,068
| 39.682126
| 181
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/SFSToSIFSStore.java
|
package org.infinispan.configuration.parsing;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import org.infinispan.commons.configuration.ConfiguredBy;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.util.IntSet;
import org.infinispan.commons.util.IntSets;
import org.infinispan.configuration.cache.AbstractStoreConfiguration;
import org.infinispan.configuration.cache.AsyncStoreConfiguration;
import org.infinispan.configuration.cache.SingleFileStoreConfiguration;
import org.infinispan.configuration.cache.StoreConfiguration;
import org.infinispan.persistence.internal.PersistenceUtil;
import org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration;
import org.infinispan.persistence.spi.InitializationContext;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.persistence.spi.NonBlockingStore;
import org.infinispan.persistence.support.DelegatingInitializationContext;
import org.infinispan.persistence.support.DelegatingNonBlockingStore;
import org.infinispan.persistence.support.SegmentPublisherWrapper;
import org.infinispan.util.concurrent.CompletionStages;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.flowables.GroupedFlowable;
/**
* Store that is used to migrate data from ISPN 12.0 SingleFileStore to an ISPN 13.0 SoftIndexFileStore.
* This store works identically to a SoftIndexFileStore except that it will first attempt to copy all the entries
* from a SingleFileStore with the same location as the configured {@link SoftIndexFileStoreConfiguration#dataLocation()}.
* Note that both a segmented and non segmented SingleFileStore is attempted since it could have been either and
* SoftIndexFileStore only supports segmentation now.
* @param <K> key type
* @param <V> value type
*/
@ConfiguredBy(SFSToSIFSConfiguration.class)
public class SFSToSIFSStore<K, V> extends DelegatingNonBlockingStore<K, V> {
private NonBlockingStore<K, V> targetStore;
@Override
public NonBlockingStore<K, V> delegate() {
return targetStore;
}
@Override
public CompletionStage<Void> start(InitializationContext ctx) {
SFSToSIFSConfiguration sfsToSIFSConfiguration = ctx.getConfiguration();
CompletionStage<NonBlockingStore<K, V>> targetStage = createAndStartSoftIndexFileStore(ctx, sfsToSIFSConfiguration);
// If config has purge don't even bother with migration
if (sfsToSIFSConfiguration.purgeOnStartup()) {
return targetStage.thenAccept(sifsStore -> targetStore = sifsStore);
}
CompletionStage<NonBlockingStore<K, V>> nonSegmentedSFSStage = createAndStartSingleFileStore(ctx, sfsToSIFSConfiguration.dataLocation(), false);
CompletionStage<NonBlockingStore<K, V>> segmentedSFSStage = createAndStartSingleFileStore(ctx, sfsToSIFSConfiguration.dataLocation(), true);
Function<NonBlockingStore<K, V>, CompletionStage<Void>> composed = sourceStore -> targetStage.thenCompose(targetStore -> {
this.targetStore = targetStore;
int segmentCount = ctx.getCache().getCacheConfiguration().clustering().hash().numSegments();
IntSet allSegments = IntSets.immutableRangeSet(segmentCount);
Flowable<GroupedFlowable<Integer, MarshallableEntry<K, V>>> groupedFlowable =
Flowable.fromPublisher(sourceStore.publishEntries(allSegments, null, true))
.groupBy(ctx.getKeyPartitioner()::getSegment);
return targetStore.batch(segmentCount, Flowable.empty(), groupedFlowable.map(SegmentPublisherWrapper::wrap))
.thenCompose(ignore -> sourceStore.destroy());
});
return CompletionStages.allOf(nonSegmentedSFSStage.thenCompose(composed),
segmentedSFSStage.thenCompose(composed));
}
CompletionStage<NonBlockingStore<K, V>> createAndStartSingleFileStore(InitializationContext ctx, String location,
boolean segmented) {
AttributeSet sfsAttributes = SingleFileStoreConfiguration.attributeDefinitionSet();
sfsAttributes.attribute(SingleFileStoreConfiguration.LOCATION).set(location);
sfsAttributes.attribute(AbstractStoreConfiguration.SEGMENTED).set(segmented);
sfsAttributes.attribute(AbstractStoreConfiguration.READ_ONLY).set(Boolean.TRUE);
return createAndStartStore(ctx, new SingleFileStoreConfiguration(sfsAttributes.protect(),
new AsyncStoreConfiguration(AsyncStoreConfiguration.attributeDefinitionSet().protect())));
}
CompletionStage<NonBlockingStore<K, V>> createAndStartSoftIndexFileStore(InitializationContext ctx,
SFSToSIFSConfiguration config) {
return createAndStartStore(ctx, new SoftIndexFileStoreConfiguration(config.attributes(),
config.async(), config.index(), config.data()));
}
private CompletionStage<NonBlockingStore<K, V>> createAndStartStore(InitializationContext ctx, StoreConfiguration storeConfiguration) {
NonBlockingStore<K, V> store = PersistenceUtil.storeFromConfiguration(storeConfiguration);
return store.start(new DelegatingInitializationContext() {
@Override
public InitializationContext delegate() {
return ctx;
}
@SuppressWarnings("unchecked")
@Override
public <T extends StoreConfiguration> T getConfiguration() {
return (T) storeConfiguration;
}
}).thenApply(ignore -> store);
}
}
| 5,473
| 48.763636
| 150
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/ParserRegistry.java
|
package org.infinispan.configuration.parsing;
import static org.infinispan.util.logging.Log.CONFIG;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.configuration.io.ConfigurationReader;
import org.infinispan.commons.configuration.io.ConfigurationReaderException;
import org.infinispan.commons.configuration.io.ConfigurationResourceResolver;
import org.infinispan.commons.configuration.io.ConfigurationResourceResolvers;
import org.infinispan.commons.configuration.io.ConfigurationSchemaVersion;
import org.infinispan.commons.configuration.io.ConfigurationWriter;
import org.infinispan.commons.configuration.io.ConfigurationWriterException;
import org.infinispan.commons.configuration.io.NamingStrategy;
import org.infinispan.commons.configuration.io.URLConfigurationResourceResolver;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.util.FileLookup;
import org.infinispan.commons.util.FileLookupFactory;
import org.infinispan.commons.util.ServiceFinder;
import org.infinispan.commons.util.Util;
import org.infinispan.commons.util.Version;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.serializing.ConfigurationHolder;
import org.infinispan.configuration.serializing.ConfigurationSerializer;
import org.infinispan.configuration.serializing.CoreConfigurationSerializer;
/**
* ParserRegistry is a namespace-mapping-aware meta-parser which provides a way to delegate the
* parsing of multi-namespace XML files to appropriate parsers, defined by the
* {@link ConfigurationParser} interface. A registry of available parsers is built using the
* {@link ServiceLoader} system. Implementations of {@link ConfigurationParser} should include a
* META-INF/services/org.infinispan.configuration.parsing.ConfigurationParser file containing a list
* of available parsers.
*
* @author Tristan Tarrant
* @since 5.2
*/
public class ParserRegistry implements NamespaceMappingParser {
private final ClassLoader cl;
private final ConcurrentMap<QName, NamespaceParserPair> parserMappings;
private final Properties properties;
public ParserRegistry() {
this(Thread.currentThread().getContextClassLoader());
}
public ParserRegistry(ClassLoader classLoader) {
this(classLoader, false, System.getProperties());
}
public ParserRegistry(ClassLoader classLoader, boolean defaultOnly, Properties properties) {
this.parserMappings = new ConcurrentHashMap<>();
this.cl = classLoader;
this.properties = properties;
Collection<ConfigurationParser> parsers = ServiceFinder.load(ConfigurationParser.class, cl, ParserRegistry.class.getClassLoader());
for (ConfigurationParser parser : parsers) {
Namespace[] namespaces = parser.getNamespaces();
if (namespaces == null) {
throw CONFIG.parserDoesNotDeclareNamespaces(parser.getClass().getName());
}
boolean skipParser = defaultOnly;
if (skipParser) {
for (Namespace ns : namespaces) {
if ("".equals(ns.uri())) {
skipParser = false;
break;
}
}
}
if (!skipParser) {
for (Namespace ns : namespaces) {
QName qName = new QName(ns.uri(), ns.root());
NamespaceParserPair existing = parserMappings.putIfAbsent(qName, new NamespaceParserPair(ns, parser));
if (existing != null && !parser.getClass().equals(existing.parser.getClass())) {
CONFIG.parserRootElementAlreadyRegistered(qName.toString(), parser.getClass().getName(), existing.parser.getClass().getName());
}
}
}
}
}
public ConfigurationBuilderHolder parse(Path path) throws IOException {
return parse(path.toUri().toURL());
}
public ConfigurationBuilderHolder parse(URL url) throws IOException {
try (InputStream is = url.openStream()) {
return parse(is, new URLConfigurationResourceResolver(url), MediaType.fromExtension(url.getFile()));
}
}
public ConfigurationBuilderHolder parseFile(String filename) throws IOException {
FileLookup fileLookup = FileLookupFactory.newInstance();
URL url = fileLookup.lookupFileLocation(filename, cl);
if (url == null) {
throw new FileNotFoundException(filename);
}
try (InputStream is = url.openStream()) {
return parse(is, new URLConfigurationResourceResolver(url), MediaType.fromExtension(url.getFile()));
}
}
public ConfigurationBuilderHolder parseFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
try {
URL url = file.toURI().toURL();
return parse(is, new URLConfigurationResourceResolver(url), MediaType.fromExtension(url.getFile()));
} finally {
Util.close(is);
}
}
public ConfigurationBuilderHolder parse(String s) {
return parse(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)), ConfigurationResourceResolvers.DEFAULT, MediaType.APPLICATION_XML);
}
public ConfigurationBuilderHolder parse(String s, MediaType mediaType) {
return parse(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)), ConfigurationResourceResolvers.DEFAULT, mediaType);
}
/**
* Parses the supplied {@link InputStream} returning a new {@link ConfigurationBuilderHolder}
* @param is an {@link InputStream} pointing to a configuration file
* @param resourceResolver an optional resolver for Xinclude
* @return a new {@link ConfigurationBuilderHolder} which contains the parsed configuration
*/
public ConfigurationBuilderHolder parse(InputStream is, ConfigurationResourceResolver resourceResolver, MediaType mediaType) {
try {
ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(cl);
parse(is, holder, resourceResolver, mediaType);
return holder.validate();
} catch (CacheConfigurationException e) {
throw e;
} catch (Exception e) {
throw new CacheConfigurationException(e);
}
}
public ConfigurationBuilderHolder parse(URL url, ConfigurationBuilderHolder holder) throws IOException {
try(InputStream is = url.openStream()) {
return parse(is, holder, new URLConfigurationResourceResolver(url), MediaType.fromExtension(url.getFile()));
}
}
public ConfigurationBuilderHolder parse(InputStream is, ConfigurationBuilderHolder holder, ConfigurationResourceResolver resourceResolver, MediaType mediaType) {
ConfigurationReader reader = ConfigurationReader.from(is).withResolver(resourceResolver).withType(mediaType).withProperties(properties).withNamingStrategy(NamingStrategy.KEBAB_CASE).build();
parse(reader, holder);
// Resolve configuration templates
holder.resolveConfigurations();
// Fire all parsingComplete events if any
holder.fireParserListeners();
return holder;
}
public ConfigurationBuilderHolder parse(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
try (reader) {
holder.setNamespaceMappingParser(this);
reader.require(ConfigurationReader.ElementType.START_DOCUMENT);
ConfigurationReader.ElementType elementType = reader.nextElement();
if (elementType == ConfigurationReader.ElementType.START_ELEMENT) {
parseElement(reader, holder);
}
while (elementType != ConfigurationReader.ElementType.END_DOCUMENT) {
// consume remaining parsing events
elementType = reader.nextElement();
}
return holder;
}
}
@Override
public void parseElement(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
String namespace = reader.getNamespace();
String name = reader.getLocalName();
NamespaceParserPair parser = findNamespaceParser(reader, namespace, name);
ConfigurationSchemaVersion oldSchema = reader.getSchema();
reader.setSchema(Schema.fromNamespaceURI(namespace));
parser.parser.readElement(reader, holder);
reader.setSchema(oldSchema);
}
private NamespaceParserPair parseCacheName(ConfigurationReader reader, String name, String namespace) {
if (reader.hasNext()) {
reader.nextElement();
}
// If there's an invalid cache type element, then it's not a cache name and an invalid cache definition
if (!Element.isCacheElement(reader.getLocalName()))
throw CONFIG.unsupportedConfiguration(name, namespace, reader.getLocation(), Version.getVersion());
reader.setAttributeValue("", "name", name);
return findNamespaceParser(reader, reader.getNamespace(), reader.getLocalName());
}
@Override
public void parseAttribute(ConfigurationReader reader, int i, ConfigurationBuilderHolder holder) throws ConfigurationReaderException {
String namespace = reader.getAttributeNamespace(i);
String name = reader.getLocalName();
NamespaceParserPair parser = findNamespaceParser(reader, namespace, name);
ConfigurationSchemaVersion oldSchema = reader.getSchema();
reader.setSchema(Schema.fromNamespaceURI(namespace));
parser.parser.readAttribute(reader, name, i, holder);
reader.setSchema(oldSchema);
}
private NamespaceParserPair findNamespaceParser(ConfigurationReader reader, String namespace, String name) {
NamespaceParserPair parser = parserMappings.get(new QName(namespace, name));
if (parser == null) {
// Next we strip off the version from the URI and look for a wildcard match
int lastColon = namespace.lastIndexOf(':');
String baseUri = namespace.substring(0, lastColon + 1) + "*";
parser = parserMappings.get(new QName(baseUri, name));
// See if we can get a default parser instead
if (parser == null || !isSupportedNamespaceVersion(parser.namespace, namespace.substring(lastColon + 1)))
// Parse a possible cache name because the cache name has not a namespace definition in YAML/JSON
return parseCacheName(reader, name, namespace);
}
return parser;
}
private boolean isSupportedNamespaceVersion(Namespace namespace, String version) {
short reqVersion = Version.getVersionShort(version);
if (reqVersion < Version.getVersionShort(namespace.since())) {
return false;
}
short untilVersion = !namespace.until().isEmpty() ? Version.getVersionShort(namespace.until()) : Version.getVersionShort();
return reqVersion <= untilVersion;
}
/**
* Serializes a full configuration to an {@link OutputStream}
*
* @param os the output stream where the configuration should be serialized to
* @param globalConfiguration the global configuration. Can be null
* @param configurations a map of named configurations
* @deprecated use {@link #serialize(ConfigurationWriter, GlobalConfiguration, Map)} instead
*/
@Deprecated
public void serialize(OutputStream os, GlobalConfiguration globalConfiguration, Map<String, Configuration> configurations) {
ConfigurationWriter writer = ConfigurationWriter.to(os).build();
serialize(writer, globalConfiguration, configurations);
try {
writer.close();
} catch (Exception e) {
throw new ConfigurationWriterException(e);
}
}
/**
* Serializes a full configuration to an {@link ConfigurationWriter}
*
* @param writer the writer where the configuration should be serialized to
* @param globalConfiguration the global configuration. Can be null
* @param configurations a map of named configurations
*/
public void serialize(ConfigurationWriter writer, GlobalConfiguration globalConfiguration, Map<String, Configuration> configurations) {
serializeWith(writer, new CoreConfigurationSerializer(), new ConfigurationHolder(globalConfiguration, configurations));
}
public <T> void serializeWith(ConfigurationWriter writer, ConfigurationSerializer<T> serializer, T t) {
writer.writeStartDocument();
serializer.serialize(writer, t);
writer.writeEndDocument();
}
/**
* Serializes a single configuration to an OutputStream
* @param os
* @param name
* @param configuration
* @deprecated use {@link #serialize(ConfigurationWriter, GlobalConfiguration, Map)} instead
*/
@Deprecated
public void serialize(OutputStream os, String name, Configuration configuration) {
serialize(os, null, Collections.singletonMap(name, configuration));
}
/**
* Serializes a single configuration to a String
* @param name the name of the configuration
* @param configuration the {@link Configuration}
* @return the XML representation of the specified configuration
* @deprecated use {@link #serialize(ConfigurationWriter, GlobalConfiguration, Map)} instead
*/
@Deprecated
public String serialize(String name, Configuration configuration) {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
serialize(os, name, configuration);
return os.toString(StandardCharsets.UTF_8);
} catch (Exception e) {
throw new CacheConfigurationException(e);
}
}
@Override
public String toString() {
return "ParserRegistry{}";
}
/**
* Serializes a single cache configuration
* @param writer
* @param name
* @param configuration
*/
public void serialize(ConfigurationWriter writer, String name, Configuration configuration) {
writer.writeStartDocument();
CoreConfigurationSerializer serializer = new CoreConfigurationSerializer();
serializer.writeCache(writer, name, configuration);
writer.writeEndDocument();
}
public static class NamespaceParserPair {
Namespace namespace;
ConfigurationParser parser;
NamespaceParserPair(Namespace namespace, ConfigurationParser parser) {
this.namespace = namespace;
this.parser = parser;
}
@Override
public String toString() {
return "NamespaceParserPair{" +
"namespace=" + namespace +
", parser=" + parser +
'}';
}
}
public static class QName {
final String namespace;
final String name;
public QName(String namespace, String name) {
this.namespace = namespace;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
QName qName = (QName) o;
return Objects.equals(namespace, qName.namespace) && Objects.equals(name, qName.name);
}
@Override
public int hashCode() {
return Objects.hash(namespace, name);
}
@Override
public String toString() {
return this.namespace.equals("") ? this.name : "{" + this.namespace + "}" + this.name;
}
}
}
| 15,805
| 40.26893
| 196
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/ConfigurationParser.java
|
package org.infinispan.configuration.parsing;
import org.infinispan.commons.configuration.io.ConfigurationReader;
/**
*
* ConfigurationParser.
*
* @author Tristan Tarrant
* @since 5.2
*/
public interface ConfigurationParser {
/**
* The entry point of a configuration parser which gets passed a {@link ConfigurationReader} positioned at a root
* element associated with the parser itself according to the registered mapping.
*
* @param reader the configuration stream reader
* @param holder a holder object used by the parser to maintain state
*/
void readElement(ConfigurationReader reader, ConfigurationBuilderHolder holder);
Namespace[] getNamespaces();
default void readAttribute(ConfigurationReader reader, String elementName, int attributeIndex, ConfigurationBuilderHolder holder) {
throw new UnsupportedOperationException("This parser cannot handle namespaced attributes");
}
}
| 940
| 31.448276
| 134
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/Parser.java
|
package org.infinispan.configuration.parsing;
import static org.infinispan.configuration.parsing.ParseUtils.ignoreAttribute;
import static org.infinispan.configuration.parsing.Parser.NAMESPACE;
import static org.infinispan.factories.KnownComponentNames.ASYNC_NOTIFICATION_EXECUTOR;
import static org.infinispan.factories.KnownComponentNames.BLOCKING_EXECUTOR;
import static org.infinispan.factories.KnownComponentNames.EXPIRATION_SCHEDULED_EXECUTOR;
import static org.infinispan.factories.KnownComponentNames.NON_BLOCKING_EXECUTOR;
import static org.infinispan.factories.KnownComponentNames.shortened;
import static org.infinispan.util.logging.Log.CONFIG;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import org.infinispan.commons.configuration.io.ConfigurationReader;
import org.infinispan.commons.configuration.io.ConfigurationResourceResolver;
import org.infinispan.commons.configuration.io.NamingStrategy;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.util.FileLookupFactory;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.AbstractStoreConfigurationBuilder;
import org.infinispan.configuration.cache.AsyncStoreConfigurationBuilder;
import org.infinispan.configuration.cache.StoreConfigurationBuilder;
import org.infinispan.configuration.global.AllowListConfigurationBuilder;
import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.configuration.global.GlobalRoleConfigurationBuilder;
import org.infinispan.configuration.global.GlobalSecurityConfigurationBuilder;
import org.infinispan.configuration.global.GlobalStateConfigurationBuilder;
import org.infinispan.configuration.global.SerializationConfigurationBuilder;
import org.infinispan.configuration.global.ShutdownHookBehavior;
import org.infinispan.configuration.global.ThreadPoolBuilderAdapter;
import org.infinispan.configuration.global.ThreadPoolConfiguration;
import org.infinispan.configuration.global.ThreadsConfigurationBuilder;
import org.infinispan.configuration.global.TransportConfigurationBuilder;
import org.infinispan.factories.threads.DefaultThreadFactory;
import org.infinispan.globalstate.ConfigurationStorage;
import org.infinispan.globalstate.LocalConfigurationStorage;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.remoting.transport.jgroups.BuiltinJGroupsChannelConfigurator;
import org.infinispan.remoting.transport.jgroups.EmbeddedJGroupsChannelConfigurator;
import org.infinispan.remoting.transport.jgroups.FileJGroupsChannelConfigurator;
import org.infinispan.security.PrincipalRoleMapper;
import org.infinispan.security.RolePermissionMapper;
import org.infinispan.security.mappers.CaseNameRewriter;
import org.infinispan.security.mappers.ClusterPermissionMapper;
import org.infinispan.security.mappers.ClusterRoleMapper;
import org.infinispan.security.mappers.CommonNameRoleMapper;
import org.infinispan.security.mappers.IdentityRoleMapper;
import org.infinispan.security.mappers.RegexNameRewriter;
import org.jgroups.conf.ProtocolConfiguration;
import org.kohsuke.MetaInfServices;
/**
* This class implements the parser for Infinispan/AS7/EAP/JDG schema files
*
* @author Tristan Tarrant
* @author Galder Zamarreño
* @since 9.0
*/
@MetaInfServices(ConfigurationParser.class)
@Namespace(root = "infinispan")
@Namespace(uri = NAMESPACE + "*", root = "infinispan")
public class Parser extends CacheParser {
public static final String NAMESPACE = "urn:infinispan:config:";
public Parser() {
}
@Override
public void readElement(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
addJGroupsDefaultStacksIfNeeded(reader, holder);
while (reader.inTag("infinispan")) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case CACHE_CONTAINER: {
parseContainer(reader, holder);
break;
}
case JGROUPS: {
parseJGroups(reader, holder);
break;
}
case THREADS: {
parseThreads(reader, holder);
break;
}
default: {
reader.handleAny(holder);
break;
}
}
}
}
private void parseSerialization(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
GlobalConfigurationBuilder builder = holder.getGlobalConfigurationBuilder();
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case MARSHALLER: {
builder.serialization().marshaller(Util.getInstance(value, holder.getClassLoader()));
break;
}
case VERSION: {
if (reader.getSchema().since(11, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
}
ignoreAttribute(reader, i);
break;
}
case CONTEXT_INITIALIZERS: {
for (String klass : reader.getListAttributeValue(i)) {
builder.serialization().addContextInitializer(Util.getInstance(klass, holder.getClassLoader()));
}
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
while (reader.hasNext()) {
reader.nextElement();
Element element = Element.forName(reader.getLocalName());
switch (element) {
case SERIALIZATION: {
reader.require(ConfigurationReader.ElementType.END_ELEMENT);
return;
}
case ADVANCED_EXTERNALIZERS:
// Empty elements for YAML/JSON
break;
case SERIALIZATION_CONTEXT_INITIALIZERS: {
if (reader.getAttributeCount() > 0) {
parseSerializationContextInitializer(reader, holder.getClassLoader(), builder.serialization());
}
break;
}
case ADVANCED_EXTERNALIZER: {
CONFIG.advancedExternalizerDeprecated();
parseAdvancedExternalizer(reader, holder.getClassLoader(), builder.serialization());
break;
}
case SERIALIZATION_CONTEXT_INITIALIZER: {
parseSerializationContextInitializer(reader, holder.getClassLoader(), builder.serialization());
break;
}
case WHITE_LIST:
if (reader.getSchema().since(12, 0)) {
throw ParseUtils.elementRemoved(reader, Element.ALLOW_LIST.getLocalName());
}
CONFIG.configDeprecatedUseOther(Element.WHITE_LIST, Element.ALLOW_LIST, reader.getLocation());
parseAllowList(reader, builder.serialization().allowList(), Element.WHITE_LIST);
break;
case ALLOW_LIST: {
if (reader.getSchema().since(10, 0)) {
parseAllowList(reader, builder.serialization().allowList(), Element.ALLOW_LIST);
break;
} else {
throw ParseUtils.unexpectedElement(reader);
}
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
private void parseSerializationContextInitializer(final ConfigurationReader reader, final ClassLoader classLoader,
final SerializationConfigurationBuilder builder) {
int attributes = reader.getAttributeCount();
ParseUtils.requireAttributes(reader, Attribute.CLASS.getLocalName());
for (int i = 0; i < attributes; i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case CLASS: {
builder.addContextInitializer(Util.getInstance(value, classLoader));
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
ParseUtils.requireNoContent(reader);
}
private void parseAllowList(final ConfigurationReader reader, final AllowListConfigurationBuilder builder, Element outerElement) {
for(int i = 0; i < reader.getAttributeCount(); i++) { // JSON/YAML
String[] values = reader.getListAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case CLASS:
builder.addClasses(values);
break;
case REGEX:
builder.addRegexps(values);
break;
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
while (reader.inTag(outerElement)) { // XML
Element element = Element.forName(reader.getLocalName());
switch (element) {
case CLASS: {
builder.addClass(reader.getElementText());
break;
}
case REGEX: {
builder.addRegexp(reader.getElementText());
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
private void parseAdvancedExternalizer(final ConfigurationReader reader, final ClassLoader classLoader,
final SerializationConfigurationBuilder builder) {
int attributes = reader.getAttributeCount();
AdvancedExternalizer<?> advancedExternalizer = null;
Integer id = null;
ParseUtils.requireAttributes(reader, Attribute.CLASS.getLocalName());
for (int i = 0; i < attributes; i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case CLASS: {
advancedExternalizer = Util.getInstance(value, classLoader);
break;
}
case ID: {
id = ParseUtils.parseInt(reader, i, value);
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
ParseUtils.requireNoContent(reader);
if (id != null) {
builder.addAdvancedExternalizer(id, advancedExternalizer);
} else {
builder.addAdvancedExternalizer(advancedExternalizer);
}
}
private void parseThreads(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
while (reader.hasNext()) {
reader.nextElement();
Element element = Element.forName(reader.getLocalName());
switch (element) {
case THREADS: {
reader.require(ConfigurationReader.ElementType.END_ELEMENT);
return;
}
case THREAD_FACTORIES: {
while (reader.inTag(Element.THREAD_FACTORIES)) {
parseThreadFactory(reader, holder);
}
break;
}
case THREAD_POOLS: {
while (reader.inTag(Element.THREAD_POOLS)) {
parseThreadPools(reader, holder);
}
break;
}
case THREAD_FACTORY: {
parseThreadFactory(reader, holder);
break;
}
default: {
parseThreadPools(reader, holder);
}
}
}
}
private void parseThreadPools(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
Map.Entry<String, String> threadPool = reader.getMapItem(Attribute.NAME);
Element element = Element.forName(threadPool.getValue());
switch (element) {
case CACHED_THREAD_POOL: {
parseCachedThreadPool(reader, holder, threadPool.getKey());
break;
}
case SCHEDULED_THREAD_POOL: {
parseScheduledThreadPool(reader, holder, threadPool.getKey());
break;
}
case BLOCKING_BOUNDED_QUEUE_THREAD_POOL: {
parseBoundedQueueThreadPool(reader, holder, threadPool.getKey(), false);
break;
}
case NON_BLOCKING_BOUNDED_QUEUE_THREAD_POOL: {
parseBoundedQueueThreadPool(reader, holder, threadPool.getKey(), true);
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
reader.endMapItem();
}
public void parseBoundedQueueThreadPool(ConfigurationReader reader, ConfigurationBuilderHolder holder,
String name, boolean isNonBlocking) {
ThreadsConfigurationBuilder threadsBuilder = holder.getGlobalConfigurationBuilder().threads();
String threadFactoryName = null;
int maxThreads = 0;
int coreThreads = 0;
int queueLength = 0;
long keepAlive = 0;
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case NAME: {
// Already seen
break;
}
case THREAD_FACTORY: {
threadFactoryName = value;
break;
}
case CORE_THREADS: {
coreThreads = ParseUtils.parseInt(reader, i, value);
break;
}
case MAX_THREADS: {
maxThreads = ParseUtils.parseInt(reader, i, value);
break;
}
case QUEUE_LENGTH: {
queueLength = ParseUtils.parseInt(reader, i, value);
break;
}
case KEEP_ALIVE_TIME: {
keepAlive = ParseUtils.parseLong(reader, i, value);
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
threadsBuilder.addBoundedThreadPool(name).threadFactory(threadFactoryName).coreThreads(coreThreads)
.maxThreads(maxThreads).queueLength(queueLength).keepAliveTime(keepAlive).nonBlocking(isNonBlocking);
ParseUtils.requireNoContent(reader);
}
private void parseScheduledThreadPool(ConfigurationReader reader, ConfigurationBuilderHolder holder, String name) {
ThreadsConfigurationBuilder threadsBuilder = holder.getGlobalConfigurationBuilder().threads();
String threadFactoryName = null;
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case NAME: {
// Already seen
break;
}
case THREAD_FACTORY: {
threadFactoryName = value;
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
threadsBuilder.addScheduledThreadPool(name).threadFactory(threadFactoryName);
ParseUtils.requireNoContent(reader);
}
private void parseCachedThreadPool(ConfigurationReader reader, ConfigurationBuilderHolder holder, String name) {
ThreadsConfigurationBuilder threadsBuilder = holder.getGlobalConfigurationBuilder().threads();
String threadFactoryName = null;
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case NAME: {
// Ignore
break;
}
case THREAD_FACTORY: {
threadFactoryName = value;
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
threadsBuilder.addCachedThreadPool(name).threadFactory(threadFactoryName);
ParseUtils.requireNoContent(reader);
}
private void parseThreadFactory(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
Map.Entry<String, String> threadFactory = reader.getMapItem(Attribute.NAME);
String threadGroupName = null;
String threadNamePattern = null;
int priority = 1; // minimum priority
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case NAME: {
// Already seen
break;
}
case GROUP_NAME: {
threadGroupName = value;
break;
}
case THREAD_NAME_PATTERN: {
threadNamePattern = value;
break;
}
case PRIORITY: {
priority = ParseUtils.parseInt(reader, i, value);
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
holder.getGlobalConfigurationBuilder().threads().addThreadFactory(threadFactory.getKey()).groupName(threadGroupName).priority(priority).threadNamePattern(threadNamePattern);
ParseUtils.requireNoContent(reader);
reader.endMapItem();
}
private void parseJGroups(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
Transport transport = null;
for (int i = 0; i < reader.getAttributeCount(); i++) {
if (!ParseUtils.isNoNamespaceAttribute(reader, i))
continue;
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case TRANSPORT:
transport = Util.getInstance(value, holder.getClassLoader());
break;
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
if (transport == null) {
// Set up default transport
holder.getGlobalConfigurationBuilder().transport().defaultTransport();
} else {
holder.getGlobalConfigurationBuilder().transport().transport(transport);
}
while (reader.inTag(Element.JGROUPS)) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case STACK_FILE:
parseStackFile(reader, holder, ParseUtils.requireAttributes(reader, Attribute.NAME)[0]);
break;
case STACKS:
parseJGroupsStacks(reader, holder);
break;
case STACK:
if (!reader.getSchema().since(10, 0)) {
throw ParseUtils.unexpectedElement(reader);
}
parseJGroupsStack(reader, holder, ParseUtils.requireAttributes(reader, Attribute.NAME)[0]);
break;
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
private void parseJGroupsStacks(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
while (reader.inTag(Element.STACKS)) {
Map.Entry<String, String> mapElement = reader.getMapItem(Attribute.NAME);
Element type = Element.forName(mapElement.getValue());
switch (type) {
case STACK:
parseJGroupsStack(reader, holder, mapElement.getKey());
break;
case STACK_FILE:
parseStackFile(reader, holder, mapElement.getKey());
break;
default:
throw ParseUtils.unexpectedElement(reader);
}
reader.endMapItem();
}
}
private void addJGroupsStackFile(ConfigurationBuilderHolder holder, String name, String path, Properties properties, ConfigurationResourceResolver resourceResolver) {
URL url = FileLookupFactory.newInstance().lookupFileLocation(path, holder.getClassLoader());
try (InputStream xml = (url != null ? url : resourceResolver.resolveResource(path)).openStream()) {
holder.addJGroupsStack(new FileJGroupsChannelConfigurator(name, path, xml, properties));
} catch (FileNotFoundException e) {
throw CONFIG.jgroupsConfigurationNotFound(path);
} catch (IOException e) {
throw CONFIG.unableToAddJGroupsStack(name, e);
}
}
private void parseJGroupsStack(ConfigurationReader reader, ConfigurationBuilderHolder holder, String stackName) {
String extend = null;
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case NAME:
break;
case EXTENDS:
extend = value;
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
List<ProtocolConfiguration> stack = new ArrayList<>();
EmbeddedJGroupsChannelConfigurator.RemoteSites remoteSites = null;
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case REMOTE_SITES:
remoteSites = parseJGroupsRelay(reader, holder, stackName);
break;
default:
// It should be an actual JGroups protocol
String protocolName = reader.getLocalName(NamingStrategy.IDENTITY);
Map<String, String> protocolAttributes = new HashMap<>();
for (int i = 0; i < reader.getAttributeCount(); i++) {
protocolAttributes.put(reader.getAttributeName(i, NamingStrategy.SNAKE_CASE), reader.getAttributeValue(i));
}
ParseUtils.requireNoContent(reader);
stack.add(new ProtocolConfiguration(protocolName, protocolAttributes));
break;
}
}
EmbeddedJGroupsChannelConfigurator stackConfigurator = new EmbeddedJGroupsChannelConfigurator(stackName, stack, remoteSites);
holder.addJGroupsStack(stackConfigurator, extend);
}
private EmbeddedJGroupsChannelConfigurator.RemoteSites parseJGroupsRelay(ConfigurationReader reader, ConfigurationBuilderHolder holder, String stackName) {
String defaultStack = ParseUtils.requireAttributes(reader, Attribute.DEFAULT_STACK)[0];
String defaultCluster = "xsite";
if (!holder.hasJGroupsStack(defaultStack)) {
throw CONFIG.missingJGroupsStack(defaultStack);
}
for (int i = 0; i < reader.getAttributeCount(); i++) {
if (!ParseUtils.isNoNamespaceAttribute(reader, i))
continue;
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case DEFAULT_STACK:
// Already seen
break;
case CLUSTER:
defaultCluster = value;
break;
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
EmbeddedJGroupsChannelConfigurator.RemoteSites remoteSites = new EmbeddedJGroupsChannelConfigurator.RemoteSites(defaultStack, defaultCluster);
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case REMOTE_SITE:
if (reader.getAttributeCount() > 0) {
String remoteSite = ParseUtils.requireAttributes(reader, Attribute.NAME)[0];
String cluster = defaultCluster;
String stack = defaultStack;
for (int i = 0; i < reader.getAttributeCount(); i++) {
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case NAME:
break;
case STACK:
stack = reader.getAttributeValue(i);
break;
case CLUSTER:
cluster = reader.getAttributeValue(i);
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
ParseUtils.requireNoContent(reader);
remoteSites.addRemoteSite(stackName, remoteSite, cluster, stack);
}
break;
default:
throw ParseUtils.unexpectedElement(reader);
}
}
return remoteSites;
}
private void parseStackFile(ConfigurationReader reader, ConfigurationBuilderHolder holder, String name) {
String path = ParseUtils.requireAttributes(reader, Attribute.PATH)[0];
ParseUtils.requireNoContent(reader);
addJGroupsStackFile(holder, name, path, reader.getProperties(), reader.getResourceResolver());
}
private void parseContainer(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
holder.pushScope(ParserScope.CACHE_CONTAINER);
GlobalConfigurationBuilder builder = holder.getGlobalConfigurationBuilder();
for (int i = 0; i < reader.getAttributeCount(); i++) {
if (!ParseUtils.isNoNamespaceAttribute(reader, i))
continue;
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case NAME: {
builder.cacheManagerName(value);
break;
}
case DEFAULT_CACHE: {
builder.defaultCacheName(value);
break;
}
case ALIASES:
case JNDI_NAME:
case MODULE:
case START:
case ASYNC_EXECUTOR:
case PERSISTENCE_EXECUTOR:
case STATE_TRANSFER_EXECUTOR: {
if (reader.getSchema().since(11, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
ignoreAttribute(reader, i);
}
break;
}
case LISTENER_EXECUTOR: {
builder.listenerThreadPoolName(value);
builder.listenerThreadPool().read(createThreadPoolConfiguration(value, ASYNC_NOTIFICATION_EXECUTOR, holder), holder.getCombine());
break;
}
case EVICTION_EXECUTOR:
if (reader.getSchema().since(11, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
CONFIG.evictionExecutorDeprecated();
}
// fallthrough
case EXPIRATION_EXECUTOR: {
builder.expirationThreadPoolName(value);
builder.expirationThreadPool().read(createThreadPoolConfiguration(value, EXPIRATION_SCHEDULED_EXECUTOR, holder), holder.getCombine());
break;
}
case REPLICATION_QUEUE_EXECUTOR: {
if (reader.getSchema().since(9, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
CONFIG.ignoredReplicationQueueAttribute(attribute.getLocalName(), reader.getLocation().getLineNumber());
}
break;
}
case NON_BLOCKING_EXECUTOR: {
builder.nonBlockingThreadPoolName(value);
builder.nonBlockingThreadPool().read(createThreadPoolConfiguration(value, NON_BLOCKING_EXECUTOR, holder), holder.getCombine());
break;
}
case BLOCKING_EXECUTOR: {
builder.blockingThreadPoolName(value);
builder.blockingThreadPool().read(createThreadPoolConfiguration(value, BLOCKING_EXECUTOR, holder), holder.getCombine());
break;
}
case STATISTICS: {
boolean statistics = ParseUtils.parseBoolean(reader, i, value);
builder.cacheContainer().statistics(statistics);
if (!reader.getSchema().since(10, 1)) {
builder.jmx().enabled(statistics);
}
break;
}
case SHUTDOWN_HOOK: {
builder.shutdown().hookBehavior(ParseUtils.parseEnum(reader, i, ShutdownHookBehavior.class, value));
break;
}
case ZERO_CAPACITY_NODE: {
builder.zeroCapacityNode(ParseUtils.parseBoolean(reader, i, value));
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
while (reader.inTag(Element.CACHE_CONTAINER)) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case CACHES: {
// Wrapper element for YAML/JSON
parseCaches(reader, holder);
break;
}
case TRANSPORT: {
parseTransport(reader, holder);
break;
}
case LOCAL_CACHE: {
parseLocalCache(reader, holder, ParseUtils.requireAttributes(reader, Attribute.NAME)[0], false);
break;
}
case LOCAL_CACHE_CONFIGURATION: {
parseLocalCache(reader, holder, ParseUtils.requireAttributes(reader, Attribute.NAME)[0], true);
break;
}
case INVALIDATION_CACHE: {
parseInvalidationCache(reader, holder, ParseUtils.requireAttributes(reader, Attribute.NAME)[0], false);
break;
}
case INVALIDATION_CACHE_CONFIGURATION: {
parseInvalidationCache(reader, holder, ParseUtils.requireAttributes(reader, Attribute.NAME)[0], true);
break;
}
case REPLICATED_CACHE: {
parseReplicatedCache(reader, holder, ParseUtils.requireAttributes(reader, Attribute.NAME)[0], false);
break;
}
case REPLICATED_CACHE_CONFIGURATION: {
parseReplicatedCache(reader, holder, ParseUtils.requireAttributes(reader, Attribute.NAME)[0], true);
break;
}
case DISTRIBUTED_CACHE: {
parseDistributedCache(reader, holder, ParseUtils.requireAttributes(reader, Attribute.NAME)[0], false);
break;
}
case DISTRIBUTED_CACHE_CONFIGURATION: {
parseDistributedCache(reader, holder, ParseUtils.requireAttributes(reader, Attribute.NAME)[0], true);
break;
}
case SERIALIZATION: {
parseSerialization(reader, holder);
break;
}
case MODULES: {
if (reader.getSchema().since(9, 0)) {
throw ParseUtils.elementRemoved(reader);
} else {
parseModules(reader, holder);
}
break;
}
case METRICS: {
parseMetrics(reader, holder);
break;
}
case JMX: {
parseJmx(reader, holder);
break;
}
case SECURITY: {
parseGlobalSecurity(reader, holder);
break;
}
case GLOBAL_STATE: {
if (reader.getSchema().since(8, 1)) {
parseGlobalState(reader, holder);
} else {
throw ParseUtils.unexpectedElement(reader);
}
break;
}
default: {
reader.handleAny(holder);
}
}
}
holder.popScope();
}
private void parseCaches(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
while (reader.inTag(Element.CACHES)) {
Map.Entry<String, String> mapElement = reader.getMapItem(Attribute.NAME);
String name = mapElement.getKey();
Element type = Element.forName(mapElement.getValue());
switch (type) {
case LOCAL_CACHE:
parseLocalCache(reader, holder, name, false);
break;
case LOCAL_CACHE_CONFIGURATION:
parseLocalCache(reader, holder, name, true);
break;
case INVALIDATION_CACHE:
parseInvalidationCache(reader, holder, name, false);
break;
case INVALIDATION_CACHE_CONFIGURATION:
parseInvalidationCache(reader, holder, name, true);
break;
case REPLICATED_CACHE:
parseReplicatedCache(reader, holder, name, false);
break;
case REPLICATED_CACHE_CONFIGURATION:
parseReplicatedCache(reader, holder, name, true);
break;
case DISTRIBUTED_CACHE:
parseDistributedCache(reader, holder, name, false);
break;
case DISTRIBUTED_CACHE_CONFIGURATION:
parseDistributedCache(reader, holder, name, true);
break;
default:
throw ParseUtils.unexpectedElement(reader, type);
}
reader.endMapItem();
}
}
private void parseGlobalSecurity(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
GlobalSecurityConfigurationBuilder security = holder.getGlobalConfigurationBuilder().security();
ParseUtils.parseAttributes(reader, security);
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case AUTHORIZATION: {
parseGlobalAuthorization(reader, holder);
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
private void parseGlobalAuthorization(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
GlobalAuthorizationConfigurationBuilder builder = holder.getGlobalConfigurationBuilder().security().authorization().enable();
Boolean groupOnlyMapping = reader.getSchema().since(15,0 ) ? null : false;
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case AUDIT_LOGGER: {
builder.auditLogger(Util.getInstance(value, holder.getClassLoader()));
break;
}
case GROUP_ONLY_MAPPING: {
groupOnlyMapping = ParseUtils.parseBoolean(reader, i, value);
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
PrincipalRoleMapper roleMapper = null;
RolePermissionMapper permissionMapper = null;
while (reader.hasNext()) {
reader.nextElement();
Element element = Element.forName(reader.getLocalName());
switch (element) {
case AUTHORIZATION: {
reader.require(ConfigurationReader.ElementType.END_ELEMENT);
if (permissionMapper != null) {
builder.rolePermissionMapper(permissionMapper);
}
if (roleMapper != null) {
builder.principalRoleMapper(roleMapper);
}
if (groupOnlyMapping != null) {
builder.groupOnlyMapping(groupOnlyMapping);
}
return;
}
case CLUSTER_PERMISSION_MAPPER:
if (permissionMapper != null) {
throw ParseUtils.unexpectedElement(reader);
}
ParseUtils.requireNoAttributes(reader);
ParseUtils.requireNoContent(reader);
permissionMapper = new ClusterPermissionMapper();
break;
case CUSTOM_PERMISSION_MAPPER:
if (permissionMapper != null) {
throw ParseUtils.unexpectedElement(reader);
}
permissionMapper = parseCustomPermissionMapper(reader, holder);
break;
case IDENTITY_ROLE_MAPPER:
if (roleMapper != null) {
throw ParseUtils.unexpectedElement(reader);
}
ParseUtils.requireNoAttributes(reader);
ParseUtils.requireNoContent(reader);
roleMapper = new IdentityRoleMapper();
break;
case COMMON_NAME_ROLE_MAPPER:
if (roleMapper != null) {
throw ParseUtils.unexpectedElement(reader);
}
ParseUtils.requireNoAttributes(reader);
ParseUtils.requireNoContent(reader);
roleMapper = new CommonNameRoleMapper();
break;
case CLUSTER_ROLE_MAPPER:
if (roleMapper != null) {
throw ParseUtils.unexpectedElement(reader);
}
roleMapper = parseClusterRoleMapper(reader);
break;
case CUSTOM_ROLE_MAPPER:
if (roleMapper != null) {
throw ParseUtils.unexpectedElement(reader);
}
roleMapper = parseCustomRoleMapper(reader, holder);
break;
case ROLES: {
while (reader.inTag()) {
Map.Entry<String, String> item = reader.getMapItem(Attribute.NAME);
parseGlobalRole(reader, builder, item.getKey());
reader.endMapItem();
}
break;
}
case ROLE: {
parseGlobalRole(reader, builder, null);
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
private ClusterRoleMapper parseClusterRoleMapper(ConfigurationReader reader) {
ParseUtils.requireNoAttributes(reader);
ClusterRoleMapper mapper = new ClusterRoleMapper();
while (reader.inTag()) {
if (Element.forName(reader.getLocalName()) == Element.NAME_REWRITER) {
while (reader.inTag()) {
switch (Element.forName(reader.getLocalName())) {
case CASE_PRINCIPAL_TRANSFORMER: {
boolean uppercase = true;
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
if (Objects.requireNonNull(attribute) == Attribute.UPPERCASE) {
uppercase = ParseUtils.parseBoolean(reader, i, value);
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
mapper.nameRewriter(new CaseNameRewriter(uppercase));
ParseUtils.requireNoContent(reader);
break;
}
case COMMON_NAME_PRINCIPAL_TRANSFORMER: {
ParseUtils.requireNoAttributes(reader);
mapper.nameRewriter(new RegexNameRewriter(Pattern.compile("cn=([^,]+),.*", Pattern.CASE_INSENSITIVE), "$1", false));
ParseUtils.requireNoContent(reader);
break;
}
case REGEX_PRINCIPAL_TRANSFORMER: {
String[] attributes = ParseUtils.requireAttributes(reader, Attribute.PATTERN, Attribute.REPLACEMENT);
boolean replaceAll = false;
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case NAME:
case PATTERN:
case REPLACEMENT:
// Already seen
break;
case REPLACE_ALL:
replaceAll = ParseUtils.parseBoolean(reader, i, value);
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
mapper.nameRewriter(new RegexNameRewriter(Pattern.compile(attributes[0]), attributes[1], replaceAll));
ParseUtils.requireNoContent(reader);
break;
}
default:
throw ParseUtils.unexpectedElement(reader);
}
}
}
}
return mapper;
}
private PrincipalRoleMapper parseCustomRoleMapper(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
String mapperClass = ParseUtils.requireSingleAttribute(reader, Attribute.CLASS.getLocalName());
ParseUtils.requireNoContent(reader);
return Util.getInstance(mapperClass, holder.getClassLoader());
}
private RolePermissionMapper parseCustomPermissionMapper(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
String mapperClass = ParseUtils.requireSingleAttribute(reader, Attribute.CLASS.getLocalName());
ParseUtils.requireNoContent(reader);
return Util.getInstance(mapperClass, holder.getClassLoader());
}
private void parseGlobalRole(ConfigurationReader reader, GlobalAuthorizationConfigurationBuilder builder, String name) {
if (name == null) {
name = ParseUtils.requireAttributes(reader, Attribute.NAME.getLocalName())[0];
}
String[] permissions = null;
GlobalRoleConfigurationBuilder role = builder.role(name);
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case NAME: {
// Already handled
break;
}
case PERMISSIONS: {
permissions = reader.getListAttributeValue(i);
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
if (permissions != null) {
role.permission(permissions);
} else {
throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.PERMISSIONS));
}
ParseUtils.requireNoContent(reader);
}
private void parseMetrics(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
GlobalConfigurationBuilder builder = holder.getGlobalConfigurationBuilder();
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case GAUGES: {
builder.metrics().gauges(ParseUtils.parseBoolean(reader, i, value));
break;
}
case HISTOGRAMS: {
builder.metrics().histograms(ParseUtils.parseBoolean(reader, i, value));
break;
}
case PREFIX: {
builder.metrics().prefix(value);
break;
}
case NAMES_AS_TAGS: {
builder.metrics().namesAsTags(ParseUtils.parseBoolean(reader, i, value));
break;
}
case ACCURATE_SIZE: {
builder.metrics().accurateSize(ParseUtils.parseBoolean(reader, i, value));
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
ParseUtils.requireNoContent(reader);
}
private void parseJmx(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
GlobalConfigurationBuilder builder = holder.getGlobalConfigurationBuilder();
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case ENABLED: {
builder.jmx().enabled(ParseUtils.parseBoolean(reader, i, value));
break;
}
case DOMAIN: {
builder.jmx().domain(value);
break;
}
case MBEAN_SERVER_LOOKUP: {
builder.jmx().mBeanServerLookup(Util.getInstance(value, holder.getClassLoader()));
break;
}
case ALLOW_DUPLICATE_DOMAINS: {
if (!reader.getSchema().since(11, 0)) {
ignoreAttribute(reader, i);
break;
} else {
throw ParseUtils.attributeRemoved(reader, i);
}
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
Properties properties = parseProperties(reader, Element.JMX);
builder.jmx().withProperties(properties);
}
private void parseModules(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
while (reader.inTag()) {
reader.handleAny(holder);
}
}
private void parseTransport(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
if (holder.getGlobalConfigurationBuilder().transport().getTransport() == null) {
holder.getGlobalConfigurationBuilder().transport().defaultTransport();
}
TransportConfigurationBuilder transport = holder.getGlobalConfigurationBuilder().transport();
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
if (ParseUtils.isNoNamespaceAttribute(reader, i)) {
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case STACK: {
transport.stack(value);
break;
}
case CLUSTER: {
transport.clusterName(value);
break;
}
case EXECUTOR: {
if (reader.getSchema().since(11, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
CONFIG.ignoredAttribute("transport executor", "11.0", attribute.getLocalName(), reader.getLocation().getLineNumber());
}
break;
}
case TOTAL_ORDER_EXECUTOR: {
if (reader.getSchema().since(9, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
CONFIG.ignoredAttribute("total order executor", "9.0", attribute.getLocalName(), reader.getLocation().getLineNumber());
}
break;
}
case REMOTE_COMMAND_EXECUTOR: {
if (reader.getSchema().since(11, 0)) {
throw ParseUtils.attributeRemoved(reader, i);
} else {
CONFIG.ignoredAttribute("remote command executor", "11.0", attribute.getLocalName(), reader.getLocation().getLineNumber());
}
break;
}
case LOCK_TIMEOUT: {
transport.distributedSyncTimeout(ParseUtils.parseLong(reader, i, value));
break;
}
case NODE_NAME: {
transport.nodeName(value);
holder.getGlobalConfigurationBuilder().threads().nodeName(value);
break;
}
case LOCKING:
break;
case MACHINE_ID: {
transport.machineId(value);
break;
}
case RACK_ID: {
transport.rackId(value);
break;
}
case SITE: {
transport.siteId(value);
break;
}
case INITIAL_CLUSTER_SIZE: {
if (reader.getSchema().since(8, 2)) {
transport.initialClusterSize(ParseUtils.parseInt(reader, i, value));
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
break;
}
case INITIAL_CLUSTER_TIMEOUT: {
if (reader.getSchema().since(8, 2)) {
transport.initialClusterTimeout(ParseUtils.parseLong(reader, i, value), TimeUnit.MILLISECONDS);
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
break;
}
case RAFT_MEMBERS:
transport.raftMembers(ParseUtils.getListAttributeValue(value));
break;
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
} else {
reader.handleAttribute(holder, i);
}
}
Properties properties = parseProperties(reader, Element.TRANSPORT);
for (Map.Entry<Object, Object> propertyEntry : properties.entrySet()) {
transport.addProperty((String) propertyEntry.getKey(), propertyEntry.getValue());
}
}
private void parseGlobalState(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
GlobalStateConfigurationBuilder builder = holder.getGlobalConfigurationBuilder().globalState().enable();
ParseUtils.parseAttributes(reader, builder);
ConfigurationStorage storage = null;
while (reader.inTag()) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case PERSISTENT_LOCATION: {
parseGlobalStatePath(reader, builder::persistentLocation);
break;
}
case SHARED_PERSISTENT_LOCATION: {
parseGlobalStatePath(reader, builder::sharedPersistentLocation);
break;
}
case TEMPORARY_LOCATION: {
parseGlobalStatePath(reader, builder::temporaryLocation);
break;
}
case IMMUTABLE_CONFIGURATION_STORAGE: {
if (storage != null) {
throw ParseUtils.unexpectedElement(reader);
}
storage = ConfigurationStorage.IMMUTABLE;
break;
}
case VOLATILE_CONFIGURATION_STORAGE: {
if (storage != null) {
throw ParseUtils.unexpectedElement(reader);
}
ParseUtils.requireNoAttributes(reader);
ParseUtils.requireNoContent(reader);
storage = ConfigurationStorage.VOLATILE;
break;
}
case OVERLAY_CONFIGURATION_STORAGE: {
if (storage != null) {
throw ParseUtils.unexpectedElement(reader);
}
ParseUtils.requireNoAttributes(reader);
ParseUtils.requireNoContent(reader);
storage = ConfigurationStorage.OVERLAY;
break;
}
case MANAGED_CONFIGURATION_STORAGE: {
if (storage != null) {
throw ParseUtils.unexpectedElement(reader);
} else {
throw CONFIG.managerConfigurationStorageUnavailable();
}
}
case CUSTOM_CONFIGURATION_STORAGE: {
if (storage != null) {
throw ParseUtils.unexpectedElement(reader);
}
storage = ConfigurationStorage.CUSTOM;
builder.configurationStorageSupplier(parseCustomConfigurationStorage(reader, holder));
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
if (storage != null) {
builder.configurationStorage(storage);
}
}
private void parseGlobalStatePath(ConfigurationReader reader, BiConsumer<String, String> pathItems) {
String path = ParseUtils.requireAttributes(reader, Attribute.PATH.getLocalName())[0];
String relativeTo = null;
for (int i = 0; i < reader.getAttributeCount(); i++) {
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case RELATIVE_TO: {
relativeTo = ParseUtils.requireAttributeProperty(reader, i);
break;
}
case PATH: {
// Handled above
break;
}
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
ParseUtils.requireNoContent(reader);
pathItems.accept(path, relativeTo);
}
private Supplier<? extends LocalConfigurationStorage> parseCustomConfigurationStorage(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
String storageClass = ParseUtils.requireSingleAttribute(reader, Attribute.CLASS.getLocalName());
ParseUtils.requireNoContent(reader);
return Util.getInstanceSupplier(storageClass, holder.getClassLoader());
}
private ThreadPoolConfiguration createThreadPoolConfiguration(String threadPoolName, String componentName, ConfigurationBuilderHolder holder) {
ThreadsConfigurationBuilder threads = holder.getGlobalConfigurationBuilder().threads();
ThreadPoolBuilderAdapter threadPool = threads.getThreadPool(threadPoolName);
if (threadPool == null)
throw CONFIG.undefinedThreadPoolName(threadPoolName);
ThreadPoolConfiguration threadPoolConfiguration = threadPool.asThreadPoolConfigurationBuilder();
boolean isNonBlocking = threadPoolConfiguration.threadPoolFactory().createsNonBlockingThreads();
if (NON_BLOCKING_EXECUTOR.equals(componentName) && !isNonBlocking) {
throw CONFIG.threadPoolFactoryIsBlocking(threadPoolName, componentName);
}
DefaultThreadFactory threadFactory = threadPoolConfiguration.threadFactory();
if (threadFactory != null) {
threadFactory.setComponent(shortened(componentName));
}
return threadPoolConfiguration;
}
/**
* @deprecated use {@link CacheParser#parseStoreAttribute(ConfigurationReader, int, AbstractStoreConfigurationBuilder)}
*/
@Deprecated
public static void parseStoreAttribute(ConfigurationReader reader, int index, AbstractStoreConfigurationBuilder<?, ?> storeBuilder) {
CacheParser.parseStoreAttribute(reader, index, storeBuilder);
}
/**
* @deprecated use {@link CacheParser#parseStoreElement(ConfigurationReader, StoreConfigurationBuilder)}
*/
@Deprecated
public static void parseStoreElement(ConfigurationReader reader, StoreConfigurationBuilder<?, ?> storeBuilder) {
CacheParser.parseStoreElement(reader, storeBuilder);
}
/**
* @deprecated use {@link CacheParser#parseStoreWriteBehind(ConfigurationReader, AsyncStoreConfigurationBuilder)}
*/
@Deprecated
public static void parseStoreWriteBehind(ConfigurationReader reader, AsyncStoreConfigurationBuilder<?> storeBuilder) {
CacheParser.parseStoreWriteBehind(reader, storeBuilder);
}
/**
* @deprecated use {@link CacheParser#parseStoreProperty(ConfigurationReader, StoreConfigurationBuilder)}
*/
@Deprecated
public static void parseStoreProperty(ConfigurationReader reader, StoreConfigurationBuilder<?, ?> storeBuilder) {
String property = ParseUtils.requireSingleAttribute(reader, Attribute.NAME.getLocalName());
String value = reader.getElementText();
storeBuilder.addProperty(property, value);
}
@Override
public Namespace[] getNamespaces() {
return ParseUtils.getNamespaceAnnotations(getClass());
}
private void addJGroupsDefaultStacksIfNeeded(final ConfigurationReader reader, final ConfigurationBuilderHolder holder) {
if (!holder.hasJGroupsStack(BuiltinJGroupsChannelConfigurator.TCP_STACK_NAME)) {
holder.addJGroupsStack(BuiltinJGroupsChannelConfigurator.TCP(reader.getProperties()));
holder.addJGroupsStack(BuiltinJGroupsChannelConfigurator.UDP(reader.getProperties()));
holder.addJGroupsStack(BuiltinJGroupsChannelConfigurator.KUBERNETES(reader.getProperties()));
holder.addJGroupsStack(BuiltinJGroupsChannelConfigurator.EC2(reader.getProperties()));
holder.addJGroupsStack(BuiltinJGroupsChannelConfigurator.GOOGLE(reader.getProperties()));
holder.addJGroupsStack(BuiltinJGroupsChannelConfigurator.AZURE(reader.getProperties()));
}
}
}
| 59,222
| 40.184284
| 179
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/ConfigurationParserListener.java
|
package org.infinispan.configuration.parsing;
import java.util.EventListener;
/**
* ConfigurationParserListener. An interface which should be implemented by listeners who wish to be
* notified when a file has been successfully parsed.
*
* @author Tristan Tarrant
* @since 5.2
*/
public interface ConfigurationParserListener extends EventListener {
void parsingComplete(ConfigurationBuilderHolder holder);
}
| 418
| 26.933333
| 100
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/Attribute.java
|
package org.infinispan.configuration.parsing;
import java.util.HashMap;
import java.util.Map;
/**
* Enumerates the attributes used in Infinispan
*
* @author Pete Muir
*/
public enum Attribute {
// must be first
UNKNOWN(null),
// KEEP THESE IN ALPHABETICAL ORDER!
ACQUIRE_TIMEOUT,
ADDRESS_COUNT,
AFTER,
ALIASES,
@Deprecated
ALLOW_DUPLICATE_DOMAINS("duplicate-domains"),
@Deprecated
ASYNC_EXECUTOR,
@Deprecated
ASYNC_MARSHALLING,
AUDIT_LOGGER,
AUTO_COMMIT,
AVAILABILITY_INTERVAL,
AWAIT_INITIAL_TRANSFER,
BACKUP_FAILURE_POLICY("failure-policy"),
BEFORE,
BIAS_ACQUISITION,
BIAS_LIFESPAN,
BLOCKING_EXECUTOR,
CACHE_SIZE,
CACHE_TIMEOUT,
CALIBRATE_BY_DELETES,
@Deprecated
CAPACITY,
CAPACITY_FACTOR,
CHUNK_SIZE,
CLASS,
CLUSTER,
COMMIT_INTERVAL,
COMPACTION_THRESHOLD,
COMPLETED_TX_TIMEOUT("complete-timeout"),
CONCURRENCY_LEVEL,
CONFIGURATION,
CONNECTION_ATTEMPTS,
CONNECTION_INTERVAL,
CONSISTENT_HASH_FACTORY,
CONTEXT_INITIALIZER,
CORE_THREADS,
DATA_CONTAINER,
DEFAULT_CACHE,
DEFAULT_STACK,
DEFAULT_MAX_RESULTS,
DOMAIN,
ENABLED,
ENCODER,
EXECUTOR,
EVICTION,
@Deprecated
EVICTION_EXECUTOR,
@Deprecated
EVICTION_STRATEGY,
EXPIRATION_EXECUTOR,
EXTENDS,
FACTOR,
FAIL_SILENTLY,
FAILURE_POLICY_CLASS,
FETCH_STATE,
@Deprecated
FLUSH_LOCK_TIMEOUT,
FRAGMENTATION_FACTOR,
GAUGES,
GROUP_NAME,
GROUP_ONLY_MAPPING,
HISTOGRAMS,
ID,
INDEX,
INDEX_QUEUE_LENGTH("max-queue-length"),
INDEXED_ENTITIES,
INDEXING_MODE,
INITIAL_CLUSTER_SIZE,
INITIAL_CLUSTER_TIMEOUT,
INTERVAL,
INVALIDATION_BATCH_SIZE,
INVALIDATION_CLEANUP_TASK_FREQUENCY("l1-cleanup-interval"),
ISOLATION,
JNDI_NAME,
KEEP_ALIVE_TIME("keepalive-time"),
KEY,
KEY_EQUIVALENCE,
KEY_PARTITIONER,
HASH_FUNCTION,
HIT_COUNT_ACCURACY,
L1_LIFESPAN("l1-lifespan"),
LIFESPAN,
LISTENER_EXECUTOR,
LOCATION,
LOCK_TIMEOUT,
LOCKING,
LOW_LEVEL_TRACE,
MACHINE_ID("machine"),
MAPPER,
MARSHALLER,
MAX_BATCH_SIZE,
MAX_CLEANUP_DELAY,
MAX_COUNT,
MAX_ENTRIES,
MAX_FILE_SIZE,
MAX_IDLE,
MAX_NODE_SIZE,
MAX_RETRIES,
MIN_SIZE,
MAX_BUFFERED_ENTRIES,
MAX_FORCED_SIZE,
MAX_SIZE,
MAX_THREADS,
MBEAN_SERVER_LOOKUP,
MERGE_POLICY,
MEDIA_TYPE,
MIN_NODE_SIZE,
MODE,
NODE_NAME,
MODIFICATION_QUEUE_SIZE,
MODULE,
NAME,
NAMES,
NAMES_AS_TAGS,
NON_BLOCKING_EXECUTOR,
NOTIFICATIONS,
ON_REHASH("onRehash"),
OPEN_FILES_LIMIT,
OWNERS,
PATH,
PASSIVATION,
PERMISSIONS,
@Deprecated
PERSISTENCE_EXECUTOR,
POSITION,
PREFIX,
PRELOAD,
PRIORITY,
PROPERTIES,
PURGE,
QUEUE_COUNT,
@Deprecated
QUEUE_FLUSH_INTERVAL,
QUEUE_LENGTH,
QUEUE_SIZE,
RACK_ID("rack"),
RAM_BUFFER_SIZE,
RAFT_MEMBERS,
READ_ONLY,
REAPER_WAKE_UP_INTERVAL("reaper-interval"),
RECOVERY_INFO_CACHE_NAME("recovery-cache"),
REFRESH_INTERVAL,
RELATIVE_TO,
REMOTE_CACHE,
REMOTE_COMMAND_EXECUTOR,
REMOTE_SITE,
REMOTE_TIMEOUT,
@Deprecated
REPLICATION_QUEUE_EXECUTOR,
ROLES,
SEGMENTED,
SEGMENTS,
SHARDS,
SHARED,
SHUTDOWN_HOOK,
@Deprecated
SHUTDOWN_TIMEOUT,
SIMPLE_CACHE,
@Deprecated
SINGLETON,
SITE,
SIZE,
@Deprecated
SPIN_DURATION("deadlock-detection-spin"),
STATISTICS,
STATISTICS_AVAILABLE,
START,
STARTUP_MODE,
@Deprecated
STATE_TRANSFER_EXECUTOR,
STORAGE,
STORE_KEYS_AS_BINARY("keys"),
STORE_VALUES_AS_BINARY("values"),
STRATEGY,
STRIPING,
STACK,
STOP_TIMEOUT,
SYNC_WRITES,
TAKE_BACKUP_OFFLINE_AFTER_FAILURES("after-failures"),
TAKE_BACKUP_OFFLINE_MIN_WAIT("min-wait"),
THREAD_FACTORY,
THREAD_NAME_PATTERN,
THREAD_POLICY,
THREAD_POOL_SIZE,
TIMEOUT,
TOMBSTONE_MAP_SIZE,
TOTAL_ORDER_EXECUTOR,
TOUCH,
TRANSACTION_MANAGER_LOOKUP_CLASS("transaction-manager-lookup"),
TRANSACTION_PROTOCOL("protocol"),
TRANSACTIONAL,
TRANSFORMER,
TRANSPORT,
TYPE,
UNRELIABLE_RETURN_VALUES,
USE_TWO_PHASE_COMMIT("two-phase-commit"),
VALUE,
VALUE_EQUIVALENCE,
VERSION,
VERSIONING_SCHEME("scheme"),
WAIT_TIME,
WHEN_SPLIT,
WHEN_FULL,
WRITE_ONLY,
WRITE_SKEW_CHECK("write-skew"),
ZERO_CAPACITY_NODE,
INVALIDATION_THRESHOLD,
CONTEXT_INITIALIZERS,
GROUPER,
ACCURATE_SIZE,
REGEX,
PATTERN,
REPLACEMENT,
REPLACE_ALL,
UNCLEAN_SHUTDOWN_ACTION,
UPPERCASE,
;
private final String name;
Attribute(final String name) {
this.name = name;
}
Attribute() {
this.name = name().toLowerCase().replace('_', '-');
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Attribute> attributes;
static {
final Map<String, Attribute> map = new HashMap<>(64);
for (Attribute attribute : values()) {
final String name = attribute.getLocalName();
if (name != null) map.put(name, attribute);
}
attributes = map;
}
public static Attribute forName(String localName) {
final Attribute attribute = attributes.get(localName);
return attribute == null ? UNKNOWN : attribute;
}
@Override
public String toString() {
return name;
}
}
| 5,693
| 19.555957
| 67
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/ConfigurationBuilderHolder.java
|
package org.infinispan.configuration.parsing;
import static org.infinispan.util.logging.Log.CONFIG;
import java.lang.ref.WeakReference;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.io.ConfigurationReader;
import org.infinispan.commons.configuration.io.ConfigurationReaderContext;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.configuration.global.JGroupsConfigurationBuilder;
import org.infinispan.remoting.transport.jgroups.EmbeddedJGroupsChannelConfigurator;
import org.infinispan.remoting.transport.jgroups.FileJGroupsChannelConfigurator;
public class ConfigurationBuilderHolder implements ConfigurationReaderContext {
private final GlobalConfigurationBuilder globalConfigurationBuilder;
private final Map<String, ConfigurationBuilder> namedConfigurationBuilders;
private ConfigurationBuilder currentConfigurationBuilder;
private final WeakReference<ClassLoader> classLoader;
private final Deque<String> scope;
private final JGroupsConfigurationBuilder jgroupsBuilder;
private NamespaceMappingParser namespaceMappingParser;
private final List<ConfigurationParserListener> listeners = new ArrayList<>();
private Combine combine = Combine.DEFAULT;
public ConfigurationBuilderHolder() {
this(Thread.currentThread().getContextClassLoader());
}
public ConfigurationBuilderHolder(ClassLoader classLoader) {
this(classLoader, new GlobalConfigurationBuilder().classLoader(classLoader));
}
public ConfigurationBuilderHolder(ClassLoader classLoader, GlobalConfigurationBuilder globalConfigurationBuilder) {
this.globalConfigurationBuilder = globalConfigurationBuilder;
this.namedConfigurationBuilders = new LinkedHashMap<>();
this.jgroupsBuilder = this.globalConfigurationBuilder.transport().jgroups();
this.classLoader = new WeakReference<>(classLoader);
scope = new ArrayDeque<>();
scope.push(ParserScope.GLOBAL.name());
}
public GlobalConfigurationBuilder getGlobalConfigurationBuilder() {
return globalConfigurationBuilder;
}
public ConfigurationBuilder newConfigurationBuilder(String name) {
ConfigurationBuilder builder = new ConfigurationBuilder();
namedConfigurationBuilders.put(name, builder);
currentConfigurationBuilder = builder;
return builder;
}
public Map<String, ConfigurationBuilder> getNamedConfigurationBuilders() {
return namedConfigurationBuilders;
}
public ConfigurationBuilder getCurrentConfigurationBuilder() {
return currentConfigurationBuilder;
}
public ConfigurationBuilder getDefaultConfigurationBuilder() {
if (globalConfigurationBuilder.defaultCacheName().isPresent()) {
return namedConfigurationBuilders.get(globalConfigurationBuilder.defaultCacheName().get());
} else {
return null;
}
}
void pushScope(Enum<?> scope) {
pushScope(scope.name());
}
public void pushScope(String scope) {
this.scope.push(scope);
}
public String popScope() {
return this.scope.pop();
}
public boolean inScope(String scope) {
return getScope().equals(scope);
}
public boolean inScope(Enum<?> scope) {
return inScope(scope.name());
}
public String getScope() {
return scope.peek();
}
public void setCombine(Combine combine) {
this.combine = combine;
}
public Combine getCombine() {
return combine;
}
public void addParserListener(ConfigurationParserListener listener) {
listeners.add(listener);
}
public void fireParserListeners() {
for (ConfigurationParserListener listener : listeners) {
listener.parsingComplete(this);
}
}
public ClassLoader getClassLoader() {
return classLoader.get();
}
public ConfigurationBuilderHolder validate() {
globalConfigurationBuilder.defaultCacheName().ifPresent(name -> {
if (!namedConfigurationBuilders.containsKey(name))
throw CONFIG.missingDefaultCacheDeclaration(name);
});
return this;
}
public void addJGroupsStack(FileJGroupsChannelConfigurator stack) {
jgroupsBuilder.addStackFile(stack.getName()).fileChannelConfigurator(stack);
}
public void addJGroupsStack(EmbeddedJGroupsChannelConfigurator stack, String extend) {
jgroupsBuilder.addStack(stack.getName()).extend(extend).channelConfigurator(stack);
}
boolean hasJGroupsStack(String name) {
return jgroupsBuilder.hasStack(name);
}
public void setNamespaceMappingParser(NamespaceMappingParser namespaceMappingParser) {
this.namespaceMappingParser = namespaceMappingParser;
}
@Override
public void handleAnyElement(ConfigurationReader reader) {
namespaceMappingParser.parseElement(reader, this);
}
@Override
public void handleAnyAttribute(ConfigurationReader reader, int i) {
namespaceMappingParser.parseAttribute(reader, i, this);
}
void resolveConfigurations() {
// Resolve all configurations
for (Map.Entry<String, ConfigurationBuilder> entry : namedConfigurationBuilders.entrySet()) {
ConfigurationBuilder builder = resolveConfiguration(entry.getKey(), combine);
entry.setValue(builder);
}
}
private ConfigurationBuilder resolveConfiguration(String name, Combine combine) {
ConfigurationBuilder builder = namedConfigurationBuilders.get(name);
if (builder == null) {
throw CONFIG.noConfiguration(name);
}
String parent = builder.configuration();
if (parent == null) {
// No parents, return as-is
return builder;
} else {
ConfigurationBuilder rebased = new ConfigurationBuilder();
rebased.read(resolveConfiguration(parent, combine).build(), combine);
rebased.read(builder.build(), combine);
return rebased;
}
}
}
| 6,186
| 32.808743
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/Namespace.java
|
package org.infinispan.configuration.parsing;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Namespace. An annotation which allows specifying the namespace recognized by an implementation of
* a {@link ConfigurationParser}. If you need to specify multiple namespaces, use the
* {@link Namespaces} annotation.
*
* @author Tristan Tarrant
* @since 6.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Namespaces.class)
public @interface Namespace {
/**
* The URI of the namespace. Defaults to the empty string.
*/
String uri() default "";
/**
* The root element of this namespace.
*/
String root();
/**
* The first version of the schema where this is supported. Defaults to 7.0. Only considered if {@link #uri()} ends
* with a wildcard
*/
String since() default "7.0";
/**
* The last version of the schema where this is supported. Defaults to the current release. Only considered if {@link #uri()} ends
* with a wildcard
*/
String until() default "";
}
| 1,112
| 26.825
| 133
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/Namespaces.java
|
package org.infinispan.configuration.parsing;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Namespaces. An annotation which allows specifying multiple {@link Namespace}s recognized by an implementation
* of a {@link ConfigurationParser}
*
* @author Tristan Tarrant
* @since 5.3
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Namespaces {
Namespace[] value();
}
| 426
| 24.117647
| 112
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/parsing/NamespaceMappingParser.java
|
package org.infinispan.configuration.parsing;
import org.infinispan.commons.configuration.io.ConfigurationReader;
import org.infinispan.commons.configuration.io.ConfigurationReaderException;
/**
*
* NamespaceMappingParser. This interface defines methods exposed by a namespace-mapping-aware
* parser (such as {@link ParserRegistry})
*
* @author Tristan Tarrant
* @since 6.0
*/
public interface NamespaceMappingParser {
/**
* Recursively parses the current element of an XML stream using an appropriate
* {@link ConfigurationParser} depending on the element's namespace.
*
* @param reader the configuration stream reader
* @param holder a configuration holder
* @throws ConfigurationReaderException
*/
void parseElement(ConfigurationReader reader, ConfigurationBuilderHolder holder) throws ConfigurationReaderException;
/**
* Handle a namespaced attribute
* @param reader the configuration stream reader
* @param i the index of the attribute
* @param holder a configuration holder
* @throws ConfigurationReaderException
*/
void parseAttribute(ConfigurationReader reader, int i, ConfigurationBuilderHolder holder) throws ConfigurationReaderException;
}
| 1,226
| 34.057143
| 129
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/format/PropertyFormatter.java
|
package org.infinispan.configuration.format;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.global.GlobalConfiguration;
/**
* Extracts the configuration into flat key-value property structure by reflection.
*
* @author Michal Linhard (mlinhard@redhat.com)
* @since 6.0
*/
public final class PropertyFormatter {
private static Method plainToString = null;
static {
try {
plainToString = Object.class.getMethod("toString");
} catch (Exception e) {
// Ignore
}
}
private final String globalConfigPrefix;
private final String configPrefix;
/**
* Create a new PropertyFormatter instance.
*/
public PropertyFormatter() {
this("", "");
}
/**
* Create a new PropertyFormatter instance.
*
* @param globalConfigPrefix Prefix used for global configuration property keys.
* @param configPrefix Prefix used for cache configuration property keys.
*/
public PropertyFormatter(String globalConfigPrefix, String configPrefix) {
this.globalConfigPrefix = globalConfigPrefix;
this.configPrefix = configPrefix;
}
/**
* Get all public, non-static, non-deprecated methods with 0 arguments (except toString() and other unuuseful ones).
*/
private static List<Method> getConfigMethods(Class<?> clazz) {
Class<?> c = clazz;
List<Method> r = new ArrayList<>();
while (c != null && c != Object.class) {
for (Method m : c.getDeclaredMethods()) {
if (Modifier.isPublic(m.getModifiers())
&& !Modifier.isStatic(m.getModifiers())
&& m.getParameterCount() == 0
&& !m.isAnnotationPresent(Deprecated.class)
&& !"hashCode".equals(m.getName())
&& !"toString".equals(m.getName())
&& !"toProperties".equals(m.getName())) {
m.setAccessible(true);
r.add(m);
}
}
c = c.getSuperclass();
}
return r;
}
private static boolean hasPlainToString(Object obj) {
Class<?> cls = obj.getClass();
try {
if (cls.getMethod("toString") == plainToString) {
return true;
}
String plainToStringValue = cls.getName() + "@" + Integer.toHexString(System.identityHashCode(obj));
return plainToStringValue.equals(obj.toString());
} catch (Exception e) {
return false;
}
}
private static void reflect(Object obj, Properties p, String prefix) {
try {
if (obj == null) {
p.put(prefix, "null");
return;
}
Class<?> cls = obj.getClass();
if (cls.getName().startsWith("org.infinispan.config") && !cls.isEnum()) {
for (Method m : getConfigMethods(obj.getClass())) {
try {
String prefixDot = prefix == null || prefix.isEmpty() ? "" : prefix + ".";
reflect(m.invoke(obj), p, prefixDot + m.getName());
} catch (IllegalAccessException e) {
// ok
}
}
} else if (Collection.class.isAssignableFrom(cls)) {
Collection<?> collection = (Collection<?>) obj;
Iterator<?> iter = collection.iterator();
for (int i = 0; i < collection.size(); i++) {
reflect(iter.next(), p, prefix + "[" + i + "]");
}
} else if (cls.isArray()) {
Object[] a = (Object[]) obj;
for (int i = 0; i < a.length; i++) {
reflect(a[i], p, prefix + "[" + i + "]");
}
} else if (hasPlainToString(obj)) {
// we have a class that doesn't have a nice toString implementation
p.put(prefix, cls.getName());
} else {
// we have a single value
p.put(prefix, obj.toString());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Properties format(Configuration configuration) {
Properties properties = new Properties();
reflect(configuration, properties, configPrefix);
return properties;
}
public Properties format(GlobalConfiguration configuration) {
Properties properties = new Properties();
reflect(configuration, properties, globalConfigPrefix);
return properties;
}
}
| 4,647
| 31.964539
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/internal/package-info.java
|
/**
* A private configuration package.
* <p>
* It can be used when advanced or tuning configuration are needed and it shouldn't be exposed to the public.
*
* @api.private
* @since 9.0
*/
package org.infinispan.configuration.internal;
| 241
| 23.2
| 109
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/internal/PrivateGlobalConfigurationBuilder.java
|
package org.infinispan.configuration.internal;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
/**
* A {@link Builder} implementation of {@link PrivateGlobalConfiguration}.
*
* @author Pedro Ruivo
* @see PrivateGlobalConfiguration
* @since 9.0
*/
public class PrivateGlobalConfigurationBuilder implements Builder<PrivateGlobalConfiguration> {
private final AttributeSet attributes;
public PrivateGlobalConfigurationBuilder(GlobalConfigurationBuilder builder) {
this.attributes = PrivateGlobalConfiguration.attributeSet();
}
@Override
public AttributeSet attributes() {
return attributes;
}
public PrivateGlobalConfigurationBuilder serverMode(boolean serverMode) {
this.attributes.attribute(PrivateGlobalConfiguration.SERVER_MODE).set(serverMode);
return this;
}
@Override
public void validate() {
//nothing
}
@Override
public PrivateGlobalConfiguration create() {
return new PrivateGlobalConfiguration(attributes.protect());
}
@Override
public Builder<?> read(PrivateGlobalConfiguration template, Combine combine) {
this.attributes.read(template.attributes(), combine);
return this;
}
@Override
public String toString() {
return "PrivateGlobalConfigurationBuilder [attributes=" + attributes + ']';
}
}
| 1,530
| 27.351852
| 95
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/internal/PrivateGlobalConfiguration.java
|
package org.infinispan.configuration.internal;
import org.infinispan.commons.configuration.BuiltBy;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.configuration.serializing.SerializedWith;
/**
* An internal configuration.
* <p>
* This is an internal configuration to be used by Infinispan modules when some advanced or ergonomic configuration is
* needed.
*
* @author Pedro Ruivo
* @since 9.0
*/
@SerializedWith(PrivateGlobalConfigurationSerializer.class)
@BuiltBy(PrivateGlobalConfigurationBuilder.class)
public class PrivateGlobalConfiguration {
static final AttributeDefinition<Boolean> SERVER_MODE = AttributeDefinition.builder("server-mode", false).immutable().build();
private final AttributeSet attributes;
PrivateGlobalConfiguration(AttributeSet attributeSet) {
this.attributes = attributeSet.checkProtection();
}
static AttributeSet attributeSet() {
return new AttributeSet(PrivateGlobalConfiguration.class, SERVER_MODE);
}
public AttributeSet attributes() {
return attributes;
}
public boolean isServerMode() {
return attributes.attribute(SERVER_MODE).get();
}
@Override
public String toString() {
return "PrivateGlobalConfiguration [attributes=" + attributes + ']';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PrivateGlobalConfiguration that = (PrivateGlobalConfiguration) o;
return attributes.equals(that.attributes);
}
@Override
public int hashCode() {
return attributes.hashCode();
}
}
| 1,746
| 28.116667
| 129
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/configuration/internal/PrivateGlobalConfigurationSerializer.java
|
package org.infinispan.configuration.internal;
import org.infinispan.commons.configuration.io.ConfigurationWriter;
import org.infinispan.configuration.serializing.ConfigurationSerializer;
/**
* A {@link ConfigurationSerializer} implementation for {@link PrivateGlobalConfiguration}.
* <p>
* The {@link PrivateGlobalConfiguration} is only to be used internally so this implementation is a no-op.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class PrivateGlobalConfigurationSerializer implements ConfigurationSerializer<PrivateGlobalConfiguration> {
@Override
public void serialize(ConfigurationWriter writer, PrivateGlobalConfiguration configuration) {
//nothing to do! private configuration is not serialized.
}
}
| 740
| 36.05
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/package-info.java
|
/**
* Classes related to eviction.
*
* @api.public
*/
package org.infinispan.eviction;
| 92
| 10.625
| 32
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/EvictionStrategy.java
|
package org.infinispan.eviction;
/**
* Supported eviction strategies
*
* @author Manik Surtani
* @since 4.0
*/
public enum EvictionStrategy {
/**
* Eviction Strategy where nothing is done by the cache and the user is probably not going to use eviction manually
*/
NONE(false, false),
/**
* Strategy where the cache does nothing but the user is assumed to manually invoke evict method
*/
MANUAL(false, false),
/**
* Strategy where the cache will remove entries to make room for new ones while staying under the configured size
*/
REMOVE(false, true),
/**
* Strategy where the cache will block new entries from being written if they would exceed the configured size
*/
EXCEPTION(true, false),
;
private boolean exception;
private boolean removal;
EvictionStrategy(boolean exception, boolean removal) {
this.exception = exception;
this.removal = removal;
}
/**
* Whether or not the cache will do something due to the strategy
* @return
*/
public boolean isEnabled() {
return this != NONE && this != MANUAL;
}
/**
* The cache will throw exceptions to prevent memory growth
* @return
*/
public boolean isExceptionBased() {
return exception;
}
/**
* The cache will remove other entries to make room to limit memory growth
* @return
*/
public boolean isRemovalBased() {
return removal;
}
}
| 1,458
| 23.316667
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/EvictionManager.java
|
package org.infinispan.eviction;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import net.jcip.annotations.ThreadSafe;
/**
* Central component that deals with eviction of cache entries.
* <p />
* This manager only controls notifications of when entries are evicted.
* <p />
* @author Manik Surtani
* @since 4.0
*/
@ThreadSafe
@Scope(Scopes.NAMED_CACHE)
public interface EvictionManager<K, V> {
/**
* Handles notifications of evicted entries
* @param evicted The entries that were just evicted
* @return stage that when complete the notifications are complete
*/
default CompletionStage<Void> onEntryEviction(Map<K, Map.Entry<K, V>> evicted) {
return onEntryEviction(evicted, null);
}
/**
* Handles notifications of evicted entries based on if the command allow them
* @param evicted The entries that were just evicted
* @param command The command that generated the eviction if applicable
* @return stage that when complete the notifications are complete
*/
CompletionStage<Void> onEntryEviction(Map<K, Map.Entry<K, V>> evicted, FlagAffectedCommand command);
}
| 1,296
| 31.425
| 103
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/EvictionType.java
|
package org.infinispan.eviction;
import org.infinispan.configuration.cache.MemoryConfiguration;
/**
* Supported eviction type
*
* @author Tristan Tarrant
* @since 8.0
* @deprecated Since 11.0, {@link MemoryConfiguration#maxCount()} and
* {@link MemoryConfiguration#maxSize()} should be used to differentiate between
* the eviction thresholds.
*/
@Deprecated
public enum EvictionType {
COUNT,
MEMORY,
}
| 418
| 21.052632
| 80
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/impl/PassivationManagerImpl.java
|
package org.infinispan.eviction.impl;
import static org.infinispan.commons.util.Util.toStr;
import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.PRIVATE;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.IteratorMapper;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.impl.InternalDataContainer;
import org.infinispan.context.impl.ImmutableContext;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated;
import org.infinispan.persistence.manager.PassivationPersistenceManager;
import org.infinispan.persistence.manager.PersistenceManager;
import org.infinispan.persistence.manager.PersistenceManager.StoreChangeListener;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.persistence.spi.MarshallableEntryFactory;
import org.infinispan.persistence.spi.PersistenceException;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
public class PassivationManagerImpl extends AbstractPassivationManager {
private static final Log log = LogFactory.getLog(PassivationManagerImpl.class);
@Inject PersistenceManager persistenceManager;
@Inject CacheNotifier<Object, Object> notifier;
@Inject Configuration cfg;
@Inject InternalDataContainer<Object, Object> container;
@Inject TimeService timeService;
@Inject MarshallableEntryFactory<?, ?> marshalledEntryFactory;
@Inject DistributionManager distributionManager;
@Inject KeyPartitioner keyPartitioner;
PassivationPersistenceManager passivationPersistenceManager;
private volatile boolean skipOnStop = false;
boolean statsEnabled = false;
volatile boolean enabled = false;
private final AtomicLong passivations = new AtomicLong(0);
private final StoreChangeListener listener = pm -> updateEnabledStatus(pm.isEnabled(), pm.usingReadOnly());
@Start(priority = 12)
public void start() {
updateEnabledStatus(cfg.persistence().usingStores(), persistenceManager.isReadOnly());
persistenceManager.addStoreListener(listener);
}
@Stop
public void stop() {
persistenceManager.removeStoreListener(listener);
}
private void updateEnabledStatus(boolean usingStores, boolean readOnly) {
enabled = !readOnly && cfg.persistence().passivation() && usingStores;
if (enabled) {
passivationPersistenceManager = (PassivationPersistenceManager) persistenceManager;
statsEnabled = cfg.statistics().enabled();
}
}
@Override
public boolean isEnabled() {
return enabled;
}
private boolean isL1Key(Object key) {
return distributionManager != null && !distributionManager.getCacheTopology().isWriteOwner(key);
}
private CompletionStage<Void> doPassivate(Object key, InternalCacheEntry<?, ?> entry) {
if (log.isTraceEnabled()) log.tracef("Passivating entry %s", toStr(key));
MarshallableEntry<?, ?> marshalledEntry = marshalledEntryFactory.create((InternalCacheEntry) entry);
CompletionStage<Void> stage = passivationPersistenceManager.passivate(marshalledEntry, keyPartitioner.getSegment(key));
return stage.handle((v, t) -> {
if (t != null) {
CONTAINER.unableToPassivateEntry(key, t);
}
if (statsEnabled) {
passivations.getAndIncrement();
}
return null;
});
}
@Override
public CompletionStage<Void> passivateAsync(InternalCacheEntry<?, ?> entry) {
Object key;
if (enabled && entry != null && !isL1Key(key = entry.getKey())) {
if (notifier.hasListener(CacheEntryPassivated.class)) {
return notifier.notifyCacheEntryPassivated(key, entry.getValue(), true, ImmutableContext.INSTANCE, null)
.thenCompose(v -> doPassivate(key, entry))
.thenCompose(v -> notifier.notifyCacheEntryPassivated(key, null, false, ImmutableContext.INSTANCE, null));
} else {
return doPassivate(key, entry);
}
}
return CompletableFutures.completedNull();
}
@Override
public void passivateAll() throws PersistenceException {
CompletionStages.join(passivateAllAsync());
}
@Override
public CompletionStage<Void> passivateAllAsync() throws PersistenceException {
if (!enabled || skipOnStop)
return CompletableFutures.completedNull();
long start = timeService.time();
if (CONTAINER.isDebugEnabled()) {
CONTAINER.debug("Passivating all entries to disk");
}
int count = container.sizeIncludingExpired();
Iterable<MarshallableEntry<Object, Object>> iterable = () -> new IteratorMapper<>(container.iterator(), e -> marshalledEntryFactory.create((InternalCacheEntry) e));
return persistenceManager.writeEntries(iterable, PRIVATE)
.thenRun(() -> {
long durationMillis = timeService.timeDuration(start, TimeUnit.MILLISECONDS);
if (CONTAINER.isDebugEnabled()) {
CONTAINER.debugf("Passivated %d entries in %s", count, Util.prettyPrintTime(durationMillis));
}
});
}
@Override
public void skipPassivationOnStop(boolean skip) {
this.skipOnStop = skip;
}
@Override
public long getPassivations() {
return passivations.get();
}
@Override
public boolean getStatisticsEnabled() {
return statsEnabled;
}
@Override
public void setStatisticsEnabled(boolean enabled) {
statsEnabled = enabled;
}
@Override
public void resetStatistics() {
passivations.set(0L);
}
}
| 6,536
| 37.910714
| 170
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/impl/ActivationManagerStub.java
|
package org.infinispan.eviction.impl;
import java.util.concurrent.CompletionStage;
import org.infinispan.factories.annotations.SurvivesRestarts;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
@Scope(Scopes.NAMED_CACHE)
@SurvivesRestarts
public class ActivationManagerStub implements ActivationManager {
@Override
public CompletionStage<Void> activateAsync(Object key, int segment) {
return CompletableFutures.completedNull();
}
@Override
public long getPendingActivationCount() {
return 0;
}
@Override
public long getActivationCount() {
return 0;
}
}
| 770
| 23.870968
| 72
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/impl/EvictionManagerImpl.java
|
package org.infinispan.eviction.impl;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.context.impl.ImmutableContext;
import org.infinispan.eviction.EvictionManager;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.impl.CacheMgmtInterceptor;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.stats.impl.StatsCollector;
import net.jcip.annotations.ThreadSafe;
@Scope(Scopes.NAMED_CACHE)
@ThreadSafe
public class EvictionManagerImpl<K, V> implements EvictionManager<K, V> {
@Inject CacheNotifier<K, V> cacheNotifier;
@Inject ComponentRef<AsyncInterceptorChain> interceptorChain;
@Inject Configuration cfg;
@Inject StatsCollector simpleCacheStatsCollector;
private CacheMgmtInterceptor cacheMgmtInterceptor;
@Start
public void findCacheMgmtInterceptor() {
// Allow the interceptor chain to start later, otherwise we'd have a dependency cycle
cacheMgmtInterceptor = interceptorChain.wired().findInterceptorExtending(CacheMgmtInterceptor.class);
}
@Override
public CompletionStage<Void> onEntryEviction(Map<K, Map.Entry<K,V>> evicted, FlagAffectedCommand command) {
CompletionStage<Void> stage = cacheNotifier.notifyCacheEntriesEvicted(evicted.values(), ImmutableContext.INSTANCE, command);
if (cfg.statistics().enabled()) {
updateEvictionStatistics(evicted);
}
return stage;
}
private void updateEvictionStatistics(Map<K, Map.Entry<K, V>> evicted) {
if (cacheMgmtInterceptor != null) {
cacheMgmtInterceptor.addEvictions(evicted.size());
} else if (simpleCacheStatsCollector != null) {
simpleCacheStatsCollector.recordEvictions(evicted.size());
}
}
}
| 2,152
| 37.446429
| 130
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/impl/AbstractPassivationManager.java
|
package org.infinispan.eviction.impl;
import net.jcip.annotations.ThreadSafe;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.jmx.annotations.MBean;
import org.infinispan.jmx.annotations.ManagedAttribute;
import org.infinispan.jmx.annotations.ManagedOperation;
import org.infinispan.jmx.annotations.MeasurementType;
import org.infinispan.persistence.spi.PersistenceException;
/**
* A passivation manager
*
* @author Manik Surtani
* @version 4.1
*/
@ThreadSafe
@Scope(Scopes.NAMED_CACHE)
@MBean(objectName = "Passivation", description = "Component that handles passivating entries to a CacheStore on eviction.")
public abstract class AbstractPassivationManager implements PassivationManager {
/**
* Passivates all entries that are in memory. This method does not notify listeners of passivation.
* @throws PersistenceException
*/
@Stop(priority = 9)
@ManagedOperation(
description = "Passivate all entries to the CacheStore",
displayName = "Passivate all")
public abstract void passivateAll() throws PersistenceException;
@ManagedAttribute(
description = "Number of passivation events",
displayName = "Number of cache passivations",
measurementType = MeasurementType.TRENDSUP
)
public abstract long getPassivations();
@ManagedOperation(
description = "Resets statistics gathered by this component",
displayName = "Reset statistics")
public abstract void resetStatistics();
}
| 1,602
| 34.622222
| 123
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/impl/PassivationManager.java
|
package org.infinispan.eviction.impl;
import java.util.concurrent.CompletionStage;
import net.jcip.annotations.ThreadSafe;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.jmx.JmxStatisticsExposer;
/**
* A passivation manager
*
* @author Manik Surtani
* @version 4.1
*/
@ThreadSafe
@Scope(Scopes.NAMED_CACHE)
public interface PassivationManager extends JmxStatisticsExposer {
boolean isEnabled();
/**
* Passivates the entry in a non blocking fashion.
* @param entry entry to passivate
* @return CompletionStage that when complete will have passivated the entry and notified listeners
*/
CompletionStage<Void> passivateAsync(InternalCacheEntry<?, ?> entry);
/**
* Start passivating all entries that are in memory.
*
* This method does not notify listeners of passivation.
*
* @since 10.1
*/
CompletionStage<Void> passivateAllAsync();
/**
* Skips the passivation when the cache is stopped.
*/
void skipPassivationOnStop(boolean skip);
long getPassivations();
void resetStatistics();
}
| 1,198
| 23.979167
| 102
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/impl/ActivationManagerImpl.java
|
package org.infinispan.eviction.impl;
import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.PRIVATE;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.LongAdder;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.jmx.annotations.MBean;
import org.infinispan.jmx.annotations.ManagedAttribute;
import org.infinispan.jmx.annotations.ManagedOperation;
import org.infinispan.jmx.annotations.MeasurementType;
import org.infinispan.persistence.manager.PersistenceManager;
import org.infinispan.persistence.manager.PersistenceManager.StoreChangeListener;
import org.infinispan.persistence.manager.PersistenceStatus;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Concrete implementation of activation logic manager.
*
* @author Galder Zamarreño
* @since 5.2
*/
@MBean(objectName = "Activation",
description = "Component that handles activating entries that have been passivated to a CacheStore by loading them into memory.")
@Scope(Scopes.NAMED_CACHE)
public class ActivationManagerImpl implements ActivationManager, StoreChangeListener {
private static final Log log = LogFactory.getLog(ActivationManagerImpl.class);
private final LongAdder activations = new LongAdder();
private final LongAdder pendingActivations = new LongAdder();
@Inject PersistenceManager persistenceManager;
@Inject Configuration cfg;
@Inject DistributionManager distributionManager;
@Inject KeyPartitioner keyPartitioner;
private volatile boolean passivation;
private boolean statisticsEnabled = false;
@Start(priority = 11) // After the cache loader manager, before the passivation manager
public void start() {
statisticsEnabled = cfg.statistics().enabled();
passivation = cfg.persistence().usingStores() && cfg.persistence().passivation();
persistenceManager.addStoreListener(this);
}
@Stop
public void stop() {
persistenceManager.removeStoreListener(this);
}
@Override
public void storeChanged(PersistenceStatus persistenceStatus) {
synchronized (this) {
passivation = passivation && persistenceStatus.isEnabled();
}
}
@Override
public CompletionStage<Void> activateAsync(Object key, int segment) {
if (!passivation) {
return CompletableFutures.completedNull();
}
if (log.isTraceEnabled()) {
log.tracef("Activating entry for key %s", key);
}
if (statisticsEnabled) {
pendingActivations.increment();
}
CompletionStage<Boolean> stage = persistenceManager.deleteFromAllStores(key, segment, PRIVATE);
return stage.handle((removed, throwable) -> {
if (statisticsEnabled) {
pendingActivations.decrement();
}
if (throwable != null) {
CONTAINER.unableToRemoveEntryAfterActivation(key, throwable);
} else if (statisticsEnabled && removed == Boolean.TRUE) {
activations.increment();
}
return null;
});
}
@Override
public long getActivationCount() {
return activations.sum();
}
@ManagedAttribute(
description = "Number of activation events",
displayName = "Number of cache entries activated",
measurementType = MeasurementType.TRENDSUP
)
public String getActivations() {
if (!statisticsEnabled)
return "N/A";
return String.valueOf(activations.sum());
}
@ManagedOperation(
description = "Resets statistics gathered by this component",
displayName = "Reset statistics"
)
public void resetStatistics() {
activations.reset();
}
@ManagedAttribute(description = "Enables or disables the gathering of statistics by this component", displayName = "Statistics enabled", writable = true)
public boolean getStatisticsEnabled() {
return statisticsEnabled;
}
public void setStatisticsEnabled(boolean statisticsEnabled) {
this.statisticsEnabled = statisticsEnabled;
}
@Override
public long getPendingActivationCount() {
return pendingActivations.sum();
}
}
| 4,674
| 33.375
| 156
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/impl/ActivationManager.java
|
package org.infinispan.eviction.impl;
import java.util.concurrent.CompletionStage;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* Controls activation of cache entries that have been passivated.
*
* @author Galder Zamarreño
* @since 5.2
*/
@Scope(Scopes.NAMED_CACHE)
public interface ActivationManager {
/**
* Activates an entry, effectively removing it from the underlying persistence store. Note that the removal may
* be done asynchronously and when the returned Stage is complete the removal is also completed.
* @param key key to activate
* @param segment segment the key maps to
* @return stage that when complete the entry has been activated
*/
CompletionStage<Void> activateAsync(Object key, int segment);
long getPendingActivationCount();
/**
* Get number of activations executed.
*
* @return A long representing the number of activations
*/
long getActivationCount();
}
| 998
| 26.75
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/eviction/impl/PassivationManagerStub.java
|
package org.infinispan.eviction.impl;
import java.util.concurrent.CompletionStage;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.factories.annotations.SurvivesRestarts;
import org.infinispan.persistence.spi.PersistenceException;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
@SurvivesRestarts
public class PassivationManagerStub extends AbstractPassivationManager {
@Override
public boolean isEnabled() {
return false;
}
@Override
public CompletionStage<Void> passivateAsync(InternalCacheEntry entry) {
return CompletableFutures.completedNull();
}
@Override
public void passivateAll() throws PersistenceException {
}
@Override
public CompletionStage<Void> passivateAllAsync() {
return CompletableFutures.completedNull();
}
@Override
public void skipPassivationOnStop(boolean skip) {
/*no-op*/
}
@Override
public long getPassivations() {
return 0;
}
@Override
public void resetStatistics() {
}
@Override
public boolean getStatisticsEnabled() {
return false;
}
@Override
public void setStatisticsEnabled(boolean enabled) {
throw new UnsupportedOperationException();
}
}
| 1,315
| 21.689655
| 74
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/expiration/package-info.java
|
/**
* Cache expiration.
*
* @api.public
*/
package org.infinispan.expiration;
| 83
| 9.5
| 34
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/expiration/TouchMode.java
|
package org.infinispan.expiration;
/**
* Control how the timestamp of read keys are updated on all the key owners in a cluster.
*
* @since 13.0
* @author Dan Berindei
*/
public enum TouchMode {
/**
* Delay read operations until the other owners confirm updating the timestamp of the entry
*/
SYNC,
/**
* Send touch commands to other owners, but do not wait for their confirmation.
*
* This allows read operations to return the value of a key even if another node has started expiring it.
* When that happens, the read won't extend the lifespan of the key.
*/
ASYNC
}
| 613
| 26.909091
| 108
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/expiration/ExpirationManager.java
|
package org.infinispan.expiration;
import org.infinispan.configuration.cache.ExpirationConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import net.jcip.annotations.ThreadSafe;
/**
* Central component that deals with expiration of cache entries.
* <p />
* Typically, {@link #processExpiration()} is called periodically by the expiration thread (which can be configured using
* {@link ExpirationConfigurationBuilder#wakeUpInterval(long)} and {@link GlobalConfigurationBuilder#expirationThreadPool()}).
* <p />
* If the expiration thread is disabled - by setting {@link ExpirationConfigurationBuilder#wakeUpInterval(long)} to <tt>0</tt> -
* then this method could be called directly, perhaps by any other maintenance thread that runs periodically in the application.
* <p />
* @author William Burns
* @since 7.2
*/
@ThreadSafe
public interface ExpirationManager<K, V> {
/**
* Processes the expiration event queue.
*/
void processExpiration();
/**
* @return true if expiration reaper thread is enabled, false otherwise
*/
boolean isEnabled();
}
| 1,129
| 33.242424
| 128
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/expiration/impl/InternalExpirationManager.java
|
package org.infinispan.expiration.impl;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.expiration.ExpirationManager;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.persistence.spi.MarshallableEntry;
/**
* Interface describing the internal operations for the the ExpirationManager.
* @author wburns
* @since 9.3
*/
@Scope(Scopes.NAMED_CACHE)
public interface InternalExpirationManager<K, V> extends ExpirationManager<K, V> {
/**
* This should be invoked passing in an entry that is now expired. This method may attempt to lock this key to
* preserve atomicity. This method should be invoked when an entry was read via get but found to be expired.
* <p>
* This method returns <b>true</b> if the entry was removed due to expiration or <b>false</b> if the entry was
* not removed due to expiration
* <p>
* If <b>hasLock</b> is true, this method assumes that the caller has the lock for the key and it must allow the
* expiration to occur, ie. returned CompletableFuture has completed, before the lock is released. Failure to do
* so may cause inconsistency in data.
* @param entry the entry that has expired
* @param currentTime the current time when it expired
* @param isWrite if the expiration was found during a write operation
* @return if this entry actually expired or not
*/
CompletableFuture<Boolean> entryExpiredInMemory(InternalCacheEntry<K, V> entry, long currentTime, boolean isWrite);
/**
* This is to be invoked when a store entry expires. This method may attempt to lock this key to preserve atomicity.
* <p>
* Note this method doesn't currently take a {@link InternalCacheEntry} and this is due to a limitation in the
* cache store API. This may cause some values to be removed if they were updated at the same time.
* @param key the key of the expired entry
* This method will be renamed to handleInStoreExpiration when the method can be removed from {@link ExpirationManager}
*/
CompletionStage<Void> handleInStoreExpirationInternal(K key);
/**
* This is to be invoked when a store entry expires and the value and/or metadata is available to be used.
*
* @param marshalledEntry the entry that can be unmarshalled as needed
* This method will be renamed to handleInStoreExpiration when the method can be removed from {@link ExpirationManager}
*/
CompletionStage<Void> handleInStoreExpirationInternal(MarshallableEntry<K, V> marshalledEntry);
/**
* Handles processing for an entry that may be expired. This will remove the entry if it is expired, otherwise may
* touch if it uses max idle.
* @param entry entry that may be expired
* @param segment the segment of the entry
* @param isWrite whether the command that saw the expired value was a write or not
* @return a stage that will complete with {@code true} if the entry was expired and {@code false} otherwise
*/
CompletionStage<Boolean> handlePossibleExpiration(InternalCacheEntry<K, V> entry, int segment, boolean isWrite);
/**
* Adds an {@link ExpirationConsumer} to be invoked when an entry is expired.
* <p>
* It exposes the {@link PrivateMetadata}
*
* @param consumer The instance to invoke.
*/
void addInternalListener(ExpirationConsumer<K, V> consumer);
/**
* Removes a previous registered {@link ExpirationConsumer}.
*
* @param listener The instance to remove.
*/
void removeInternalListener(Object listener);
interface ExpirationConsumer<T, U> {
/**
* Invoked when an entry is expired.
*
* @param key The key.
* @param value The value.
* @param metadata The {@link Metadata}.
* @param privateMetadata The {@link PrivateMetadata}.
*/
void expired(T key, U value, Metadata metadata, PrivateMetadata privateMetadata);
}
}
| 4,205
| 43.744681
| 122
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/expiration/impl/ClusterExpirationManager.java
|
package org.infinispan.expiration.impl;
import static org.infinispan.commons.util.Util.toStr;
import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.util.IntSet;
import org.infinispan.commons.util.IntSets;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.ClusteringConfiguration;
import org.infinispan.container.entries.ExpiryHelper;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.context.Flag;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.metadata.Metadata;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.remoting.RemoteException;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.statetransfer.OutdatedTopologyException;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import net.jcip.annotations.ThreadSafe;
/**
* Allows for cluster based expirations to occur. This provides guarantees that when an entry is expired that it will
* expire that entry across the entire cluster at once. This requires obtaining the lock for said entry before
* expiration is performed. Since expiration can occur without holding onto the lock it is possible for an expiration
* to occur immediately after a value has been updated. This can cause a premature expiration to occur. Attempts
* are made to prevent this by using the expired entry's value and lifespan to limit this expiration so it only happens
* in a smaller amount of cases.
* <p>
* Cache stores however do not supply the value or metadata information which means if an entry is purged from the cache
* store that it will forcibly remove the value even if a concurrent write updated it just before. This will be
* addressed by future SPI changes to the cache store.
* @param <K>
* @param <V>
*/
@Scope(Scopes.NAMED_CACHE)
@ThreadSafe
public class ClusterExpirationManager<K, V> extends ExpirationManagerImpl<K, V> {
private static final Log log = LogFactory.getLog(ClusterExpirationManager.class);
/**
* Defines the maximum number of allowed concurrent expirations. Any expirations over this must wait until
* another has completed before processing
*/
private static final int MAX_CONCURRENT_EXPIRATIONS = 100;
@Inject protected RpcManager rpcManager;
@Inject protected DistributionManager distributionManager;
private Address localAddress;
private long timeout;
@Override
public void start() {
super.start();
this.localAddress = cache.getCacheManager().getAddress();
this.timeout = configuration.clustering().remoteTimeout();
configuration.clustering()
.attributes().attribute(ClusteringConfiguration.REMOTE_TIMEOUT)
.addListener((a, ignored) -> {
timeout = a.get();
});
}
@Override
public void processExpiration() {
if (!Thread.currentThread().isInterrupted()) {
LocalizedCacheTopology topology;
// Purge all contents until we know we did so with a stable topology
do {
topology = distributionManager.getCacheTopology();
} while (purgeInMemoryContents(topology));
}
if (!Thread.currentThread().isInterrupted()) {
CompletionStages.join(persistenceManager.purgeExpired());
}
}
/**
* Purges in memory contents removing any expired entries.
* @return true if there was a topology change
*/
private boolean purgeInMemoryContents(LocalizedCacheTopology topology) {
long start = 0;
int removedEntries = 0;
AtomicInteger errors = new AtomicInteger();
try {
if (log.isTraceEnabled()) {
log.tracef("Purging data container on cache %s for topology %d", cacheName, topology.getTopologyId());
start = timeService.time();
}
// We limit how many non blocking expiration removals performed concurrently
// The addition to the queue shouldn't ever block but rather pollForCompletion when we are waiting for
// prior tasks to complete
BlockingQueue<CompletableFuture<?>> expirationPermits = new ArrayBlockingQueue<>(MAX_CONCURRENT_EXPIRATIONS);
long currentTimeMillis = timeService.wallClockTime();
IntSet segments;
if (topology.getReadConsistentHash().getMembers().contains(localAddress)) {
segments = IntSets.from(topology.getReadConsistentHash().getPrimarySegmentsForOwner(localAddress));
} else {
segments = IntSets.immutableEmptySet();
}
for (Iterator<InternalCacheEntry<K, V>> purgeCandidates = dataContainer.running().iteratorIncludingExpired(segments);
purgeCandidates.hasNext();) {
InternalCacheEntry<K, V> ice = purgeCandidates.next();
if (ice.canExpire()) {
// Have to synchronize on the entry to make sure we see the value and metadata at the same time
boolean expiredMortal;
boolean expiredTransient;
V value;
long lifespan;
long maxIdle;
synchronized (ice) {
value = ice.getValue();
lifespan = ice.getLifespan();
maxIdle = ice.getMaxIdle();
expiredMortal = ExpiryHelper.isExpiredMortal(lifespan, ice.getCreated(), currentTimeMillis);
expiredTransient = ExpiryHelper.isExpiredTransient(maxIdle, ice.getLastUsed(), currentTimeMillis);
}
if (expiredMortal || expiredTransient) {
// Any expirations over the max must check for another to finish before it can proceed
if (++removedEntries > MAX_CONCURRENT_EXPIRATIONS && !pollForCompletion(expirationPermits, start, removedEntries, errors)) {
return false;
}
CompletableFuture<?> stage;
// If the entry is expired both wrt lifespan and wrt maxIdle, we perform lifespan expiration as it is cheaper
if (expiredMortal) {
stage = handleLifespanExpireEntry(ice.getKey(), value, lifespan, false);
} else {
stage = handleMaxIdleExpireEntry(ice, false, currentTimeMillis);
}
stage.whenComplete((obj, t) -> addStageToPermits(expirationPermits, stage));
}
}
// Short circuit if topology has changed
if (distributionManager.getCacheTopology() != topology) {
printResults("Purging data container on cache %s stopped due to topology change. Total time was: %s and removed %d entries with %d errors", start, removedEntries, errors);
return true;
}
}
// We wait for any pending expiration to complete before returning
int expirationsLeft = Math.min(removedEntries, MAX_CONCURRENT_EXPIRATIONS);
for (int i = 0; i < expirationsLeft; ++i) {
if (!pollForCompletion(expirationPermits, start, removedEntries, errors)) {
return false;
}
}
printResults("Purging data container on cache %s completed in %s and removed %d entries with %d errors", start, removedEntries, errors);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
printResults("Purging data container on cache %s was interrupted. Total time was: %s and removed %d entries with %d errors", start, removedEntries, errors);
} catch (Throwable t) {
log.exceptionPurgingDataContainer(t);
}
return false;
}
/**
* This is a separate method to document the fact that this is invoked in a separate thread and also for code
* augmentation to find this method if needed
* <p>
* This method should never block as the queue should always have room by design
* @param expirationPermits the permits blocking queue to add to
* @param future the future to add to it.
*/
void addStageToPermits(BlockingQueue<CompletableFuture<?>> expirationPermits, CompletableFuture<?> future) {
boolean inserted = expirationPermits.offer(future);
assert inserted;
}
private void printResults(String message, long start, int removedEntries, AtomicInteger errors) {
if (log.isTraceEnabled()) {
log.tracef(message, cacheName, Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS)), removedEntries, errors.get());
}
}
/**
* Polls for an expiration to complete, returning whether an expiration completed in the time allotted. If an
* expiration has completed it will also verify it is had errored and update the count and log the message.
* @param queue the queue to poll from to find a completed expiration
* @param start the start time of the processing
* @param removedEntries the current count of expired entries
* @param errors value to increment when an error occurs
* @return true if an expiration completed
* @throws InterruptedException if the polling is interrupted
*/
private boolean pollForCompletion(BlockingQueue<CompletableFuture<?>> queue, long start, int removedEntries,
AtomicInteger errors) throws InterruptedException, TimeoutException {
CompletableFuture<?> future;
if ((future = queue.poll(timeout * 3, TimeUnit.MILLISECONDS)) != null) {
try {
// This shouldn't block
future.get(100, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
Throwable ce = e.getCause();
while (ce instanceof RemoteException) {
ce = ce.getCause();
}
if (ce instanceof org.infinispan.util.concurrent.TimeoutException) {
// Ignoring a TimeoutException as it could just be the entry was being updated concurrently
log.tracef(e, "Encountered timeout exception, assuming it was due to a concurrent write. Entry will" +
" be attempted to be removed on the next purge if still expired.");
} else {
errors.incrementAndGet();
log.exceptionPurgingDataContainer(e.getCause());
}
}
return true;
}
printResults("Purging data container on cache %s stopped due to waiting for prior removal (could be a bug or misconfiguration). Total time was: %s and removed %d entries", start, removedEntries, errors);
return false;
}
// Skip locking is required in case if the entry was found expired due to a write, which would already
// have the lock and remove lifespan expired is fired in a different thread with a different context. Otherwise the
// expiration may occur in the wrong order and events may also be raised in the incorrect order. We assume the caller
// holds the lock until this CompletableFuture completes. Without lock skipping this would deadlock.
CompletableFuture<Boolean> handleLifespanExpireEntry(K key, V value, long lifespan, boolean isWrite) {
return handleEitherExpiration(key, value, false, lifespan, isWrite);
}
CompletableFuture<Boolean> removeLifespan(AdvancedCache<K, V> cacheToUse, K key, V value, long lifespan) {
return cacheToUse.removeLifespanExpired(key, value, lifespan);
}
CompletableFuture<Boolean> handleMaxIdleExpireEntry(InternalCacheEntry<K, V> entry, boolean isWrite, long currentTime) {
return handleEitherExpiration(entry.getKey(), entry.getValue(), true, entry.getMaxIdle(), isWrite)
.thenCompose(expired -> {
if (!expired) {
if (log.isTraceEnabled()) {
log.tracef("Entry was not actually expired via max idle - touching on all nodes");
}
// TODO: what do we do if another node couldn't touch the value?
return checkExpiredMaxIdle(entry, keyPartitioner.getSegment(entry.getKey()), currentTime)
.thenApply(ignore -> Boolean.FALSE);
}
return CompletableFutures.completedTrue();
});
}
CompletableFuture<Boolean> removeMaxIdle(AdvancedCache<K, V> cacheToUse, K key, V value) {
return cacheToUse.removeMaxIdleExpired(key, value);
}
private CompletableFuture<Boolean> handleEitherExpiration(K key, V value, boolean maxIdle, long time, boolean isWrite) {
CompletableFuture<Boolean> completableFuture = new CompletableFuture<>();
CompletableFuture<Boolean> previousFuture = expiring.putIfAbsent(key, completableFuture);
if (previousFuture == null) {
if (log.isTraceEnabled()) {
log.tracef("Submitting expiration removal for key: %s which is maxIdle: %s of: %s", toStr(key), maxIdle, time);
}
try {
AdvancedCache<K, V> cacheToUse = cacheToUse(isWrite);
CompletableFuture<Boolean> future;
if (maxIdle) {
future = removeMaxIdle(cacheToUse, key, value);
} else {
future = removeLifespan(cacheToUse, key, value, time);
}
return future.whenComplete((b, t) -> {
// We have to remove the entry from the map before setting the exception status - otherwise retry for
// a write at the same time could get stuck in a recursive loop
expiring.remove(key);
if (t != null) {
completableFuture.completeExceptionally(t);
} else {
completableFuture.complete(b);
}
});
} catch (Throwable t) {
// We have to remove the entry from the map before setting the exception status - otherwise retry for
// a write at the same time could get stuck in a recursive loop
expiring.remove(key);
completableFuture.completeExceptionally(t);
throw t;
}
}
if (log.isTraceEnabled()) {
log.tracef("There is a pending expiration removal for key %s, waiting until it completes.", key);
}
// This means there was another thread that found it had expired via max idle or we have optimistic tx
return previousFuture;
}
Throwable getMostNestedSuppressedThrowable(Throwable t) {
Throwable nested = getNestedThrowable(t);
Throwable[] suppressedNested = nested.getSuppressed();
if (suppressedNested.length > 0) {
nested = getNestedThrowable(suppressedNested[0]);
}
return nested;
}
Throwable getNestedThrowable(Throwable t) {
Throwable cause;
while ((cause = t.getCause()) != null) {
t = cause;
}
return t;
}
AdvancedCache<K, V> cacheToUse(boolean isWrite) {
return isWrite ? cache.withFlags(Flag.SKIP_LOCKING) : cache.withFlags(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT);
}
@Override
public CompletableFuture<Boolean> entryExpiredInMemory(InternalCacheEntry<K, V> entry, long currentTime,
boolean isWrite) {
// We need to synchronize on the entry since {@link InternalCacheEntry} locks the entry when doing an update
// so we can see both the new value and the metadata
boolean expiredMortal;
V value;
long lifespan;
synchronized (entry) {
value = entry.getValue();
lifespan = entry.getLifespan();
expiredMortal = ExpiryHelper.isExpiredMortal(lifespan, entry.getCreated(), currentTime);
}
CompletableFuture<Boolean> future;
if (expiredMortal) {
future = handleLifespanExpireEntry(entry.getKey(), value, lifespan, isWrite);
// We don't want to block the user while the remove expired is happening for lifespan on a read
if (!waitOnLifespanExpiration(isWrite)) {
return CompletableFutures.completedTrue();
}
} else {
// This means it expired transiently - this will block user until we confirm the entry is okay
future = handleMaxIdleExpireEntry(entry, isWrite, currentTime);
}
return future.handle((expired, t) -> {
if (t != null) {
// With optimistic transaction the TimeoutException is nested as the following:
// CompletionException
// -> caused by RollbackException
// -> suppressing XAException
// -> caused by RemoteException
// -> caused by TimeoutException
// In Pessimistic or Non tx it is just a CompletionException wrapping a TimeoutException
Throwable cause = getMostNestedSuppressedThrowable(t);
// Note this exception is from a prior registered stage, not our own. If the prior one got a TimeoutException
// we try to reregister our write to do a remove expired call. This can happen if a read
// spawned remove expired times out as it has a 0 lock acquisition timeout. We don't want to propagate
// the TimeoutException to the caller of the write command as it is unrelated.
// Note that the remove expired command is never "retried" itself.
if (cause instanceof org.infinispan.util.concurrent.TimeoutException) {
if (log.isTraceEnabled()) {
log.tracef("Encountered timeout exception in remove expired invocation - need to retry!");
}
// Have to try the command ourselves as the prior one timed out (this could be valid if a read based
// remove expired couldn't acquire the try lock
return entryExpiredInMemory(entry, currentTime, isWrite);
} else {
if (log.isTraceEnabled()) {
log.tracef(t, "Encountered exception in remove expired invocation - propagating!");
}
return CompletableFuture.<Boolean>failedFuture(cause);
}
} else {
return expired == Boolean.TRUE ? CompletableFutures.completedTrue() : CompletableFutures.completedFalse();
}
}).thenCompose(Function.identity());
}
// Designed to be overridden as needed
boolean waitOnLifespanExpiration(boolean isWrite) {
// We always have to wait for the prior expiration to complete if we are holding the lock. Otherwise we can have
// multiple invocations running at the same time.
return isWrite;
}
@Override
public CompletionStage<Void> handleInStoreExpirationInternal(K key) {
return handleInStoreExpirationInternal(key, null);
}
@Override
public CompletionStage<Void> handleInStoreExpirationInternal(MarshallableEntry<K, V> marshalledEntry) {
return handleInStoreExpirationInternal(marshalledEntry.getKey(), marshalledEntry);
}
private CompletionStage<Void> handleInStoreExpirationInternal(K key, MarshallableEntry<K, V> marshallableEntry) {
CompletableFuture<Boolean> completableFuture = new CompletableFuture<>();
CompletableFuture<Boolean> previousFuture = expiring.putIfAbsent(key, completableFuture);
if (previousFuture == null) {
AdvancedCache<K, V> cacheToUse = cache.withFlags(Flag.SKIP_SHARED_CACHE_STORE, Flag.ZERO_LOCK_ACQUISITION_TIMEOUT);
CompletionStage<Boolean> resultStage;
if (marshallableEntry != null) {
Metadata metadata = marshallableEntry.getMetadata();
resultStage = cacheToUse.removeLifespanExpired(key, marshallableEntry.getValue(),
metadata == null || metadata.lifespan() == -1 ? null : metadata.lifespan());
} else {
// Unfortunately stores don't pull the entry so we can't tell exactly why it expired and thus we have to remove
// the entire value. Unfortunately this could cause a concurrent write to be undone
resultStage = cacheToUse.removeLifespanExpired(key, null, null);
}
return resultStage.handle((b, t) -> {
expiring.remove(key);
if (t != null) {
completableFuture.completeExceptionally(t);
} else {
completableFuture.complete(b);
}
return null;
});
}
return CompletionStages.ignoreValue(previousFuture);
}
@Override
protected CompletionStage<Boolean> checkExpiredMaxIdle(InternalCacheEntry<?, ?> ice, int segment, long currentTime) {
CompletionStage<Boolean> stage = attemptTouchAndReturnIfExpired(ice, segment, currentTime);
if (CompletionStages.isCompletedSuccessfully(stage)) {
return CompletableFutures.booleanStage(CompletionStages.join(stage));
}
return CompletionStages.handleAndCompose(stage, (expired, t) -> {
if (t != null) {
Throwable innerT = CompletableFutures.extractException(t);
if (innerT instanceof OutdatedTopologyException) {
if (log.isTraceEnabled()) {
log.tracef("Touch received OutdatedTopologyException, retrying");
}
return attemptTouchAndReturnIfExpired(ice, segment, currentTime);
}
return CompletableFuture.failedFuture(t);
}
return CompletableFutures.booleanStage(expired);
});
}
private CompletionStage<Boolean> attemptTouchAndReturnIfExpired(InternalCacheEntry<?, ?> ice, int segment, long currentTime) {
return cache.touch(ice.getKey(), segment, true)
.thenApply(touched -> {
if (touched) {
// The ICE can be a copy in cases such as off-heap - we need to update its time that is reported to the user
ice.touch(currentTime);
}
return !touched;
});
}
}
| 22,712
| 47.325532
| 209
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/expiration/impl/TouchCommand.java
|
package org.infinispan.expiration.impl;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.read.AbstractDataCommand;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
/**
* This command updates a cache entry's last access timestamp. If eviction is enabled, it will also update the recency information
* <p>
* This command returns a Boolean that is whether this command was able to touch the value or not.
*/
public class TouchCommand extends AbstractDataCommand {
public static final byte COMMAND_ID = 66;
private boolean touchEvenIfExpired;
public TouchCommand() { }
public TouchCommand(Object key, int segment, long flagBitSet, boolean touchEvenIfExpired) {
super(key, segment, flagBitSet);
this.touchEvenIfExpired = touchEvenIfExpired;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return true;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeObject(key);
UnsignedNumeric.writeUnsignedInt(output, segment);
output.writeLong(FlagBitSets.copyWithoutRemotableFlags(getFlagsBitSet()));
output.writeBoolean(touchEvenIfExpired);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
key = input.readObject();
segment = UnsignedNumeric.readUnsignedInt(input);
setFlagsBitSet(input.readLong());
touchEvenIfExpired = input.readBoolean();
}
public boolean isTouchEvenIfExpired() {
return touchEvenIfExpired;
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitTouchCommand(ctx, this);
}
@Override
public LoadType loadType() {
return LoadType.DONT_LOAD;
}
}
| 2,050
| 27.887324
| 130
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/expiration/impl/TxClusterExpirationManager.java
|
package org.infinispan.expiration.impl;
import org.infinispan.AdvancedCache;
import org.infinispan.context.Flag;
import org.infinispan.transaction.LockingMode;
import net.jcip.annotations.ThreadSafe;
@ThreadSafe
public class TxClusterExpirationManager<K, V> extends ClusterExpirationManager<K, V> {
private boolean optimisticTransaction;
@Override
public void start() {
super.start();
optimisticTransaction = configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC;
}
@Override
boolean waitOnLifespanExpiration(boolean isWrite) {
// We always have to wait when using optimistic transactions when an entry was found to be expired.
// An example is a user calling get then put if the value was null.
// This can cause an expiration event to be fired concurrently with the put.
// In an optimistic transaction this can cause an issue as the put may get a write skew exception.
// By waiting we prevent this case which can be confusing getting a write skew with a single requestor.
return isWrite || optimisticTransaction;
}
@Override
AdvancedCache<K, V> cacheToUse(boolean isWrite) {
// For non writes we don't have any lock wait time. This is to prevent deadlocks with a concurrent write and
// also so that with concurrent gets, only one will win.
// Pessimistic caches will already hold the lock for the read value and thus we have to skip locking
// Optimistic will not hold the lock at this point and thus we always have to lock the entry
return isWrite ? (optimisticTransaction ? cache : cache.withFlags(Flag.SKIP_LOCKING)) :
cache.withFlags(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT);
}
}
| 1,726
| 41.121951
| 114
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/expiration/impl/ExpirationManagerImpl.java
|
package org.infinispan.expiration.impl;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.infinispan.AdvancedCache;
import org.infinispan.cache.impl.AbstractDelegatingCache;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.Util;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.container.impl.InternalDataContainer;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.annotations.ComponentName;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.metadata.Metadata;
import org.infinispan.metadata.impl.PrivateMetadata;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.persistence.manager.PersistenceManager;
import org.infinispan.persistence.spi.MarshallableEntry;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import net.jcip.annotations.ThreadSafe;
@ThreadSafe
@Scope(Scopes.NAMED_CACHE)
public class ExpirationManagerImpl<K, V> implements InternalExpirationManager<K, V> {
private static final Log log = LogFactory.getLog(ExpirationManagerImpl.class);
@Inject @ComponentName(KnownComponentNames.EXPIRATION_SCHEDULED_EXECUTOR)
protected ScheduledExecutorService executor;
@Inject protected Configuration configuration;
@Inject protected PersistenceManager persistenceManager;
@Inject protected ComponentRef<InternalDataContainer<K, V>> dataContainer;
@Inject protected CacheNotifier<K, V> cacheNotifier;
@Inject protected TimeService timeService;
@Inject protected KeyPartitioner keyPartitioner;
@Inject protected ComponentRef<AdvancedCache<K, V>> cacheRef;
@Inject BlockingManager blockingManager;
protected boolean enabled;
protected String cacheName;
protected AdvancedCache<K, V> cache;
/**
* This map is used for performance reasons. Essentially when an expiration event should not be raised this
* map should be populated first. The main examples are if an expiration is about to occur for that key or the
* key will be removed or updated. In the latter case we don't want to send an expiration event and then a remove
* event when we could do just the removal.
*/
protected ConcurrentMap<K, CompletableFuture<Boolean>> expiring = new ConcurrentHashMap<>();
protected ScheduledFuture<?> expirationTask;
private final List<ExpirationConsumer<K, V>> listeners = new CopyOnWriteArrayList<>();
@Start(priority = 55)
// make sure this starts after the PersistenceManager
public void start() {
// first check if eviction is enabled!
enabled = configuration.expiration().reaperEnabled();
if (enabled) {
// Set up the eviction timer task
long expWakeUpInt = configuration.expiration().wakeUpInterval();
if (expWakeUpInt <= 0) {
CONTAINER.notStartingEvictionThread();
enabled = false;
} else {
expirationTask = executor.scheduleWithFixedDelay(new ScheduledTask(),
expWakeUpInt, expWakeUpInt, TimeUnit.MILLISECONDS);
}
}
// Data container entries are retrieved directly, so we don't need to worry about an encodings
this.cache = AbstractDelegatingCache.unwrapCache(cacheRef.wired()).getAdvancedCache();
this.cacheName = cache.getName();
}
@Override
public void processExpiration() {
long start = 0;
if (!Thread.currentThread().isInterrupted()) {
try {
if (log.isTraceEnabled()) {
log.trace("Purging data container of expired entries");
start = timeService.time();
}
long currentTimeMillis = timeService.wallClockTime();
for (Iterator<InternalCacheEntry<K, V>> purgeCandidates = dataContainer.running().iteratorIncludingExpired();
purgeCandidates.hasNext();) {
InternalCacheEntry<K, V> e = purgeCandidates.next();
if (e.isExpired(currentTimeMillis)) {
CompletionStages.join(entryExpiredInMemory(e, currentTimeMillis, false));
}
}
if (log.isTraceEnabled()) {
log.tracef("Purging data container completed in %s",
Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS)));
}
} catch (Exception e) {
CONTAINER.exceptionPurgingDataContainer(e);
}
}
if (!Thread.currentThread().isInterrupted()) {
CompletionStages.join(persistenceManager.purgeExpired());
}
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public CompletableFuture<Boolean> entryExpiredInMemory(InternalCacheEntry<K, V> entry, long currentTime,
boolean hasLock) {
return blockingManager.supplyBlocking(() ->
dataContainer.running().compute(entry.getKey(), ((k, oldEntry, factory) -> {
if (oldEntry != null) {
synchronized (oldEntry) {
if (oldEntry.isExpired(currentTime)) {
deleteFromStoresAndNotify(k, oldEntry.getValue(), oldEntry.getMetadata(), oldEntry.getInternalMetadata());
} else {
return oldEntry;
}
}
}
return null;
})) == null, "local-expiration").toCompletableFuture();
}
@Override
public CompletionStage<Void> handleInStoreExpirationInternal(K key) {
// Note since this is invoked without the actual key lock it is entirely possible for a remove to occur
// concurrently before the data container lock is acquired and then the oldEntry below will be null causing an
// expiration event to be generated that is extra
return handleInStoreExpirationInternal(key, null, null, null);
}
@Override
public CompletionStage<Void> handleInStoreExpirationInternal(final MarshallableEntry<K, V> marshalledEntry) {
return handleInStoreExpirationInternal(marshalledEntry.getKey(), marshalledEntry.getValue(), marshalledEntry.getMetadata(), marshalledEntry.getInternalMetadata());
}
private CompletionStage<Void> handleInStoreExpirationInternal(K key, V value, Metadata metadata, PrivateMetadata privateMetadata) {
dataContainer.running().compute(key, (oldKey, oldEntry, factory) -> {
boolean shouldRemove = false;
if (oldEntry == null) {
shouldRemove = true;
notify(key, value, metadata, privateMetadata);
} else if (oldEntry.canExpire()) {
long time = timeService.wallClockTime();
if (oldEntry.isExpired(time)) {
synchronized (oldEntry) {
// Even though we were provided marshalled entry - they may only provide metadata or value possibly
// so we have to check for null on either
shouldRemove = oldEntry.isExpired(time) && (metadata == null || oldEntry.getMetadata().equals(metadata)) &&
(value == null || value.equals(oldEntry.getValue()));
if (shouldRemove) {
notify(key, value, metadata, privateMetadata);
}
}
}
}
if (shouldRemove) {
return null;
}
return oldEntry;
});
return CompletableFutures.completedNull();
}
/**
* Deletes the key from the store as well as notifies the cache listeners of the expiration of the given key,
* value, metadata combination.
* <p>
* This method must be invoked while holding data container lock for the given key to ensure events are ordered
* properly.
*/
private void deleteFromStoresAndNotify(K key, V value, Metadata metadata, PrivateMetadata privateMetadata) {
listeners.forEach(l -> l.expired(key, value, metadata, privateMetadata)); //for internal use, assume non-blocking
CompletionStages.join(CompletionStages.allOf(
persistenceManager.deleteFromAllStores(key, keyPartitioner.getSegment(key), PersistenceManager.AccessMode.BOTH),
cacheNotifier.notifyCacheEntryExpired(key, value, metadata, null)));
}
private void notify(K key, V value, Metadata metadata, PrivateMetadata privateMetadata) {
listeners.forEach(l -> l.expired(key, value, metadata, privateMetadata)); //for internal use, assume non-blocking
CompletionStages.join(cacheNotifier.notifyCacheEntryExpired(key, value, metadata, null));
}
@Override
public CompletionStage<Boolean> handlePossibleExpiration(InternalCacheEntry<K, V> ice, int segment, boolean isWrite) {
long currentTime = timeService.wallClockTime();
if (ice.isExpired(currentTime)) {
if (log.isTraceEnabled()) {
log.tracef("Retrieved entry for key %s was expired locally, attempting expiration removal", ice.getKey());
}
CompletableFuture<Boolean> expiredStage = entryExpiredInMemory(ice, currentTime, isWrite);
if (log.isTraceEnabled()) {
expiredStage = expiredStage.thenApply(expired -> {
if (expired == Boolean.FALSE) {
log.tracef("Retrieved entry for key %s was found to not be expired.", ice.getKey());
} else {
log.tracef("Retrieved entry for key %s was confirmed to be expired.", ice.getKey());
}
return expired;
});
}
return expiredStage;
} else if (ice.canExpireMaxIdle()) {
return checkExpiredMaxIdle(ice, segment, currentTime);
}
return CompletableFutures.completedFalse();
}
/**
* Response is whether the value should be treated as expired. This is determined by if a value as able to be touched
* or not, that is if it couldn't be touched - we assumed expired (as it was removed in some way).
* @param entry the entry to check expiration and touch
* @param segment the segment the entry maps to
* @param currentTime the current time in milliseconds
* @return whether the entry was expired or not
*/
protected CompletionStage<Boolean> checkExpiredMaxIdle(InternalCacheEntry<?, ?> entry, int segment, long currentTime) {
CompletionStage<Boolean> future = cache.touch(entry.getKey(), segment, true);
if (CompletionStages.isCompletedSuccessfully(future)) {
return CompletableFutures.booleanStage(!CompletionStages.join(future));
}
return future.thenApply(touched -> !touched);
}
@Stop(priority = 5)
public void stop() {
if (expirationTask != null) {
expirationTask.cancel(true);
}
}
@Override
public void addInternalListener(ExpirationConsumer<K, V> consumer) {
listeners.add(consumer);
}
@Override
public void removeInternalListener(Object listener) {
listeners.remove(listener);
}
class ScheduledTask implements Runnable {
@Override
public void run() {
LogFactory.pushNDC(cacheName, log.isTraceEnabled());
try {
processExpiration();
} finally {
LogFactory.popNDC(log.isTraceEnabled());
}
}
}
}
| 12,282
| 42.711744
| 169
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/ConfigurationStorage.java
|
package org.infinispan.globalstate;
import org.infinispan.configuration.global.GlobalStateConfiguration;
/**
* Configuration storage
*
* @author Tristan Tarrant
* @since 9.2
*/
public enum ConfigurationStorage {
/**
* Prevents the creation or removal of caches.
*/
IMMUTABLE,
/**
* Stores cache configurations in volatile storage. Only supports {@link org.infinispan.commons.api.CacheContainerAdmin.AdminFlag#VOLATILE}
*/
VOLATILE,
/**
* Persists cache configurations to the {@link GlobalStateConfiguration#persistentLocation()} in a <pre>caches.xml</pre> file that is read on startup.
*/
OVERLAY,
/**
* Stores non-{@link org.infinispan.commons.api.CacheContainerAdmin.AdminFlag#VOLATILE} caches in a managed environment such as the server model. Supported in server deployments only.
*/
MANAGED,
/**
* Lets you provide a configuration storage provider. Providers must implement the {@link LocalConfigurationStorage} interface.
*/
CUSTOM,
}
| 1,019
| 29
| 186
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/package-info.java
|
/**
* Global configuration state.
*
* @api.public
*/
package org.infinispan.globalstate;
| 94
| 10.875
| 35
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/ScopedState.java
|
package org.infinispan.globalstate;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.commons.marshall.Ids;
/**
* Key for scoped entries in the ClusterConfigurationManager state cache
*
* @author Tristan Tarrant
* @since 9.2
*/
public class ScopedState {
private final String scope;
private final String name;
public ScopedState(String scope, String name) {
this.scope = scope;
this.name = name;
}
public String getScope() {
return scope;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScopedState that = (ScopedState) o;
if (scope != null ? !scope.equals(that.scope) : that.scope != null) return false;
return name != null ? name.equals(that.name) : that.name == null;
}
@Override
public int hashCode() {
int result = scope != null ? scope.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ScopedState{" +
"scope='" + scope + '\'' +
", name='" + name + '\'' +
'}';
}
public static class Externalizer extends AbstractExternalizer<ScopedState> {
private static final long serialVersionUID = 326802903448963450L;
@Override
public Integer getId() {
return Ids.SCOPED_STATE;
}
@Override
public Set<Class<? extends ScopedState>> getTypeClasses() {
return Collections.singleton(ScopedState.class);
}
@Override
public void writeObject(ObjectOutput output, ScopedState object) throws IOException {
output.writeUTF(object.scope);
output.writeUTF(object.name);
}
@Override
public ScopedState readObject(ObjectInput input) throws IOException, ClassNotFoundException {
String scope = input.readUTF();
String name = input.readUTF();
return new ScopedState(scope, name);
}
}
}
| 2,284
| 24.388889
| 99
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/GlobalStateProvider.java
|
package org.infinispan.globalstate;
/**
* GlobalStateProvider. Implementors who need to register with the {@link GlobalStateManager}
* because they contribute to/are interested in the contents of the global persistent state.
*
* @author Tristan Tarrant
* @since 8.1
*/
public interface GlobalStateProvider {
/**
* This method is invoked by the {@link GlobalStateManager} just before
* persisting the global state
*/
void prepareForPersist(ScopedPersistentState globalState);
/**
* This method is invoked by the {@link GlobalStateManager} after starting up to notify
* that global state has been restored.
*/
void prepareForRestore(ScopedPersistentState globalState);
}
| 714
| 28.791667
| 93
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/GlobalConfigurationManager.java
|
package org.infinispan.globalstate;
import java.util.EnumSet;
import java.util.concurrent.CompletionStage;
import org.infinispan.Cache;
import org.infinispan.commons.api.CacheContainerAdmin.AdminFlag;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* The {@link GlobalConfigurationManager} is the main interface for sharing runtime configuration state across a cluster.
* It uses an internal cache 'org.infinispan.CONFIG'. The cache is keyed with {@link ScopedState}. Each scope owner is responsible
* for its own keys.
*
* @author Tristan Tarrant
* @since 9.2
*/
@Scope(Scopes.GLOBAL)
public interface GlobalConfigurationManager {
String CONFIG_STATE_CACHE_NAME = "org.infinispan.CONFIG";
default void postStart() {}
/**
* Returns the global state cache
*/
Cache<ScopedState, Object> getStateCache();
/**
* Defines a cluster-wide configuration template
*
* @param name the name of the template
* @param configuration the configuration object
* @param flags the flags to apply
*/
CompletionStage<Void> createTemplate(String name, Configuration configuration, EnumSet<AdminFlag> flags);
/**
* Defines a cluster-wide configuration template
*
* @param name the name of the template
* @param configuration the configuration object
* @param flags the flags to apply
*/
CompletionStage<Configuration> getOrCreateTemplate(String name, Configuration configuration, EnumSet<AdminFlag> flags);
/**
* Defines a cluster-wide cache configuration
* @param cacheName the name of the configuration
* @param configuration the configuration object
* @param flags the flags to apply
*/
CompletionStage<Configuration> createCache(String cacheName, Configuration configuration, EnumSet<AdminFlag> flags);
/**
* Defines a cluster-wide cache configuration or retrieves an existing one
* @param cacheName the name of the configuration
* @param configuration the configuration object
* @param flags the flags to apply
*/
CompletionStage<Configuration> getOrCreateCache(String cacheName, Configuration configuration, EnumSet<AdminFlag> flags);
/**
* Defines a cluster-wide cache configuration using the supplied template
* @param cacheName the name of the configuration
* @param template the template name to use
* @param flags the flags to apply
*/
CompletionStage<Configuration> createCache(String cacheName, String template, EnumSet<AdminFlag> flags);
/**
* Defines a cluster-wide cache configuration using the supplied template or retrieves an existing one
* @param cacheName the name of the configuration
* @param template the template name to use
* @param flags the flags to apply
*/
CompletionStage<Configuration> getOrCreateCache(String cacheName, String template, EnumSet<AdminFlag> flags);
/**
* Removes a cluster-wide cache and its configuration
* @param cacheName the name of the cache
* @param flags
*/
CompletionStage<Void> removeCache(String cacheName, EnumSet<AdminFlag> flags);
/**
* Removes a cluster-wide template
* @param name the name of the template
* @param flags
*/
CompletionStage<Void> removeTemplate(String name, EnumSet<AdminFlag> flags);
}
| 3,397
| 34.768421
| 130
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/LocalConfigurationStorage.java
|
package org.infinispan.globalstate;
import java.util.EnumSet;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.configuration.ConfigurationManager;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.util.concurrent.BlockingManager;
/**
* The {@link LocalConfigurationStorage} is responsible for applying on each node the configuration changes initiated
* through the {@link org.infinispan.globalstate.GlobalConfigurationManager} and persist them unless they are
* {@link org.infinispan.commons.api.CacheContainerAdmin.AdminFlag#VOLATILE}.
*
* @author Tristan Tarrant
* @since 9.2
*/
public interface LocalConfigurationStorage {
/**
* Initialization entry point for the {@link LocalConfigurationStorage}
* @param embeddedCacheManager
* @param configurationManager
* @param blockingManager handler to use when a blocking operation is required
*/
void initialize(EmbeddedCacheManager embeddedCacheManager, ConfigurationManager configurationManager, BlockingManager blockingManager);
/**
* Checks whether this {@link LocalConfigurationStorage} supports the supplied flags.
* A {@link org.infinispan.commons.CacheConfigurationException} will be thrown in case this cannot be done.
*
*/
void validateFlags(EnumSet<CacheContainerAdmin.AdminFlag> flags);
/**
* Creates the cache using the supplied template, configuration and flags. This method may be invoked either with or
* without a template. In both cases a concrete configuration will also be available. If a template name is present,
* the {@link LocalConfigurationStorage} should use it, e.g. when persisting the configuration.
*
* @param name the name of the cache to create
* @param template the template that should be used to configure the cache. Can be null.
* @param configuration the {@link Configuration} to use
* @param flags the desired {@link org.infinispan.commons.api.CacheContainerAdmin.AdminFlag}s
*/
CompletionStage<Void> createCache(String name, String template, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags);
/**
* Creates the template using the supplied configuration and flags.
*
* @param name the name of the template to create
* @param configuration the {@link Configuration} to use
* @param flags the desired {@link org.infinispan.commons.api.CacheContainerAdmin.AdminFlag}s
*/
CompletionStage<Void> createTemplate(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags);
/**
* Updates an existing configuration. Only the attributes that are mutable and that have been modified in the supplied
* configuration will be applied.
*
* @param name the name of the configuration (cache/template)
* @param configuration the configuration changes to apply
* @param flags the desired {@link org.infinispan.commons.api.CacheContainerAdmin.AdminFlag}s
*/
CompletionStage<Void> updateConfiguration(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags);
/**
* Validates an update to an existing configuration.
* @param name the name of the configuration (cache/template)
* @param configuration the configuration changes to apply
* @param flags the desired {@link org.infinispan.commons.api.CacheContainerAdmin.AdminFlag}s
*/
CompletionStage<Void> validateConfigurationUpdate(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags);
/**
* Removes the specified cache.
*
* @param name the name of the cache to remove
* @param flags the desired {@link org.infinispan.commons.api.CacheContainerAdmin.AdminFlag}s
*/
CompletionStage<Void> removeCache(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags);
/**
* Removes the specified template.
*
* @param name the name of the template to remove
* @param flags the desired {@link org.infinispan.commons.api.CacheContainerAdmin.AdminFlag}s
*/
CompletionStage<Void> removeTemplate(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags);
/**
* Loads all persisted cache configurations
* @deprecated since 12.0, use {@link #loadAllCaches} instead
*/
@Deprecated
default Map<String, Configuration> loadAll() {
return loadAllCaches();
}
/**
* Loads all persisted cache configurations
*/
Map<String, Configuration> loadAllCaches();
/**
* Loads all persisted templates
*/
Map<String, Configuration> loadAllTemplates();
}
| 4,736
| 41.675676
| 142
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/ScopeFilter.java
|
package org.infinispan.globalstate;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import java.util.function.Predicate;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.marshall.Ids;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilter;
import org.infinispan.notifications.cachelistener.filter.EventType;
/**
* A filter for {@link ScopedState} that allows listeners of the global state cache to choose events by scope.
*/
public class ScopeFilter implements CacheEventFilter<ScopedState, Object>, Predicate<ScopedState> {
private final String scope;
public ScopeFilter(String scope) {
this.scope = scope;
}
@Override
public boolean accept(ScopedState key, Object oldValue, Metadata oldMetadata, Object newValue, Metadata newMetadata, EventType eventType) {
return test(key);
}
@Override
public boolean test(ScopedState key) {
return scope.equals(key.getScope());
}
public static class Externalizer implements AdvancedExternalizer<ScopeFilter> {
@Override
public Set<Class<? extends ScopeFilter>> getTypeClasses() {
return Collections.singleton(ScopeFilter.class);
}
@Override
public Integer getId() {
return Ids.SCOPED_STATE_FILTER;
}
@Override
public void writeObject(ObjectOutput output, ScopeFilter object) throws IOException {
output.writeUTF(object.scope);
}
@Override
public ScopeFilter readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new ScopeFilter(input.readUTF());
}
}
}
| 1,781
| 29.20339
| 142
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/ScopedPersistentState.java
|
package org.infinispan.globalstate;
import java.util.function.BiConsumer;
/**
* ScopedPersistentState represents state which needs to be persisted, scoped by name (e.g. the cache name).
* The default implementation of persistent state uses the standard {@link java.util.Properties} format with the
* additional rule that order is preserved. In order to verify state consistency (e.g. across a cluster) a checksum
* of the state's data can be computed. State properties prefixed with the '@' character will not be included as part
* of the checksum computation (e.g. @timestamp)
*
* @author Tristan Tarrant
* @since 8.1
*/
public interface ScopedPersistentState {
String GLOBAL_SCOPE = "___global";
/**
* Returns the name of this persistent state's scope
*/
String getScope();
/**
* Sets a state property. Values will be unicode-escaped when written
*/
void setProperty(String key, String value);
/**
* Retrieves a state property
*/
String getProperty(String key);
/**
* Sets an integer state property.
*/
void setProperty(String key, int value);
/**
* Sets a float state property.
*/
void setProperty(String format, float f);
/**
* Retrieves an integer state property
*/
int getIntProperty(String key);
/**
* Retrieves a float state property
*/
float getFloatProperty(String key);
/**
* Performs the specified action on every entry of the state
*/
void forEach(BiConsumer<String, String> action);
/**
* Returns the checksum of the properties excluding those prefixed with @
*/
int getChecksum();
/**
* Returns whether the state contains a property
*/
boolean containsProperty(String key);
}
| 1,755
| 24.823529
| 117
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/GlobalStateManager.java
|
package org.infinispan.globalstate;
import java.util.Optional;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* GlobalStateManager.
*
* @author Tristan Tarrant
* @since 8.1
*/
@Scope(Scopes.GLOBAL)
public interface GlobalStateManager {
/**
* Registers a state provider within this state manager
*
* @param provider
*/
void registerStateProvider(GlobalStateProvider provider);
/**
* Reads the persistent state for the specified scope.
*/
Optional<ScopedPersistentState> readScopedState(String scope);
/**
* Persists the specified scoped state
*/
void writeScopedState(ScopedPersistentState state);
/**
* Delete the persistent state for the given scope
*/
void deleteScopedState(String scope);
/**
* Persists the global state by contacting all registered scope providers
*/
void writeGlobalState();
}
| 939
| 20.860465
| 76
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/impl/ImmutableLocalConfigurationStorage.java
|
package org.infinispan.globalstate.impl;
import static org.infinispan.util.logging.Log.CONFIG;
import java.lang.invoke.MethodHandles;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.configuration.ConfigurationManager;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.globalstate.LocalConfigurationStorage;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* An immutable implementation of {@link LocalConfigurationStorage} which does not allow cache creation/removal.
*
* @author Tristan Tarrant
* @since 9.2
*/
public class ImmutableLocalConfigurationStorage implements LocalConfigurationStorage {
protected static Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
@Override
public void initialize(EmbeddedCacheManager embeddedCacheManager, ConfigurationManager configurationManager, BlockingManager blockingManager) {
}
@Override
public void validateFlags(EnumSet<CacheContainerAdmin.AdminFlag> flags) {
throw CONFIG.immutableConfiguration();
}
@Override
public CompletionStage<Void> createCache(String name, String template, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
throw CONFIG.immutableConfiguration();
}
@Override
public CompletionStage<Void> removeCache(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
throw CONFIG.immutableConfiguration();
}
@Override
public CompletionStage<Void> createTemplate(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
throw CONFIG.immutableConfiguration();
}
@Override
public CompletionStage<Void> updateConfiguration(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
throw CONFIG.immutableConfiguration();
}
@Override
public CompletionStage<Void> validateConfigurationUpdate(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
throw CONFIG.immutableConfiguration();
}
@Override
public CompletionStage<Void> removeTemplate(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
throw CONFIG.immutableConfiguration();
}
@Override
public Map<String, Configuration> loadAllCaches() {
return Collections.emptyMap();
}
@Override
public Map<String, Configuration> loadAllTemplates() {
return Collections.emptyMap();
}
}
| 2,736
| 34.089744
| 150
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/impl/CacheState.java
|
package org.infinispan.globalstate.impl;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.marshall.Ids;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.commons.marshall.SerializeWith;
/**
* Cache State information stored in a cluster-wide cache
*
* @author Tristan Tarrant
* @since 9.2
*/
@SerializeWith(CacheState.Externalizer.class)
public class CacheState {
private final String template;
private final String configuration;
private final EnumSet<CacheContainerAdmin.AdminFlag> flags;
public CacheState(String template, String configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
this.template = template;
this.configuration = configuration;
this.flags = flags.clone();
}
public String getTemplate() {
return template;
}
public String getConfiguration() {
return configuration;
}
public EnumSet<CacheContainerAdmin.AdminFlag> getFlags() {
return flags;
}
public static class Externalizer implements AdvancedExternalizer<CacheState> {
@Override
public void writeObject(ObjectOutput output, CacheState state) throws IOException {
MarshallUtil.marshallString(state.template, output);
MarshallUtil.marshallString(state.configuration, output);
output.writeObject(state.flags);
}
@Override
public CacheState readObject(ObjectInput input) throws IOException, ClassNotFoundException {
String template = MarshallUtil.unmarshallString(input);
String configuration = MarshallUtil.unmarshallString(input);
EnumSet<CacheContainerAdmin.AdminFlag> flags = (EnumSet<CacheContainerAdmin.AdminFlag>) input.readObject();
return new CacheState(template, configuration, flags == null ? EnumSet.noneOf(CacheContainerAdmin.AdminFlag.class) : flags);
}
@Override
public Set<Class<? extends CacheState>> getTypeClasses() {
return Collections.singleton(CacheState.class);
}
@Override
public Integer getId() {
return Ids.CACHE_STATE;
}
}
}
| 2,359
| 30.466667
| 133
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/impl/ScopedPersistentStateImpl.java
|
package org.infinispan.globalstate.impl;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import org.infinispan.globalstate.ScopedPersistentState;
/**
* ScopedPersistentStateImpl.
*
* @author Tristan Tarrant
* @since 8.1
*/
public class ScopedPersistentStateImpl implements ScopedPersistentState {
private final String scope;
private final Map<String, String> state;
public ScopedPersistentStateImpl(String scope) {
this.scope = scope;
this.state = new LinkedHashMap<>(); // to preserve order
}
@Override
public String getScope() {
return scope;
}
@Override
public void setProperty(String key, String value) {
state.put(key, value);
}
@Override
public void setProperty(String key, int value) {
setProperty(key, Integer.toString(value));
}
@Override
public int getIntProperty(String key) {
return Integer.parseInt(state.get(key));
}
@Override
public void setProperty(String key, float f) {
setProperty(key, Float.toString(f));
}
@Override
public float getFloatProperty(String key) {
return Float.parseFloat(state.get(key));
}
@Override
public String getProperty(String key) {
return state.get(key);
}
@Override
public void forEach(BiConsumer<String, String> action) {
state.forEach(action);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScopedPersistentStateImpl that = (ScopedPersistentStateImpl) o;
if (scope != null ? !scope.equals(that.scope) : that.scope != null) return false;
return state != null ? state.equals(that.state) : that.state == null;
}
@Override
public int hashCode() {
int result = scope != null ? scope.hashCode() : 0;
result = 31 * result + (state != null ? state.hashCode() : 0);
return result;
}
@Override
public int getChecksum() {
int result = scope != null ? scope.hashCode() : 0;
result += state.entrySet().stream().filter(e -> !e.getKey().startsWith("@")).mapToInt(Map.Entry::hashCode).sum();
return result;
}
@Override
public boolean containsProperty(String key) {
return state.containsKey(key);
}
}
| 2,335
| 23.589474
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/impl/VolatileLocalConfigurationStorage.java
|
package org.infinispan.globalstate.impl;
import static org.infinispan.factories.KnownComponentNames.CACHE_DEPENDENCY_GRAPH;
import static org.infinispan.util.logging.Log.CONFIG;
import java.lang.invoke.MethodHandles;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.configuration.ConfigurationManager;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.parsing.ParserRegistry;
import org.infinispan.eviction.impl.PassivationManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.globalstate.LocalConfigurationStorage;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.persistence.manager.PersistenceManager;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.util.DependencyGraph;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* An implementation of {@link LocalConfigurationStorage} which does only supports
* {@link org.infinispan.commons.api.CacheContainerAdmin.AdminFlag#VOLATILE} operations
*
* @author Tristan Tarrant
* @since 9.2
*/
public class VolatileLocalConfigurationStorage implements LocalConfigurationStorage {
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
protected EmbeddedCacheManager cacheManager;
protected ParserRegistry parserRegistry;
protected ConfigurationManager configurationManager;
protected BlockingManager blockingManager;
@Override
public void initialize(EmbeddedCacheManager cacheManager, ConfigurationManager configurationManager, BlockingManager blockingManager) {
this.configurationManager = configurationManager;
this.cacheManager = cacheManager;
this.parserRegistry = new ParserRegistry();
this.blockingManager = blockingManager;
}
@Override
public void validateFlags(EnumSet<CacheContainerAdmin.AdminFlag> flags) {
if (!flags.contains(CacheContainerAdmin.AdminFlag.VOLATILE))
throw CONFIG.globalStateDisabled();
}
@Override
public CompletionStage<Void> createTemplate(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
Configuration existing = SecurityActions.getCacheConfiguration(cacheManager, name);
if (existing == null) {
SecurityActions.defineConfiguration(cacheManager, name, configuration);
log.debugf("Defined template '%s' on '%s' using %s", name, cacheManager.getAddress(), configuration);
} else if (!existing.matches(configuration)) {
throw CONFIG.incompatibleClusterConfiguration(name, configuration, existing);
} else {
log.debugf("%s already has a template %s with configuration %s", cacheManager.getAddress(), name, configuration);
}
return CompletableFutures.completedNull();
}
@Override
public CompletionStage<Void> createCache(String name, String template, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
Configuration existing = SecurityActions.getCacheConfiguration(cacheManager, name);
if (existing == null) {
SecurityActions.defineConfiguration(cacheManager, name, configuration);
log.debugf("Defined cache '%s' on '%s' using %s", name, cacheManager.getAddress(), configuration);
} else if (!existing.matches(configuration)) {
throw CONFIG.incompatibleClusterConfiguration(name, configuration, existing);
} else {
log.debugf("%s already has a cache %s with configuration %s", cacheManager.getAddress(), name, configuration);
}
// Ensure the cache is started
return blockingManager.<Void>supplyBlocking(() -> {
try {
SecurityActions.getCache(cacheManager, name);
} catch (CacheException cacheException) {
log.cannotObtainFailedCache(name, cacheException);
}
return null;
}, name).toCompletableFuture();
}
@Override
public CompletionStage<Void> validateConfigurationUpdate(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
Configuration existing = SecurityActions.getCacheConfiguration(cacheManager, name);
if (existing == null) {
throw CONFIG.noSuchCacheConfiguration(name);
} else {
existing.validateUpdate(name, configuration);
return CompletableFutures.completedNull();
}
}
@Override
public CompletionStage<Void> updateConfiguration(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
Configuration existing = SecurityActions.getCacheConfiguration(cacheManager, name);
if (existing == null) {
throw CONFIG.noSuchCacheConfiguration(name);
} else {
existing.update(name, configuration);
}
return CompletableFutures.completedNull();
}
@Override
public CompletionStage<Void> removeCache(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
return blockingManager.<Void>supplyBlocking(() -> {
removeCacheSync(name, flags);
return null;
}, name).toCompletableFuture();
}
protected void removeCacheSync(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
log.debugf("Remove cache %s", name);
GlobalComponentRegistry globalComponentRegistry = SecurityActions.getGlobalComponentRegistry(cacheManager);
ComponentRegistry cacheComponentRegistry = globalComponentRegistry.getNamedComponentRegistry(name);
if (cacheComponentRegistry != null) {
cacheComponentRegistry.getComponent(PersistenceManager.class).setClearOnStop(true);
cacheComponentRegistry.getComponent(PassivationManager.class).skipPassivationOnStop(true);
Cache<?, ?> cache = cacheManager.getCache(name, false);
if (cache != null) {
SecurityActions.stopCache(cache);
}
}
globalComponentRegistry.removeCache(name);
// Remove cache configuration and remove it from the computed cache name list
globalComponentRegistry.getComponent(ConfigurationManager.class).removeConfiguration(name);
// Remove cache from dependency graph
//noinspection unchecked
globalComponentRegistry.getComponent(DependencyGraph.class, CACHE_DEPENDENCY_GRAPH).remove(name);
}
@Override
public CompletionStage<Void> removeTemplate(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
removeTemplateSync(name, flags);
return CompletableFutures.completedNull();
}
protected void removeTemplateSync(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
log.debugf("Remove template %s", name);
GlobalComponentRegistry globalComponentRegistry = SecurityActions.getGlobalComponentRegistry(cacheManager);
// Remove cache configuration and remove it from the computed cache name list
globalComponentRegistry.getComponent(ConfigurationManager.class).removeConfiguration(name);
}
@Override
public Map<String, Configuration> loadAllCaches() {
// This is volatile, so nothing to do here
return Collections.emptyMap();
}
@Override
public Map<String, Configuration> loadAllTemplates() {
// This is volatile, so nothing to do here
return Collections.emptyMap();
}
}
| 7,734
| 43.710983
| 150
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/impl/OverlayLocalConfigurationStorage.java
|
package org.infinispan.globalstate.impl;
import static org.infinispan.commons.util.Util.renameTempFile;
import static org.infinispan.util.logging.Log.CONFIG;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.commons.configuration.io.ConfigurationWriter;
import org.infinispan.commons.configuration.io.URLConfigurationResourceResolver;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.GlobalStateConfiguration;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.globalstate.LocalConfigurationStorage;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* An implementation of {@link LocalConfigurationStorage} which stores non-{@link org.infinispan.commons.api.CacheContainerAdmin.AdminFlag#VOLATILE}
* <p>
* This component persists cache configurations to the {@link GlobalStateConfiguration#persistentLocation()} in a
* <pre>caches.xml</pre> file which is read on startup.
*
* @author Tristan Tarrant
* @since 9.2
*/
public class OverlayLocalConfigurationStorage extends VolatileLocalConfigurationStorage {
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private final Set<String> persistentCaches = ConcurrentHashMap.newKeySet();
private final Set<String> persistentTemplates = ConcurrentHashMap.newKeySet();
private final Lock persistenceLock = new ReentrantLock();
@Override
public void validateFlags(EnumSet<CacheContainerAdmin.AdminFlag> flags) {
GlobalConfiguration globalConfiguration = configurationManager.getGlobalConfiguration();
if (!flags.contains(CacheContainerAdmin.AdminFlag.VOLATILE) && !globalConfiguration.globalState().enabled())
throw CONFIG.globalStateDisabled();
}
@Override
public CompletionStage<Void> createTemplate(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
CompletionStage<Void> future = super.createTemplate(name, configuration, flags);
if (!flags.contains(CacheContainerAdmin.AdminFlag.VOLATILE)) {
return blockingManager.thenApplyBlocking(future, (v) -> {
persistentTemplates.add(name);
storeTemplates();
return v;
}, name).toCompletableFuture();
} else {
return future;
}
}
@Override
public CompletionStage<Void> removeTemplate(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
return blockingManager.<Void>supplyBlocking(() -> {
if (persistentTemplates.remove(name)) {
storeTemplates();
}
removeTemplateSync(name, flags);
return null;
}, name).toCompletableFuture();
}
@Override
public CompletionStage<Void> createCache(String name, String template, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
CompletionStage<Void> future = super.createCache(name, template, configuration, flags);
if (!flags.contains(CacheContainerAdmin.AdminFlag.VOLATILE)) {
return blockingManager.thenApplyBlocking(future, (v) -> {
persistentCaches.add(name);
storeCaches();
return v;
}, name).toCompletableFuture();
} else {
return future;
}
}
@Override
public CompletionStage<Void> updateConfiguration(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
CompletionStage<Void> future = super.updateConfiguration(name, configuration, flags);
if (persistentCaches.contains(name)) {
return blockingManager.thenApplyBlocking(future, (v) -> {
storeCaches();
return v;
}, name).toCompletableFuture();
} else {
return future;
}
}
@Override
public CompletionStage<Void> removeCache(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
return blockingManager.<Void>supplyBlocking(() -> {
if (persistentCaches.remove(name)) {
storeCaches();
}
removeCacheSync(name, flags);
return null;
}, name).toCompletableFuture();
}
@Override
public Map<String, Configuration> loadAllCaches() {
Map<String, Configuration> configs = load(getCachesFile());
log.tracef("Loaded cache configurations from local persistence: %s", configs.keySet());
return configs;
}
@Override
public Map<String, Configuration> loadAllTemplates() {
Map<String, Configuration> configs = load(getTemplateFile());
log.tracef("Loaded templates from local persistence: %s", configs.keySet());
return configs;
}
private Map<String, Configuration> load(File file) {
try (FileInputStream fis = new FileInputStream(file)) {
Map<String, Configuration> configurations = new HashMap<>();
ConfigurationBuilderHolder holder = configurationManager.toBuilderHolder();
parserRegistry.parse(fis, holder, new URLConfigurationResourceResolver(file.toURI().toURL()), MediaType.APPLICATION_XML);
Collection<String> definedConfigurations = configurationManager.getDefinedConfigurations();
for (Map.Entry<String, ConfigurationBuilder> entry : holder.getNamedConfigurationBuilders().entrySet()) {
String name = entry.getKey();
if (!definedConfigurations.contains(name)) {
Configuration configuration = entry.getValue().build();
configurations.put(name, configuration);
}
}
return configurations;
} catch (FileNotFoundException e) {
// Ignore
return Collections.emptyMap();
} catch (IOException e) {
throw new CacheConfigurationException(e);
}
}
private void storeCaches() {
persistConfigurations("caches", getCachesFile(), getCachesFileLock(), persistentCaches);
}
private void storeTemplates() {
persistConfigurations("templates", getTemplateFile(), getTemplateFileLock(), persistentTemplates);
}
private void persistConfigurations(String prefix, File file, File lock, Set<String> configNames) {
// Renaming is done using file locks, which are acquired by the entire JVM.
// Use a regular lock as well, so another thread cannot lock the file at the same time
// and cause an OverlappingFileLockException.
persistenceLock.lock();
try {
GlobalConfiguration globalConfiguration = configurationManager.getGlobalConfiguration();
File sharedDirectory = new File(globalConfiguration.globalState().sharedPersistentLocation());
sharedDirectory.mkdirs();
File temp = File.createTempFile(prefix, null, sharedDirectory);
Map<String, Configuration> configurationMap = new HashMap<>();
for (String config : configNames) {
Configuration configuration = configurationManager.getConfiguration(config, true);
if (configuration == null) {
log.configurationNotFound(config, configurationManager.getDefinedConfigurations());
} else {
configurationMap.put(config, configuration);
}
}
try (ConfigurationWriter writer = ConfigurationWriter.to(new FileOutputStream(temp)).clearTextSecrets(true).prettyPrint(true).build()) {
parserRegistry.serialize(writer, null, configurationMap);
}
try {
renameTempFile(temp, lock, file);
} catch (Exception e) {
throw CONFIG.cannotRenamePersistentFile(temp.getAbsolutePath(), file, e);
}
} catch (Exception e) {
throw CONFIG.errorPersistingGlobalConfiguration(e);
} finally {
persistenceLock.unlock();
}
}
private File getCachesFile() {
return new File(configurationManager.getGlobalConfiguration().globalState().sharedPersistentLocation(), "caches.xml");
}
private File getCachesFileLock() {
return new File(configurationManager.getGlobalConfiguration().globalState().sharedPersistentLocation(), "caches.xml.lck");
}
private File getTemplateFile() {
return new File(configurationManager.getGlobalConfiguration().globalState().sharedPersistentLocation(), "templates.xml");
}
private File getTemplateFileLock() {
return new File(configurationManager.getGlobalConfiguration().globalState().sharedPersistentLocation(), "templates.xml.lck");
}
}
| 9,291
| 41.045249
| 150
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/impl/GlobalConfigurationStateListener.java
|
package org.infinispan.globalstate.impl;
import static org.infinispan.globalstate.impl.GlobalConfigurationManagerImpl.CACHE_SCOPE;
import static org.infinispan.globalstate.impl.GlobalConfigurationManagerImpl.isKnownScope;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.util.concurrent.CompletionStage;
import org.infinispan.globalstate.ScopedState;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent;
import org.infinispan.commons.util.concurrent.CompletableFutures;
/**
* Listens to events on the global state cache and manages cache configuration creation / removal accordingly
*
* @author Tristan Tarrant
* @since 9.2
*/
@Listener(observation = Listener.Observation.BOTH)
public class GlobalConfigurationStateListener {
private final GlobalConfigurationManagerImpl gcm;
GlobalConfigurationStateListener(GlobalConfigurationManagerImpl gcm) {
this.gcm = gcm;
}
@CacheEntryCreated
public CompletionStage<Void> handleCreate(CacheEntryCreatedEvent<ScopedState, CacheState> event) {
// We are only interested in POST for creation
if (event.isPre())
return CompletableFutures.completedNull();
String scope = event.getKey().getScope();
if (!isKnownScope(scope))
return CompletableFutures.completedNull();
String name = event.getKey().getName();
CacheState state = event.getValue();
return CACHE_SCOPE.equals(scope) ?
gcm.createCacheLocally(name, state) :
gcm.createTemplateLocally(name, state);
}
@CacheEntryModified
public CompletionStage<Void> handleUpdate(CacheEntryModifiedEvent<ScopedState, CacheState> event) {
String scope = event.getKey().getScope();
if (!isKnownScope(scope))
return CompletableFutures.completedNull();
String name = event.getKey().getName();
CacheState state = event.getNewValue();
if (event.isPre()) {
return event.isOriginLocal() ? gcm.validateConfigurationUpdateLocally(name, state) : CompletableFutures.completedNull();
} else {
return gcm.updateConfigurationLocally(name, state);
}
}
@CacheEntryRemoved
public CompletionStage<Void> handleRemove(CacheEntryRemovedEvent<ScopedState, CacheState> event) {
// We are only interested in POST for removal
if (event.isPre())
return CompletableFutures.completedNull();
String scope = event.getKey().getScope();
if (!isKnownScope(scope))
return CompletableFutures.completedNull();
String name = event.getKey().getName();
if (CACHE_SCOPE.equals(scope)) {
CONTAINER.debugf("Stopping cache %s because it was removed from global state", name);
return gcm.removeCacheLocally(name);
} else {
CONTAINER.debugf("Removing template %s because it was removed from global state", name);
return gcm.removeTemplateLocally(name);
}
}
}
| 3,399
| 39.47619
| 129
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/impl/GlobalStateManagerImpl.java
|
package org.infinispan.globalstate.impl;
import static org.infinispan.globalstate.ScopedPersistentState.GLOBAL_SCOPE;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.Util;
import org.infinispan.commons.util.Version;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.globalstate.GlobalStateManager;
import org.infinispan.globalstate.GlobalStateProvider;
import org.infinispan.globalstate.ScopedPersistentState;
/**
* GlobalStateManagerImpl. This global component manages persistent state across restarts as well as global
* configurations. The information is stored in a Properties file. On a graceful shutdown it persists the following
* information:
* <p>
* version = full version (e.g. major.minor.micro.qualifier) timestamp = timestamp using ISO-8601
* <p>
* as well as any additional information contributed by registered {@link GlobalStateProvider}s
*
* @author Tristan Tarrant
* @since 8.1
*/
@Scope(Scopes.GLOBAL)
public class GlobalStateManagerImpl implements GlobalStateManager {
public static final String VERSION = "@version";
public static final String TIMESTAMP = "@timestamp";
public static final String VERSION_MAJOR = "version-major";
@Inject
GlobalConfiguration globalConfiguration;
@Inject
TimeService timeService;
private List<GlobalStateProvider> stateProviders = new ArrayList<>();
private boolean persistentState;
FileOutputStream globalLockFile;
private FileLock globalLock;
private ScopedPersistentState globalState;
@Start(priority = 1) // Must start before everything else
public void start() {
persistentState = globalConfiguration.globalState().enabled();
if (persistentState) {
acquireGlobalLock();
loadGlobalState();
}
}
@Stop(priority = 1) // Must write global state before other global components shut down
public void stop() {
if (persistentState) {
writeGlobalState();
releaseGlobalLock();
}
}
private void acquireGlobalLock() {
File lockFile = getLockFile();
if (lockFile.exists()) {
// The node was not shutdown cleanly
switch (globalConfiguration.globalState().uncleanShutdownAction()) {
case FAIL:
throw CONTAINER.globalStateLockFilePresent(lockFile);
case PURGE:
deleteScopedState(GLOBAL_SCOPE);
lockFile.delete();
break;
case IGNORE:
// Do nothing;
break;
}
}
try {
lockFile.getParentFile().mkdirs();
globalLockFile = new FileOutputStream(lockFile);
globalLock = globalLockFile.getChannel().tryLock();
if (globalLock == null) {
throw CONTAINER.globalStateCannotAcquireLockFile(null, lockFile);
}
} catch (IOException | OverlappingFileLockException e) {
throw CONTAINER.globalStateCannotAcquireLockFile(e, lockFile);
}
}
private void releaseGlobalLock() {
if (globalLockFile != null) {
if (globalLock != null && globalLock.isValid())
Util.close(globalLock);
globalLock = null;
Util.close(globalLockFile);
// Only delete the file if we had successfully acquired it
getLockFile().delete();
}
}
private void loadGlobalState() {
File stateFile = getStateFile(GLOBAL_SCOPE);
globalState = readScopedState(GLOBAL_SCOPE).orElse(null);
if (globalState != null) {
ScopedPersistentState state = globalState;
// We proceed only if we can write to the file
if (!stateFile.canWrite()) {
throw CONTAINER.nonWritableStateFile(stateFile);
}
// Validate the state before proceeding
if (!state.containsProperty(VERSION) || !state.containsProperty(VERSION_MAJOR) || !state.containsProperty(TIMESTAMP)) {
throw CONTAINER.invalidPersistentState(GLOBAL_SCOPE);
}
CONTAINER.globalStateLoad(state.getProperty(VERSION), state.getProperty(TIMESTAMP));
stateProviders.forEach(provider -> provider.prepareForRestore(state));
} else {
// Clean slate. Create the persistent location if necessary and acquire a lock
stateFile.getParentFile().mkdirs();
}
}
@Override
public void writeGlobalState() {
if (persistentState) {
if (stateProviders.isEmpty()) {
// If no state providers were registered, we cannot persist
CONTAINER.incompleteGlobalState();
} else {
ScopedPersistentState state = new ScopedPersistentStateImpl(GLOBAL_SCOPE);
state.setProperty(VERSION, Version.getVersion());
state.setProperty(VERSION_MAJOR, Version.getMajor());
state.setProperty(TIMESTAMP, timeService.instant().toString());
// ask any state providers to contribute to the global state
for (GlobalStateProvider provider : stateProviders) {
provider.prepareForPersist(state);
}
writeScopedState(state);
CONTAINER.globalStateWrite(state.getProperty(VERSION), state.getProperty(TIMESTAMP));
}
}
}
@Override
public void writeScopedState(ScopedPersistentState state) {
if (persistentState) {
File stateFile = getStateFile(state.getScope());
try (PrintWriter w = new PrintWriter(stateFile)) {
state.forEach((key, value) -> {
w.printf("%s=%s%n", Util.unicodeEscapeString(key), Util.unicodeEscapeString(value));
});
} catch (IOException e) {
throw CONTAINER.failedWritingGlobalState(e, stateFile);
}
}
}
@Override
public void deleteScopedState(String scope) {
if (persistentState) {
File stateFile = getStateFile(scope);
try {
Files.deleteIfExists(stateFile.toPath());
} catch (IOException e) {
throw CONTAINER.failedWritingGlobalState(e, stateFile);
}
}
}
@Override
public Optional<ScopedPersistentState> readScopedState(String scope) {
if (!persistentState)
return Optional.empty();
File stateFile = getStateFile(scope);
if (!stateFile.exists())
return Optional.empty();
try (BufferedReader r = new BufferedReader(new FileReader(stateFile))) {
ScopedPersistentState state = new ScopedPersistentStateImpl(scope);
for (String line = r.readLine(); line != null; line = r.readLine()) {
if (!line.startsWith("#")) { // Skip comment lines
int eq = line.indexOf('=');
while (eq > 0 && line.charAt(eq - 1) == '\\') {
eq = line.indexOf('=', eq + 1);
}
if (eq > 0) {
state.setProperty(Util.unicodeUnescapeString(line.substring(0, eq).trim()),
Util.unicodeUnescapeString(line.substring(eq + 1).trim()));
}
}
}
return Optional.of(state);
} catch (IOException e) {
throw CONTAINER.failedReadingPersistentState(e, stateFile);
}
}
private File getStateFile(String scope) {
return new File(globalConfiguration.globalState().persistentLocation(), scope + ".state");
}
private File getLockFile() {
return new File(globalConfiguration.globalState().persistentLocation(), GLOBAL_SCOPE + ".lck");
}
@Override
public void registerStateProvider(GlobalStateProvider provider) {
this.stateProviders.add(provider);
if (globalState != null) {
provider.prepareForRestore(globalState);
}
}
}
| 8,435
| 35.838428
| 128
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/globalstate/impl/GlobalConfigurationManagerImpl.java
|
package org.infinispan.globalstate.impl;
import static org.infinispan.util.logging.Log.CONFIG;
import java.lang.invoke.MethodHandles;
import java.util.EnumSet;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.infinispan.Cache;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.commons.configuration.io.ConfigurationReader;
import org.infinispan.commons.util.concurrent.CompletableFutures;
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.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.globalstate.GlobalConfigurationManager;
import org.infinispan.globalstate.LocalConfigurationStorage;
import org.infinispan.globalstate.ScopedState;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier;
import org.infinispan.notifications.cachemanagerlistener.event.ConfigurationChangedEvent;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.security.PrincipalRoleMapper;
import org.infinispan.security.RolePermissionMapper;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.topology.LocalTopologyManager;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.concurrent.CompletionStages;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Implementation of {@link GlobalConfigurationManager}
*
* @author Tristan Tarrant
* @since 9.2
*/
@Scope(Scopes.GLOBAL)
public class GlobalConfigurationManagerImpl implements GlobalConfigurationManager {
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
public static final String CACHE_SCOPE = "cache";
public static final String TEMPLATE_SCOPE = "template";
@Inject
EmbeddedCacheManager cacheManager;
@Inject
LocalTopologyManager localTopologyManager;
@Inject
ConfigurationManager configurationManager;
@Inject
InternalCacheRegistry internalCacheRegistry;
@Inject
BlockingManager blockingManager;
@Inject
CacheManagerNotifier cacheManagerNotifier;
@Inject
RolePermissionMapper rolePermissionMapper;
@Inject
PrincipalRoleMapper principalRoleMapper;
private Cache<ScopedState, Object> stateCache;
private ParserRegistry parserRegistry;
private LocalConfigurationStorage localConfigurationManager;
static boolean isKnownScope(String scope) {
return CACHE_SCOPE.equals(scope) || TEMPLATE_SCOPE.equals(scope);
}
@Start
void start() {
switch (configurationManager.getGlobalConfiguration().globalState().configurationStorage()) {
case IMMUTABLE:
this.localConfigurationManager = new ImmutableLocalConfigurationStorage();
break;
case VOLATILE:
this.localConfigurationManager = new VolatileLocalConfigurationStorage();
break;
case OVERLAY:
this.localConfigurationManager = new OverlayLocalConfigurationStorage();
break;
default:
this.localConfigurationManager =
configurationManager.getGlobalConfiguration().globalState().configurationStorageClass().get();
break;
}
internalCacheRegistry.registerInternalCache(
CONFIG_STATE_CACHE_NAME,
new ConfigurationBuilder().build(),
EnumSet.of(InternalCacheRegistry.Flag.GLOBAL));
internalCacheRegistry.startInternalCaches();
parserRegistry = new ParserRegistry();
Set<String> staticCacheNames = new TreeSet<>(configurationManager.getDefinedCaches());
staticCacheNames.removeAll(internalCacheRegistry.getInternalCacheNames());
log.debugf("Starting user defined caches: %s", staticCacheNames);
for (String cacheName : staticCacheNames) {
SecurityActions.getCache(cacheManager, cacheName);
}
localConfigurationManager.initialize(cacheManager, configurationManager, blockingManager);
// Install the global state listener
GlobalConfigurationStateListener stateCacheListener = new GlobalConfigurationStateListener(this);
getStateCache().addListener(stateCacheListener);
// Load the persisted configurations
Map<String, Configuration> persistedTemplates = localConfigurationManager.loadAllTemplates();
Map<String, Configuration> persistedCaches = localConfigurationManager.loadAllCaches();
getStateCache().forEach((key, v) -> {
String scope = key.getScope();
if (isKnownScope(scope)) {
String name = key.getName();
CacheState state = (CacheState) v;
boolean cacheScope = CACHE_SCOPE.equals(scope);
Map<String, Configuration> map = cacheScope ? persistedCaches : persistedTemplates;
ensureClusterCompatibility(name, state, map);
CompletionStage<Void> future = cacheScope ? createCacheLocally(name, state) : createTemplateLocally(name, state);
CompletionStages.join(future);
}
});
EnumSet<CacheContainerAdmin.AdminFlag> adminFlags = EnumSet.noneOf(CacheContainerAdmin.AdminFlag.class);
// Create the templates
persistedTemplates.forEach((name, configuration) -> {
ensurePersistenceCompatibility(name, configuration);
// The template was permanent, it still needs to be
CompletionStages.join(getOrCreateTemplate(name, configuration, adminFlags));
});
// Create the caches
persistedCaches.forEach((name, configuration) -> {
ensurePersistenceCompatibility(name, configuration);
// The cache configuration was permanent, it still needs to be
CompletionStages.join(getOrCreateCache(name, configuration, adminFlags));
});
}
private void ensureClusterCompatibility(String name, CacheState state, Map<String, Configuration> configs) {
Configuration persisted = configs.get(name);
if (persisted != null) {
// Template value is not serialized, so buildConfiguration param is irrelevant
Configuration configuration = buildConfiguration(name, state.getConfiguration(), false);
if (!persisted.matches(configuration))
throw CONFIG.incompatibleClusterConfiguration(name, configuration, persisted);
}
}
private void ensurePersistenceCompatibility(String name, Configuration configuration) {
Configuration staticConfiguration = cacheManager.getCacheConfiguration(name);
if (staticConfiguration != null && !staticConfiguration.matches(configuration))
throw CONFIG.incompatiblePersistedConfiguration(name, configuration, staticConfiguration);
}
private void assertNameLength(String name) {
if (!ByteString.isValid(name)) {
throw CONFIG.invalidNameSize(name);
}
}
@Override
public Cache<ScopedState, Object> getStateCache() {
if (stateCache == null) {
stateCache = cacheManager.getCache(CONFIG_STATE_CACHE_NAME);
}
return stateCache;
}
@Override
public CompletionStage<Void> createTemplate(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
assertNameLength(name);
Cache<ScopedState, Object> cache = getStateCache();
ScopedState key = new ScopedState(TEMPLATE_SCOPE, name);
return cache.containsKeyAsync(key).thenCompose(exists -> {
if (exists)
throw CONFIG.configAlreadyDefined(name);
return cache.putAsync(key, new CacheState(null, parserRegistry.serialize(name, configuration), flags));
}).thenApply(v -> null);
}
@Override
public CompletionStage<Configuration> getOrCreateTemplate(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
assertNameLength(name);
localConfigurationManager.validateFlags(flags);
try {
final CacheState state = new CacheState(null, parserRegistry.serialize(name, configuration), flags);
return getStateCache().putIfAbsentAsync(new ScopedState(TEMPLATE_SCOPE, name), state).thenApply((v) -> configuration);
} catch (Exception e) {
throw CONFIG.configurationSerializationFailed(name, configuration, e);
}
}
@Override
public CompletionStage<Configuration> createCache(String cacheName, Configuration configuration,
EnumSet<CacheContainerAdmin.AdminFlag> flags) {
if (cacheManager.cacheExists(cacheName)) {
throw CONFIG.cacheExists(cacheName);
} else {
return getOrCreateCache(cacheName, configuration, flags);
}
}
@Override
public CompletionStage<Configuration> getOrCreateCache(String cacheName, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
return createCache(cacheName, null, configuration, flags);
}
@Override
public CompletionStage<Configuration> createCache(String cacheName, String template, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
if (cacheManager.cacheExists(cacheName)) {
throw CONFIG.cacheExists(cacheName);
} else {
return getOrCreateCache(cacheName, template, flags);
}
}
@Override
public CompletionStage<Configuration> getOrCreateCache(String cacheName, String template, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
Configuration configuration;
if (template == null) {
// The user has not specified a template, if a cache already exists just return it without checking for compatibility
if (cacheManager.cacheExists(cacheName))
return CompletableFuture.completedFuture(configurationManager.getConfiguration(cacheName, true));
else {
Optional<String> defaultCacheName = configurationManager.getGlobalConfiguration().defaultCacheName();
configuration = defaultCacheName.map(s -> configurationManager.getConfiguration(s, true)).orElse(null);
}
if (configuration == null) {
configuration = new ConfigurationBuilder().build();
}
} else {
configuration = configurationManager.getConfiguration(template, true);
if (configuration == null) {
throw CONFIG.undeclaredConfiguration(template, cacheName);
}
}
return createCache(cacheName, template, configuration, flags);
}
CompletionStage<Configuration> createCache(String cacheName, String template, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
assertNameLength(cacheName);
localConfigurationManager.validateFlags(flags);
final CacheState state;
try {
state = new CacheState(template, parserRegistry.serialize(cacheName, configuration), flags);
} catch (Exception e) {
throw CONFIG.configurationSerializationFailed(cacheName, configuration, e);
}
if (flags.contains(CacheContainerAdmin.AdminFlag.UPDATE)) {
if (internalCacheRegistry.isInternalCache(cacheName)) {
throw CONFIG.cannotUpdateInternalCache(cacheName);
}
return getStateCache().putAsync(new ScopedState(CACHE_SCOPE, cacheName), state)
.thenApply((v) -> configuration);
} else {
return getStateCache().putIfAbsentAsync(new ScopedState(CACHE_SCOPE, cacheName), state)
.thenApply((v) -> configuration);
}
}
CompletionStage<Void> createTemplateLocally(String name, CacheState state) {
Configuration configuration = buildConfiguration(name, state.getConfiguration(), true);
return createTemplateLocally(name, configuration, state.getFlags());
}
CompletionStage<Void> createTemplateLocally(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
log.debugf("Creating template %s from global state", name);
return localConfigurationManager.createTemplate(name, configuration, flags)
.thenCompose(v -> cacheManagerNotifier.notifyConfigurationChanged(ConfigurationChangedEvent.EventType.CREATE, "template", name))
.toCompletableFuture();
}
CompletionStage<Void> createCacheLocally(String name, CacheState state) {
Configuration configuration = buildConfiguration(name, state.getConfiguration(), false);
return createCacheLocally(name, state.getTemplate(), configuration, state.getFlags());
}
CompletionStage<Void> createCacheLocally(String name, String template, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
log.debugf("Creating cache %s from global state", name);
return localConfigurationManager.createCache(name, template, configuration, flags)
.thenCompose(v -> cacheManagerNotifier.notifyConfigurationChanged(ConfigurationChangedEvent.EventType.CREATE, "cache", name))
.toCompletableFuture();
}
CompletionStage<Void> validateConfigurationUpdateLocally(String name, CacheState state) {
log.debugf("Validating configuration %s from global state", name);
Configuration configuration = buildConfiguration(name, state.getConfiguration(), false);
return localConfigurationManager.validateConfigurationUpdate(name, configuration, state.getFlags());
}
CompletionStage<Void> updateConfigurationLocally(String name, CacheState state) {
log.debugf("Updating configuration %s from global state", name);
Configuration configuration = buildConfiguration(name, state.getConfiguration(), false);
return localConfigurationManager.updateConfiguration(name, configuration, state.getFlags())
.thenCompose(v -> cacheManagerNotifier.notifyConfigurationChanged(ConfigurationChangedEvent.EventType.UPDATE, "cache", name));
}
private Configuration buildConfiguration(String name, String configStr, boolean template) {
Properties properties = new Properties(System.getProperties());
properties.put(CacheParser.IGNORE_DUPLICATES, true);
ConfigurationReader reader = ConfigurationReader.from(configStr).withProperties(properties).build();
ConfigurationBuilderHolder builderHolder = parserRegistry.parse(reader, configurationManager.toBuilderHolder());
return builderHolder.getNamedConfigurationBuilders().get(name).template(template).build(configurationManager.getGlobalConfiguration());
}
@Override
public CompletionStage<Void> removeCache(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
ScopedState cacheScopedState = new ScopedState(CACHE_SCOPE, name);
if (getStateCache().containsKey(cacheScopedState)) {
try {
localTopologyManager.setCacheRebalancingEnabled(name, false);
} catch (Exception e) {
// Ignore
}
return getStateCache().removeAsync(cacheScopedState).thenCompose(r -> CompletableFutures.completedNull());
} else {
return localConfigurationManager.removeCache(name, flags);
}
}
@Override
public CompletionStage<Void> removeTemplate(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) {
return getStateCache().removeAsync(new ScopedState(TEMPLATE_SCOPE, name)).thenCompose((r) -> CompletableFutures.completedNull());
}
CompletionStage<Void> removeCacheLocally(String name) {
return localConfigurationManager.removeCache(name, EnumSet.noneOf(CacheContainerAdmin.AdminFlag.class)).thenCompose(v -> cacheManagerNotifier.notifyConfigurationChanged(ConfigurationChangedEvent.EventType.REMOVE, "cache", name));
}
CompletionStage<Void> removeTemplateLocally(String name) {
return localConfigurationManager.removeTemplate(name, EnumSet.noneOf(CacheContainerAdmin.AdminFlag.class)).thenCompose(v -> cacheManagerNotifier.notifyConfigurationChanged(ConfigurationChangedEvent.EventType.REMOVE, "template", name));
}
}
| 16,558
| 45.64507
| 241
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/AuditLogger.java
|
package org.infinispan.security;
import javax.security.auth.Subject;
/**
* AuditLogger.
*
* @author Tristan Tarrant
* @since 7.0
*/
public interface AuditLogger {
void audit(Subject subject, AuditContext context, String contextName, AuthorizationPermission permission, AuditResponse response);
}
| 306
| 20.928571
| 133
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/package-info.java
|
/**
* Security API.
*
* @api.public
*/
package org.infinispan.security;
| 76
| 10
| 32
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/Role.java
|
package org.infinispan.security;
import java.util.Collection;
import org.infinispan.security.impl.CacheRoleImpl;
/**
* A role to permission mapping.
*
* @author Tristan Tarrant
* @since 7.0
*/
public interface Role {
/**
* Returns the name of this role
*/
String getName();
/**
* Returns the list of permissions associated with this role
*/
Collection<AuthorizationPermission> getPermissions();
/**
* Returns a pre-computed access mask which contains the permissions specified by this role
*/
int getMask();
/**
* Whether this role can be implicitly inherited.
*/
boolean isInheritable();
static Role newRole(String name, boolean inheritable, AuthorizationPermission... authorizationPermissions) {
return new CacheRoleImpl(name, inheritable, authorizationPermissions);
}
}
| 853
| 21.473684
| 111
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/GroupPrincipal.java
|
package org.infinispan.security;
import java.security.Principal;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.0
**/
public class GroupPrincipal implements Principal {
private final String name;
public GroupPrincipal(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public String toString() {
return "RolePrincipal{" +
"name='" + name + '\'' +
'}';
}
}
| 504
| 17.035714
| 57
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/MutablePrincipalRoleMapper.java
|
package org.infinispan.security;
import java.util.Set;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public interface MutablePrincipalRoleMapper extends PrincipalRoleMapper {
void grant(String roleName, String principalName);
void deny(String roleName, String principalName);
Set<String> list(String principalName);
String listAll();
}
| 389
| 20.666667
| 73
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/CachePermission.java
|
package org.infinispan.security;
import java.security.Permission;
import java.security.PermissionCollection;
/**
* CachePermission.
*
* @author Tristan Tarrant
* @since 7.0
*/
public final class CachePermission extends Permission {
private static final long serialVersionUID = 9120524408585262253L;
private final AuthorizationPermission authzPermission;
public CachePermission(String name) {
this(AuthorizationPermission.valueOf(name));
}
public CachePermission(AuthorizationPermission perm) {
super(perm.toString());
authzPermission = perm;
}
@Override
public boolean implies(Permission permission) {
if ((permission == null) || (permission.getClass() != getClass()))
return false;
CachePermission that = (CachePermission) permission;
return this.authzPermission.implies(that.authzPermission);
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if ((obj == null) || (obj.getClass() != getClass()))
return false;
CachePermission that = (CachePermission) obj;
return this.authzPermission == that.authzPermission;
}
@Override
public int hashCode() {
return authzPermission.hashCode();
}
@Override
public String getActions() {
return "";
}
public PermissionCollection newPermissionCollection() {
return new CachePermissionCollection();
}
public AuthorizationPermission getAuthorizationPermission() {
return authzPermission;
}
}
| 1,544
| 23.140625
| 72
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/MutableRolePermissionMapper.java
|
package org.infinispan.security;
import java.util.concurrent.CompletionStage;
/**
* A {@link RolePermissionMapper} with the ability to add/remove roles at runtime
*
* @since 14.0
**/
public interface MutableRolePermissionMapper extends RolePermissionMapper {
/**
* Adds a new role
* @param role the role
*/
CompletionStage<Void> addRole(Role role);
/**
* Removes a role
* @param role the name of the role to be removed
* @return true if a role with the supplied name was found and removed
*/
CompletionStage<Boolean> removeRole(String role);
}
| 591
| 23.666667
| 81
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/PrincipalRoleMapper.java
|
package org.infinispan.security;
import java.security.Principal;
import java.util.Set;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* PrincipalRoleMapper.
*
* @author Tristan Tarrant
* @since 7.0
*/
@Scope(Scopes.GLOBAL)
public interface PrincipalRoleMapper {
/**
* Maps a principal name to a set of role names. The principal name depends on
* the source of the principal itself. For example, in LDAP a Principal
* might use the Distinguished Name format (DN). The mapper should
* return null if it does not recognize the principal.
*
* @param principal
* @return list of roles the principal belongs to
*/
Set<String> principalToRoles(Principal principal);
/**
* Sets the context for this {@link PrincipalRoleMapper}
*
* @param context
*/
default void setContext(PrincipalRoleMapperContext context) {}
}
| 925
| 25.457143
| 81
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/PrincipalRoleMapperContext.java
|
package org.infinispan.security;
/**
* PrincipalRoleMapperContext.
*
* @author Tristan Tarrant
* @since 7.0
* @deprecated since 14.0. To be removed in 17.0. Use {@link AuthorizationMapperContext} instead
*/
@Deprecated
public interface PrincipalRoleMapperContext extends AuthorizationMapperContext {
}
| 309
| 22.846154
| 96
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/AuditResponse.java
|
package org.infinispan.security;
public enum AuditResponse {
ALLOW,
DENY,
ERROR,
INFO
}
| 101
| 10.333333
| 32
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/Security.java
|
package org.infinispan.security;
import java.security.Principal;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.security.auth.Subject;
import org.infinispan.commons.jdkspecific.CallerId;
/**
* Security. A simple class to implement caller privileges without a security manager.
* <p>
* N.B. this uses the caller's {@link Package}, this can easily be subverted by placing the calling code within the
* org.infinispan hierarchy. For most purposes, however, this is ok.
*
* @author Tristan Tarrant
* @since 7.0
*/
public final class Security {
private static final ThreadLocal<Boolean> PRIVILEGED = ThreadLocal.withInitial(() -> Boolean.FALSE);
/*
* We don't override initialValue because we don't want to allocate the ArrayDeque if we just want to check if a
* Subject has been set.
*/
private static final ThreadLocal<Deque<Subject>> SUBJECT = new InheritableThreadLocal<>() {
@Override
protected Deque<Subject> childValue(Deque<Subject> parentValue) {
return parentValue == null ? null : new ArrayDeque<>(parentValue);
}
};
private static boolean isTrustedClass(Class<?> klass) {
// TODO: implement a better way
String packageName = klass.getPackage().getName();
return packageName.startsWith("org.infinispan") ||
packageName.startsWith("org.jboss.as.clustering.infinispan");
}
public static <T> T doPrivileged(Supplier<T> action) {
if (!isPrivileged() && isTrustedClass(CallerId.getCallerClass(3))) {
try {
PRIVILEGED.set(true);
return action.get();
} finally {
PRIVILEGED.remove();
}
} else {
return action.get();
}
}
public static void doPrivileged(Runnable action) {
if (!isPrivileged() && isTrustedClass(CallerId.getCallerClass(3))) {
try {
PRIVILEGED.set(true);
action.run();
} finally {
PRIVILEGED.remove();
}
} else {
action.run();
}
}
private static Deque<Subject> pre(Subject subject) {
if (subject == null) {
return null;
}
Deque<Subject> stack = SUBJECT.get();
if (stack == null) {
stack = new ArrayDeque<>(3);
SUBJECT.set(stack);
}
stack.push(subject);
return stack;
}
private static void post(Subject subject, Deque<Subject> stack) {
if (subject != null) {
stack.pop();
if (stack.isEmpty()) {
SUBJECT.remove();
}
}
}
public static void doAs(final Subject subject, final Runnable action) {
Deque<Subject> stack = pre(subject);
try {
action.run();
} finally {
post(subject, stack);
}
}
public static <T> T doAs(final Subject subject, final Supplier<T> action) {
Deque<Subject> stack = pre(subject);
try {
return action.get();
} finally {
post(subject, stack);
}
}
public static <T, R> R doAs(final Subject subject, Function<T, R> function, T t) {
Deque<Subject> stack = pre(subject);
try {
return function.apply(t);
} finally {
post(subject, stack);
}
}
public static <T, U, R> R doAs(final Subject subject, BiFunction<T, U, R> function, T t, U u) {
Deque<Subject> stack = pre(subject);
try {
return function.apply(t, u);
} finally {
post(subject, stack);
}
}
public static boolean isPrivileged() {
return PRIVILEGED.get();
}
/**
* If using {@link Security#doAs(Subject, Runnable)} or {@link Security#doAs(Subject, Function, Object)} or {@link Security#doAs(Subject, BiFunction, Object, Object)},
* returns the {@link Subject} associated with the current thread otherwise it returns
* null.
*/
public static Subject getSubject() {
Deque<Subject> subjects = SUBJECT.get();
if (subjects != null && !subjects.isEmpty()) {
return subjects.peek();
} else {
return null;
}
}
/**
* Returns the first principal of a subject
*/
public static Principal getSubjectUserPrincipal(Subject s) {
if (s != null && !s.getPrincipals().isEmpty()) {
return s.getPrincipals().iterator().next();
}
return null;
}
public static String getSubjectUserPrincipalName(Subject s) {
if (s != null && !s.getPrincipals().isEmpty()) {
return s.getPrincipals().iterator().next().getName();
}
return null;
}
/**
* A simplified version of Subject.toString() with the following advantages:
* <ul>
* <li>only lists principals, ignoring credentials</li>
* <li>uses a compact, single-line format</li>
* <li>does not use synchronization</li>
* <li>does not use i18n messages</li>
* </ul></uk>
* @param subject
* @return
*/
public static String toString(Subject subject) {
StringBuilder sb = new StringBuilder("Subject: [");
boolean comma = false;
for(Principal p : subject.getPrincipals()) {
if (comma) {
sb.append(" ,");
}
sb.append(p.toString());
comma = true;
}
return sb.append(']').toString();
}
}
| 5,428
| 27.87766
| 171
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/AuthorizationPermission.java
|
package org.infinispan.security;
import org.infinispan.Cache;
import org.infinispan.commons.marshall.ProtoStreamTypeIds;
import org.infinispan.protostream.annotations.ProtoEnumValue;
import org.infinispan.protostream.annotations.ProtoTypeId;
/**
* AuthorizationPermission.
*
* @author Tristan Tarrant
* @since 7.0
*/
@ProtoTypeId(ProtoStreamTypeIds.AUTHORIZATION_PERMISSION)
public enum AuthorizationPermission {
/**
* Allows control of a cache's lifecycle (i.e. invoke {@link Cache#start()} and {@link Cache#stop()}
*/
@ProtoEnumValue(value = 1 << 0, name = "LIFECYCLE_PERMISSION")
LIFECYCLE(1 << 0),
/**
* Allows reading data from a cache
*/
@ProtoEnumValue(1 << 1)
READ(1 << 1),
/**
* Allows writing data to a cache
*/
@ProtoEnumValue(1 << 2)
WRITE(1 << 2),
/**
* Allows performing task execution (e.g. cluster executor, tasks) on a cache
*/
@ProtoEnumValue(1 << 3)
EXEC(1 << 3),
/**
* Allows attaching listeners to a cache
*/
@ProtoEnumValue(1 << 4)
LISTEN(1 << 4),
/**
* Allows bulk-read operations (e.g. {@link Cache#keySet()}) on a cache
*/
@ProtoEnumValue(1 << 5)
BULK_READ(1 << 5),
/**
* Allows bulk-write operations (e.g. {@link Cache#clear()}) on a cache
*/
@ProtoEnumValue(1 << 6)
BULK_WRITE(1 << 6),
/**
* Allows performing "administrative" operations on a cache
*/
@ProtoEnumValue(1 << 7)
ADMIN(1 << 7),
/**
* Allows creation of resources (caches, counters, schemas, tasks)
*/
@ProtoEnumValue(1 << 8)
CREATE(1 << 8),
/**
* Allows retrieval of stats
*/
@ProtoEnumValue(1 << 9)
MONITOR(1 << 9),
/**
* Aggregate permission which implies all the others
*/
@ProtoEnumValue(Integer.MAX_VALUE)
ALL(Integer.MAX_VALUE),
/**
* Aggregate permission which implies all read permissions
*/
@ProtoEnumValue((1 << 1) + (1 << 5))
ALL_READ(READ.getMask() + BULK_READ.getMask()),
/**
* Aggregate permission which implies all write permissions
*/
@ProtoEnumValue((1 << 2) + (1 << 6))
ALL_WRITE(WRITE.getMask() + BULK_WRITE.getMask()),
/**
* No permissions
*/
@ProtoEnumValue
NONE(0);
private final int mask;
private final CachePermission securityPermission;
AuthorizationPermission(int mask) {
this.mask = mask;
securityPermission = new CachePermission(this);
}
public int getMask() {
return mask;
}
public CachePermission getSecurityPermission() {
return securityPermission;
}
public boolean matches(int mask) {
return ((this.mask & mask) == this.mask);
}
public boolean implies(AuthorizationPermission that) {
return ((this.mask & that.mask) == that.mask);
}
}
| 2,780
| 24.054054
| 103
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/AuthorizationManager.java
|
package org.infinispan.security;
import java.util.EnumSet;
import javax.security.auth.Subject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* The AuthorizationManager is a cache-scoped component which verifies that the {@link Subject}
* associated with the current thread, or explicitly specified, has the requested permissions.
*
* @author Tristan Tarrant
* @since 7.0
*/
@Scope(Scopes.NAMED_CACHE)
public interface AuthorizationManager {
/**
* Verifies that the {@link Subject} associated with the current thread
* has the requested permission. A {@link SecurityException} is thrown otherwise.
*/
void checkPermission(AuthorizationPermission permission);
/**
* Verifies that the {@link Subject} has the requested permission. A {@link SecurityException} is thrown otherwise.
*/
void checkPermission(Subject subject, AuthorizationPermission permission);
/**
* Verifies that the {@link Subject} associated with the current thread
* has the requested permission and role. A {@link SecurityException} is thrown otherwise.
*/
void checkPermission(AuthorizationPermission permission, String role);
/**
* Verifies that the {@link Subject} has the requested permission and role.
* A {@link SecurityException} is thrown otherwise.
*/
void checkPermission(Subject subject, AuthorizationPermission permission, String role);
/**
* Returns the permissions that the specified {@link Subject} has for the cache
*/
EnumSet<AuthorizationPermission> getPermissions(Subject subject);
/**
* Returns the permission required to write to the resource associated with this AuthorizationManager.
*/
AuthorizationPermission getWritePermission();
}
| 1,786
| 33.365385
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/AuditContext.java
|
package org.infinispan.security;
/**
* AuditContext.
*
* @author Tristan Tarrant
* @since 7.0
*/
public enum AuditContext {
CACHE("cache"),
CACHEMANAGER("container"),
COUNTER("counter"),
SERVER("server");
private final String name;
AuditContext(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
| 372
| 13.92
| 32
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/SecureCache.java
|
package org.infinispan.security;
import org.infinispan.AdvancedCache;
/**
* SecureCache.
*
* @author Tristan Tarrant
* @since 7.0
*/
public interface SecureCache<K, V> extends AdvancedCache<K, V> {
}
| 208
| 13.928571
| 64
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/RolePermissionMapper.java
|
package org.infinispan.security;
import java.util.Map;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* Maps roles to permissions
*
* @since 14.0
**/
@Scope(Scopes.GLOBAL)
public interface RolePermissionMapper {
/**
* Sets the context for this {@link RolePermissionMapper}
*
* @param context
*/
default void setContext(AuthorizationMapperContext context) {}
/**
* @param name the name of the role
* @return the {@link Role}
*/
Role getRole(String name);
/**
* @return all roles handled by this RolePermissionMapper
*/
Map<String, Role> getAllRoles();
/**
* @param name
* @return whether this permission mapper contains the named role
*/
boolean hasRole(String name);
}
| 801
| 19.564103
| 68
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/AuthorizationMapperContext.java
|
package org.infinispan.security;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* @since 14.0
**/
public interface AuthorizationMapperContext {
EmbeddedCacheManager getCacheManager();
}
| 202
| 17.454545
| 51
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/GlobalSecurityManager.java
|
package org.infinispan.security;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* GlobalSecurityManager.
*
* @author Tristan Tarrant
* @since 8.1
*/
@Scope(Scopes.GLOBAL)
public interface GlobalSecurityManager {
/**
* Returns the global ACL cache
*/
<K, V> Map<K, V> globalACLCache();
/**
* Flushes the ACL cache for this node
* @return
*/
CompletionStage<Void> flushGlobalACLCache();
void flushLocalACLCache();
}
| 577
| 17.645161
| 47
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/CachePermissionCollection.java
|
package org.infinispan.security;
import static org.infinispan.util.logging.Log.SECURITY;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
/**
* CachePermissionCollection.
*
* @author Tristan Tarrant
* @since 7.0
*/
public class CachePermissionCollection extends PermissionCollection {
private static final long serialVersionUID = -3709477547317792941L;
private final List<Permission> perms;
private int mask = 0;
public CachePermissionCollection() {
perms = new ArrayList<>();
}
@Override
public void add(Permission permission) {
if (permission.getClass() != CachePermission.class)
throw SECURITY.invalidPermission(permission);
if (isReadOnly())
throw SECURITY.readOnlyPermissionCollection();
CachePermission p = (CachePermission)permission;
synchronized (this) {
perms.add(p);
mask |= p.getAuthorizationPermission().getMask();
}
}
@Override
public boolean implies(Permission permission) {
if (permission == null || !permission.getClass().equals(CachePermission.class))
return false;
CachePermission p = (CachePermission)permission;
return p.getAuthorizationPermission().matches(mask);
}
@Override
public Enumeration<Permission> elements() {
synchronized (this) {
return Collections.enumeration(perms);
}
}
}
| 1,520
| 24.779661
| 85
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/audit/NullAuditLogger.java
|
package org.infinispan.security.audit;
import javax.security.auth.Subject;
import org.infinispan.security.AuditContext;
import org.infinispan.security.AuditLogger;
import org.infinispan.security.AuditResponse;
import org.infinispan.security.AuthorizationPermission;
/**
* NullAuditLogger. A simple {@link AuditLogger} which drops all audit messages
*
* @author Tristan Tarrant
* @since 7.0
* @api.public
*/
public class NullAuditLogger implements AuditLogger {
@Override
public void audit(Subject subject, AuditContext context, String contextName, AuthorizationPermission permission,
AuditResponse response) {
}
@Override
public boolean equals(Object obj) {
return obj instanceof NullAuditLogger;
}
}
| 745
| 24.724138
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/audit/LoggingAuditLogger.java
|
package org.infinispan.security.audit;
import javax.security.auth.Subject;
import org.infinispan.security.AuditContext;
import org.infinispan.security.AuditLogger;
import org.infinispan.security.AuditResponse;
import org.infinispan.security.AuthorizationPermission;
import org.infinispan.security.Security;
import org.infinispan.security.impl.AuditMessages;
import org.jboss.logging.Logger;
/**
* LoggingAuditLogger. A simple {@link AuditLogger} which send audit messages to a named
* logger "org.infinispan.AUDIT"
*
* @author Tristan Tarrant
* @since 7.0
* @api.public
*/
public class LoggingAuditLogger implements AuditLogger {
static final AuditMessages auditLog = Logger.getMessageLogger(AuditMessages.class, "org.infinispan.AUDIT");
@Override
public void audit(Subject subject, AuditContext context, String contextName, AuthorizationPermission permission,
AuditResponse response) {
auditLog.auditMessage(response, Security.getSubjectUserPrincipal(subject), permission, context, contextName);
}
@Override
public boolean equals(Object obj) {
return obj instanceof LoggingAuditLogger;
}
}
| 1,145
| 31.742857
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/GetUnwrappedCacheAction.java
|
package org.infinispan.security.actions;
import java.util.function.Supplier;
import org.infinispan.Cache;
import org.infinispan.security.impl.SecureCacheImpl;
/**
* GetUnwrappedCacheAction.
*
* @author Tristan Tarrant
* @since 12.1
*/
public class GetUnwrappedCacheAction<A extends Cache<K, V>, K, V> implements Supplier<A> {
private final Cache<K, V> cache;
public GetUnwrappedCacheAction(Cache<K, V> cache) {
this.cache = cache;
}
@Override
public A get() {
if (cache instanceof SecureCacheImpl) {
return (A) ((SecureCacheImpl) cache).getDelegate();
} else {
return (A) cache.getAdvancedCache();
}
}
}
| 676
| 20.15625
| 90
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/CacheContainsKeyAsyncAction.java
|
package org.infinispan.security.actions;
import java.util.concurrent.CompletionStage;
import org.infinispan.AdvancedCache;
/**
* @since 14.0
*/
public class CacheContainsKeyAsyncAction<K> extends AbstractAdvancedCacheAction<CompletionStage<Boolean>> {
private final K key;
public CacheContainsKeyAsyncAction(AdvancedCache<?, ?> cache, K key) {
super(cache);
this.key = key;
}
@Override
public CompletionStage<Boolean> get() {
return ((AdvancedCache<K, ?>) cache).containsKeyAsync(key);
}
}
| 534
| 21.291667
| 107
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/SecurityActions.java
|
package org.infinispan.security.actions;
import static org.infinispan.security.Security.doPrivileged;
import java.util.concurrent.CompletionStage;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.health.Health;
import org.infinispan.manager.ClusterExecutor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listenable;
import org.infinispan.persistence.manager.PersistenceManager;
import org.infinispan.security.AuthorizationManager;
import org.infinispan.security.AuthorizationPermission;
import org.infinispan.security.impl.Authorizer;
import org.infinispan.security.impl.SecureCacheImpl;
/**
* @since 15.0
**/
public class SecurityActions {
public static EmbeddedCacheManager getEmbeddedCacheManager(AdvancedCache<?, ?> cache) {
return doPrivileged(new GetEmbeddedCacheManagerAction(cache));
}
public static GlobalComponentRegistry getGlobalComponentRegistry(EmbeddedCacheManager cacheManager) {
return doPrivileged(cacheManager::getGlobalComponentRegistry);
}
public static GlobalConfiguration getCacheManagerConfiguration(EmbeddedCacheManager cacheManager) {
return doPrivileged(cacheManager::getCacheManagerConfiguration);
}
public static <A extends Cache<K,V>, K, V> A getUnwrappedCache(Cache<K, V> cache) {
return doPrivileged(new GetUnwrappedCacheAction<>(cache));
}
public static <A extends Cache<K,V>, K, V> A getUnwrappedCache(EmbeddedCacheManager cacheManager, String cacheName) {
return doPrivileged(new GetUnwrappedNameCacheAction<>(cacheManager, cacheName));
}
public static void defineConfiguration(final EmbeddedCacheManager cacheManager, final String cacheName, final Configuration configurationOverride) {
doPrivileged(new DefineConfigurationAction(cacheManager, cacheName, configurationOverride));
}
public static <A extends Cache<K,V>, K, V> A getCache(final EmbeddedCacheManager cacheManager, final String cacheName) {
return doPrivileged(new GetCacheAction<>(cacheManager, cacheName));
}
public static Configuration getCacheConfiguration(EmbeddedCacheManager cacheManager, String name) {
return doPrivileged(new GetCacheConfigurationFromManagerAction(cacheManager, name));
}
public static void stopCache(Cache<?, ?> cache) {
doPrivileged(() -> {
cache.stop();
return null;
});
}
public static ClusterExecutor getClusterExecutor(final Cache<?, ?> cache) {
GetClusterExecutorAction action = new GetClusterExecutorAction(cache);
return doPrivileged(action);
}
public static ClusterExecutor getClusterExecutor(final EmbeddedCacheManager cacheManager) {
GetClusterExecutorAction action = new GetClusterExecutorAction(cacheManager);
return doPrivileged(action);
}
public static void checkPermission(EmbeddedCacheManager cacheManager, AuthorizationPermission permission) {
Authorizer authorizer = getGlobalComponentRegistry(cacheManager).getComponent(Authorizer.class);
authorizer.checkPermission(permission);
}
public static ComponentRegistry getCacheComponentRegistry(AdvancedCache<?, ?> advancedCache) {
return doPrivileged(advancedCache::getComponentRegistry);
}
public static void undefineConfiguration(EmbeddedCacheManager cacheManager, String name) {
UndefineConfigurationAction action = new UndefineConfigurationAction(cacheManager, name);
doPrivileged(action);
}
public static AuthorizationManager getCacheAuthorizationManager(AdvancedCache<?, ?> cache) {
return doPrivileged(cache::getAuthorizationManager);
}
public static void addListener(EmbeddedCacheManager cacheManager, Object listener) {
doPrivileged(new AddCacheManagerListenerAction(cacheManager, listener));
}
public static CompletionStage<Void> removeListenerAsync(Listenable listenable, Object listener) {
RemoveListenerAsyncAction action = new RemoveListenerAsyncAction(listenable, listener);
return doPrivileged(action);
}
public static <K, V> CompletionStage<CacheEntry<K, V>> getCacheEntryAsync(final AdvancedCache<K, V> cache, K key) {
GetCacheEntryAsyncAction<K, V> action = new GetCacheEntryAsyncAction<>(cache, key);
return doPrivileged(action);
}
public static Configuration getCacheConfiguration(final AdvancedCache<?, ?> cache) {
return doPrivileged(cache::getCacheConfiguration);
}
public static <K> CompletionStage<Boolean> cacheContainsKeyAsync(AdvancedCache<K, ?> ac, K key) {
return doPrivileged(new CacheContainsKeyAsyncAction<>(ac, key));
}
public static void addCacheDependency(EmbeddedCacheManager cacheManager, String from, String to) {
doPrivileged(new AddCacheDependencyAction(cacheManager, from, to));
}
public static PersistenceManager getPersistenceManager(final EmbeddedCacheManager cacheManager, String cacheName) {
final GetPersistenceManagerAction action = new GetPersistenceManagerAction(cacheManager, cacheName);
return doPrivileged(action);
}
public static Health getHealth(final EmbeddedCacheManager cacheManager) {
GetCacheManagerHealthAction action = new GetCacheManagerHealthAction(cacheManager);
return doPrivileged(action);
}
public static CompletionStage<Void> addLoggerListenerAsync(EmbeddedCacheManager ecm, Object listener) {
return doPrivileged(new AddLoggerListenerAsyncAction(ecm, listener));
}
public static CompletionStage<Void> addListenerAsync(EmbeddedCacheManager cacheManager, Object listener) {
return doPrivileged(new AddCacheManagerListenerAsyncAction(cacheManager, listener));
}
public static CacheEntry<String, String> getCacheEntry(AdvancedCache<String, String> cache, String key) {
return doPrivileged(new GetCacheEntryAction<>(cache, key));
}
public static DistributionManager getDistributionManager(AdvancedCache<?, ?> cache) {
return doPrivileged(cache::getDistributionManager);
}
public static <K, V> AdvancedCache<K, V> anonymizeSecureCache(AdvancedCache<K, V> cache) {
return doPrivileged(() -> cache.transform(SecurityActions::unsetSubject));
}
private static <K, V> AdvancedCache<K, V> unsetSubject(AdvancedCache<K, V> cache) {
if (cache instanceof SecureCacheImpl) {
return new SecureCacheImpl<>(getUnwrappedCache(cache));
} else {
return cache;
}
}
public static <A extends Cache<K, V>, K, V> A getOrCreateCache(EmbeddedCacheManager cm, String configName, Configuration cfg) {
GetOrCreateCacheAction<A, K, V> action = new GetOrCreateCacheAction<>(cm, configName, cfg);
return doPrivileged(action);
}
public static Configuration getOrCreateTemplate(EmbeddedCacheManager cm, String configName, Configuration cfg) {
GetOrCreateTemplateAction action = new GetOrCreateTemplateAction(cm, configName, cfg);
return doPrivileged(action);
}
public static void stopManager(EmbeddedCacheManager cacheManager) {
doPrivileged(() -> {
cacheManager.stop();
return null;
});
}
}
| 7,494
| 41.344633
| 151
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/AddCacheDependencyAction.java
|
package org.infinispan.security.actions;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* AddCacheDependencyAction.
*
* @author Dan Berindei
* @since 10.0
*/
public class AddCacheDependencyAction extends AbstractEmbeddedCacheManagerAction<Void> {
private final String from;
private final String to;
public AddCacheDependencyAction(EmbeddedCacheManager cacheManager, String from, String to) {
super(cacheManager);
this.from = from;
this.to = to;
}
@Override
public Void get() {
cacheManager.addCacheDependency(from, to);
return null;
}
}
| 607
| 20.714286
| 95
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/AddCacheManagerListenerAsyncAction.java
|
package org.infinispan.security.actions;
import java.util.concurrent.CompletionStage;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* CacheManagerAddListenerAction.
*
* @since 14.0
*/
public class AddCacheManagerListenerAsyncAction extends AbstractEmbeddedCacheManagerAction<CompletionStage<Void>> {
private final Object listener;
public AddCacheManagerListenerAsyncAction(EmbeddedCacheManager cacheManager, Object listener) {
super(cacheManager);
this.listener = listener;
}
@Override
public CompletionStage<Void> get() {
return cacheManager.addListenerAsync(listener);
}
}
| 632
| 22.444444
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/AbstractAdvancedCacheAction.java
|
package org.infinispan.security.actions;
import java.util.function.Supplier;
import org.infinispan.AdvancedCache;
/**
* AbstractAdvancedCacheAction. A helper abstract for writing {@link Supplier}s which require an {@link AdvancedCache}
*
* @author Tristan Tarrant
* @since 7.0
*/
abstract class AbstractAdvancedCacheAction<T> implements Supplier<T> {
final AdvancedCache<?, ?> cache;
public AbstractAdvancedCacheAction(AdvancedCache<?, ?> cache) {
this.cache = cache;
}
}
| 497
| 22.714286
| 118
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/RemoveListenerAsyncAction.java
|
package org.infinispan.security.actions;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import org.infinispan.notifications.Listenable;
/**
* removeListenerAsync action
*
* @author Dan Berindei
* @since 13.0
*/
public class RemoveListenerAsyncAction implements Supplier<CompletionStage<Void>> {
private final Listenable listenable;
private final Object listener;
public RemoveListenerAsyncAction(Listenable listenable, Object listener) {
this.listenable = listenable;
this.listener = listener;
}
@Override
public CompletionStage<Void> get() {
return listenable.removeListenerAsync(listener);
}
}
| 694
| 22.166667
| 83
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/GetCacheEntryAsyncAction.java
|
package org.infinispan.security.actions;
import java.util.concurrent.CompletionStage;
import org.infinispan.AdvancedCache;
import org.infinispan.container.entries.CacheEntry;
/**
* GetCacheEntryAction.
*
* @author Tristan Tarrant
* @since 10.0
*/
public class GetCacheEntryAsyncAction<K, V> extends AbstractAdvancedCacheAction<CompletionStage<CacheEntry<K,V>>> {
private final K key;
public GetCacheEntryAsyncAction(AdvancedCache<?, ?> cache, K key) {
super(cache);
this.key = key;
}
@Override
public CompletionStage<CacheEntry<K, V>> get() {
return ((AdvancedCache<K, V>) cache).getCacheEntryAsync(key);
}
}
| 656
| 22.464286
| 115
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/GetClusterExecutorAction.java
|
package org.infinispan.security.actions;
import java.util.Objects;
import java.util.function.Supplier;
import org.infinispan.Cache;
import org.infinispan.manager.ClusterExecutor;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* GetClusterExecutorAction.
*
* @author Tristan Tarrant
* @since 7.0
*/
public class GetClusterExecutorAction implements Supplier<ClusterExecutor> {
private final Cache<?, ?> cache;
private final EmbeddedCacheManager cacheManager;
public GetClusterExecutorAction(Cache<?, ?> cache) {
this.cache = Objects.requireNonNull(cache);
this.cacheManager = null;
}
public GetClusterExecutorAction(EmbeddedCacheManager cacheManager) {
this.cache = null;
this.cacheManager = Objects.requireNonNull(cacheManager);
}
@Override
public ClusterExecutor get() {
EmbeddedCacheManager manager;
if (cache != null) {
manager = cache.getCacheManager();
} else {
manager = this.cacheManager;
}
return manager.executor();
}
}
| 1,049
| 23.418605
| 76
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/GetOrCreateTemplateAction.java
|
package org.infinispan.security.actions;
import java.util.function.Supplier;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* GetOrCreateCacheAction.
*
* @author Tristan Tarrant
* @since 12.1
*/
public class GetOrCreateTemplateAction implements Supplier<Configuration> {
private final String cacheName;
private final EmbeddedCacheManager cacheManager;
private final Configuration configuration;
public GetOrCreateTemplateAction(EmbeddedCacheManager cacheManager, String cacheName, Configuration configuration) {
this.cacheManager = cacheManager;
this.cacheName = cacheName;
this.configuration = configuration;
}
@Override
public Configuration get() {
return cacheManager.administration().getOrCreateTemplate(cacheName, configuration);
}
}
| 864
| 26.903226
| 119
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/DefineConfigurationAction.java
|
package org.infinispan.security.actions;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* DefineConfigurationAction.
*
* @author Tristan Tarrant
* @since 7.0
*/
public final class DefineConfigurationAction implements Runnable {
private final EmbeddedCacheManager cacheManager;
private final String cacheName;
private final Configuration configurationOverride;
public DefineConfigurationAction(EmbeddedCacheManager cacheManager, String cacheName, Configuration configurationOverride) {
this.cacheManager = cacheManager;
this.cacheName = cacheName;
this.configurationOverride = configurationOverride;
}
@Override
public void run() {
cacheManager.defineConfiguration(cacheName, configurationOverride);
}
}
| 828
| 26.633333
| 127
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/UndefineConfigurationAction.java
|
package org.infinispan.security.actions;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* UndefineConfigurationAction.
*
* @author Tristan Tarrant
* @since 9.0
*/
public final class UndefineConfigurationAction implements Runnable {
private final EmbeddedCacheManager cacheManager;
private final String cacheName;
public UndefineConfigurationAction(EmbeddedCacheManager cacheManager, String cacheName) {
this.cacheManager = cacheManager;
this.cacheName = cacheName;
}
@Override
public void run() {
cacheManager.undefineConfiguration(cacheName);
}
}
| 607
| 21.518519
| 92
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/GetCacheManagerHealthAction.java
|
package org.infinispan.security.actions;
import org.infinispan.health.Health;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* @since 10.0
*/
public class GetCacheManagerHealthAction extends AbstractEmbeddedCacheManagerAction<Health> {
public GetCacheManagerHealthAction(EmbeddedCacheManager cacheManager) {
super(cacheManager);
}
@Override
public Health get() {
return cacheManager.getHealth();
}
}
| 441
| 22.263158
| 93
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/AbstractEmbeddedCacheManagerAction.java
|
package org.infinispan.security.actions;
import java.util.function.Supplier;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* AbstractEmbeddedCacheManagerAction. A helper abstract for writing security-sensitive {@link Supplier}s which require an {@link EmbeddedCacheManager}
*
* @author Tristan Tarrant
* @since 7.0
*/
abstract class AbstractEmbeddedCacheManagerAction<T> implements Supplier<T> {
final EmbeddedCacheManager cacheManager;
public AbstractEmbeddedCacheManagerAction(EmbeddedCacheManager cacheManager) {
this.cacheManager = cacheManager;
}
}
| 589
| 27.095238
| 151
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/GetUnwrappedNameCacheAction.java
|
package org.infinispan.security.actions;
import java.util.function.Supplier;
import org.infinispan.Cache;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.security.impl.SecureCacheImpl;
/**
* GetUnwrappedNameCacheAction.
*
* @since 15.0
*/
public class GetUnwrappedNameCacheAction<A extends Cache<K, V>, K, V> implements Supplier<A> {
private final String cacheName;
private final EmbeddedCacheManager cacheManager;
public GetUnwrappedNameCacheAction(EmbeddedCacheManager cacheManager, String cacheName) {
this.cacheManager = cacheManager;
this.cacheName = cacheName;
}
@Override
public A get() {
Cache<?, ?> cache = cacheManager.getCache(cacheName);
if (cache instanceof SecureCacheImpl) {
return (A) ((SecureCacheImpl) cache).getDelegate();
} else {
return (A) cache.getAdvancedCache();
}
}
}
| 905
| 25.647059
| 94
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/AddCacheManagerListenerAction.java
|
package org.infinispan.security.actions;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* CacheManagerAddListenerAction.
*
* @author Tristan Tarrant
* @since 7.0
*/
public class AddCacheManagerListenerAction extends AbstractEmbeddedCacheManagerAction<Void> {
private final Object listener;
public AddCacheManagerListenerAction(EmbeddedCacheManager cacheManager, Object listener) {
super(cacheManager);
this.listener = listener;
}
@Override
public Void get() {
cacheManager.addListener(listener);
return null;
}
}
| 575
| 20.333333
| 93
|
java
|
null |
infinispan-main/core/src/main/java/org/infinispan/security/actions/GetCacheAction.java
|
package org.infinispan.security.actions;
import java.util.function.Supplier;
import org.infinispan.Cache;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* GetCacheAction.
*
* @author Tristan Tarrant
* @since 7.0
*/
public class GetCacheAction<A extends Cache<K, V>, K, V> implements Supplier<A> {
private final String cacheName;
private final EmbeddedCacheManager cacheManager;
public GetCacheAction(EmbeddedCacheManager cacheManager, String cacheName) {
this.cacheManager = cacheManager;
this.cacheName = cacheName;
}
@Override
public A get() {
return (A)cacheManager.getCache(cacheName);
}
}
| 654
| 20.833333
| 81
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.