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/commons/all/src/main/java/org/infinispan/configuration/cache/XSiteStateTransferMode.java
|
package org.infinispan.configuration.cache;
/**
* Cross site state transfer mode.
*
* @author Pedro Ruivo
* @since 12.1
*/
public enum XSiteStateTransferMode {
/**
* Cross-site state transfer is triggered manually via CLI, JMX, or REST.
*/
MANUAL,
/**
* Cross-site state transfer is triggered automatically.
*/
AUTO;
private final static XSiteStateTransferMode[] CACHED = XSiteStateTransferMode.values();
public static XSiteStateTransferMode valueOf(int index) {
return CACHED[index];
}
}
| 540
| 20.64
| 90
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/package-info.java
|
/**
* Commons package
*
* @api.public
*/
package org.infinispan.commons;
| 77
| 10.142857
| 31
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/CacheException.java
|
package org.infinispan.commons;
/**
* Thrown when operations fail unexpectedly.
* <p/>
* Specific subclasses such as {@link org.infinispan.util.concurrent.TimeoutException} and {@link
* org.infinispan.commons.CacheConfigurationException} have more specific uses.
* <p/>
* Transactions: if a CacheException (including any subclasses) is thrown for an operation on a JTA transaction, then
* the transaction is marked for rollback.
*
* @author <a href="mailto:bela@jboss.org">Bela Ban</a>
* @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class CacheException extends RuntimeException {
/** The serialVersionUID */
private static final long serialVersionUID = -5704354545244956536L;
public CacheException() {
super();
}
public CacheException(Throwable cause) {
super(cause.getMessage(), cause);
}
public CacheException(String msg) {
super(msg);
}
public CacheException(String msg, Throwable cause) {
super(msg, cause);
}
public CacheException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| 1,250
| 28.785714
| 117
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/GlobalContextInitializer.java
|
package org.infinispan.commons;
import org.infinispan.commons.util.KeyValueWithPrevious;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
/**
* Interface used to initialise the global {@link org.infinispan.protostream.SerializationContext} using the specified Pojos,
* and the generated proto files and marshallers.
*
* @author Ryan Emerson
* @since 10.0
*/
@AutoProtoSchemaBuilder(
includeClasses = KeyValueWithPrevious.class,
schemaFileName = "global.commons.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.global.commons",
service = false
)
public interface GlobalContextInitializer extends SerializationContextInitializer {
GlobalContextInitializer INSTANCE = new GlobalContextInitializerImpl();
}
| 863
| 35
| 125
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/IllegalLifecycleStateException.java
|
package org.infinispan.commons;
/**
* This exception is thrown when the cache or cache manager does not have the
* right lifecycle state for operations to be called on it. Situations like
* this include when the cache is stopping or is stopped, when the cache
* manager is stopped...etc.
*
* @since 10.1 (prior was in org.infinispan package since 7.0)
*/
public class IllegalLifecycleStateException extends CacheException {
public IllegalLifecycleStateException() {
}
public IllegalLifecycleStateException(String s) {
super(s);
}
public IllegalLifecycleStateException(String message, Throwable cause) {
super(message, cause);
}
public IllegalLifecycleStateException(Throwable cause) {
super(cause.getMessage(), cause);
}
}
| 776
| 27.777778
| 77
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/CacheConfigurationException.java
|
package org.infinispan.commons;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* An exception that represents an error in the configuration. This could be a parsing error or a logical error
* involving clashing configuration options or missing mandatory configuration elements.
*
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik@jboss.org)</a>
*
* @since 4.0
*/
public class CacheConfigurationException extends CacheException {
/** The serialVersionUID */
private static final long serialVersionUID = -7103679310393205388L;
private static final Log log = LogFactory.getLog(CacheConfigurationException.class);
public CacheConfigurationException(Exception e) {
super(e.getMessage(), e);
}
public CacheConfigurationException(String string) {
super(string);
}
@Deprecated
public CacheConfigurationException(String string, String erroneousAttribute) {
super(string);
}
public CacheConfigurationException(String string, Throwable throwable) {
super(string, throwable);
}
@Deprecated
public List<String> getErroneousAttributes() {
return Collections.emptyList();
}
@Deprecated
public void addErroneousAttribute(String s) {
// Do nothing
}
public static Optional<RuntimeException> fromMultipleRuntimeExceptions(List<RuntimeException> exceptions) {
switch (exceptions.size()) {
case 0:
return Optional.empty();
case 1: {
RuntimeException e = exceptions.get(0);
return e instanceof CacheConfigurationException ? Optional.of(e) : Optional.of(new CacheConfigurationException(e));
}
default: {
CacheConfigurationException exception = log.multipleConfigurationValidationErrors();
exceptions.forEach(e -> exception.addSuppressed(e));
return Optional.of(exception);
}
}
}
}
| 2,047
| 29.567164
| 127
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/CacheListenerException.java
|
package org.infinispan.commons;
/**
* Wraps exceptions produced by listener implementations.
*
* @author Galder Zamarreño
* @since 6.0
*/
public class CacheListenerException extends CacheException {
public CacheListenerException() {
}
public CacheListenerException(Throwable cause) {
super(cause.getMessage(), cause);
}
public CacheListenerException(String msg) {
super(msg);
}
public CacheListenerException(String msg, Throwable cause) {
super(msg, cause);
}
}
| 515
| 18.111111
| 63
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/hash/MurmurHash3.java
|
package org.infinispan.commons.hash;
import java.io.ObjectInput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.Ids;
import org.infinispan.commons.marshall.WrappedBytes;
import org.infinispan.commons.marshall.exts.NoStateExternalizer;
import net.jcip.annotations.Immutable;
import net.jcip.annotations.ThreadSafe;
/**
* MurmurHash3 implementation in Java, based on Austin Appleby's <a href=
* "https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp"
* >original in C</a>
*
* Only implementing x64 version, because this should always be faster on 64 bit
* native processors, even 64 bit being ran with a 32 bit OS; this should also
* be as fast or faster than the x86 version on some modern 32 bit processors.
*
* @author Patrick McFarland
* @see <a href="http://sites.google.com/site/murmurhash/">MurmurHash website</a>
* @see <a href="http://en.wikipedia.org/wiki/MurmurHash">MurmurHash entry on Wikipedia</a>
* @since 5.0
*/
@ThreadSafe
@Immutable
public class MurmurHash3 implements Hash {
private final static MurmurHash3 instance = new MurmurHash3();
public static final byte INVALID_CHAR = (byte) '?';
public static MurmurHash3 getInstance() {
return instance;
}
private MurmurHash3() {
}
static class State {
long h1;
long h2;
long k1;
long k2;
long c1;
long c2;
}
static long getblock(byte[] key, int i) {
return
((key[i + 0] & 0x00000000000000FFL))
| ((key[i + 1] & 0x00000000000000FFL) << 8)
| ((key[i + 2] & 0x00000000000000FFL) << 16)
| ((key[i + 3] & 0x00000000000000FFL) << 24)
| ((key[i + 4] & 0x00000000000000FFL) << 32)
| ((key[i + 5] & 0x00000000000000FFL) << 40)
| ((key[i + 6] & 0x00000000000000FFL) << 48)
| ((key[i + 7] & 0x00000000000000FFL) << 56);
}
static void bmix(State state) {
state.k1 *= state.c1;
state.k1 = (state.k1 << 23) | (state.k1 >>> 64 - 23);
state.k1 *= state.c2;
state.h1 ^= state.k1;
state.h1 += state.h2;
state.h2 = (state.h2 << 41) | (state.h2 >>> 64 - 41);
state.k2 *= state.c2;
state.k2 = (state.k2 << 23) | (state.k2 >>> 64 - 23);
state.k2 *= state.c1;
state.h2 ^= state.k2;
state.h2 += state.h1;
state.h1 = state.h1 * 3 + 0x52dce729;
state.h2 = state.h2 * 3 + 0x38495ab5;
state.c1 = state.c1 * 5 + 0x7b7d159c;
state.c2 = state.c2 * 5 + 0x6bce6396;
}
static long fmix(long k) {
k ^= k >>> 33;
k *= 0xff51afd7ed558ccdL;
k ^= k >>> 33;
k *= 0xc4ceb9fe1a85ec53L;
k ^= k >>> 33;
return k;
}
/**
* Hash a value using the x64 128 bit variant of MurmurHash3
*
* @param key value to hash
* @param seed random value
* @return 128 bit hashed key, in an array containing two longs
*/
public static long[] MurmurHash3_x64_128(final byte[] key, final int seed) {
State state = new State();
state.h1 = 0x9368e53c2f6af274L ^ seed;
state.h2 = 0x586dcd208f7cd3fdL ^ seed;
state.c1 = 0x87c37b91114253d5L;
state.c2 = 0x4cf5ad432745937fL;
for (int i = 0; i < key.length / 16; i++) {
state.k1 = getblock(key, i * 2 * 8);
state.k2 = getblock(key, (i * 2 + 1) * 8);
bmix(state);
}
state.k1 = 0;
state.k2 = 0;
int tail = (key.length >>> 4) << 4;
switch (key.length & 15) {
case 15: state.k2 ^= (long) key[tail + 14] << 48;
case 14: state.k2 ^= (long) key[tail + 13] << 40;
case 13: state.k2 ^= (long) key[tail + 12] << 32;
case 12: state.k2 ^= (long) key[tail + 11] << 24;
case 11: state.k2 ^= (long) key[tail + 10] << 16;
case 10: state.k2 ^= (long) key[tail + 9] << 8;
case 9: state.k2 ^= key[tail + 8];
case 8: state.k1 ^= (long) key[tail + 7] << 56;
case 7: state.k1 ^= (long) key[tail + 6] << 48;
case 6: state.k1 ^= (long) key[tail + 5] << 40;
case 5: state.k1 ^= (long) key[tail + 4] << 32;
case 4: state.k1 ^= (long) key[tail + 3] << 24;
case 3: state.k1 ^= (long) key[tail + 2] << 16;
case 2: state.k1 ^= (long) key[tail + 1] << 8;
case 1: state.k1 ^= key[tail + 0];
bmix(state);
}
state.h2 ^= key.length;
state.h1 += state.h2;
state.h2 += state.h1;
state.h1 = fmix(state.h1);
state.h2 = fmix(state.h2);
state.h1 += state.h2;
state.h2 += state.h1;
return new long[] { state.h1, state.h2 };
}
/**
* Hash a value using the x64 64 bit variant of MurmurHash3
*
* @param key value to hash
* @param seed random value
* @return 64 bit hashed key
*/
public static long MurmurHash3_x64_64(final byte[] key, final int seed) {
// Exactly the same as MurmurHash3_x64_128, except it only returns state.h1
State state = new State();
state.h1 = 0x9368e53c2f6af274L ^ seed;
state.h2 = 0x586dcd208f7cd3fdL ^ seed;
state.c1 = 0x87c37b91114253d5L;
state.c2 = 0x4cf5ad432745937fL;
for (int i = 0; i < key.length / 16; i++) {
state.k1 = getblock(key, i * 2 * 8);
state.k2 = getblock(key, (i * 2 + 1) * 8);
bmix(state);
}
state.k1 = 0;
state.k2 = 0;
int tail = (key.length >>> 4) << 4;
switch (key.length & 15) {
case 15: state.k2 ^= (long) key[tail + 14] << 48;
case 14: state.k2 ^= (long) key[tail + 13] << 40;
case 13: state.k2 ^= (long) key[tail + 12] << 32;
case 12: state.k2 ^= (long) key[tail + 11] << 24;
case 11: state.k2 ^= (long) key[tail + 10] << 16;
case 10: state.k2 ^= (long) key[tail + 9] << 8;
case 9: state.k2 ^= key[tail + 8];
case 8: state.k1 ^= (long) key[tail + 7] << 56;
case 7: state.k1 ^= (long) key[tail + 6] << 48;
case 6: state.k1 ^= (long) key[tail + 5] << 40;
case 5: state.k1 ^= (long) key[tail + 4] << 32;
case 4: state.k1 ^= (long) key[tail + 3] << 24;
case 3: state.k1 ^= (long) key[tail + 2] << 16;
case 2: state.k1 ^= (long) key[tail + 1] << 8;
case 1: state.k1 ^= key[tail + 0];
bmix(state);
}
state.h2 ^= key.length;
state.h1 += state.h2;
state.h2 += state.h1;
state.h1 = fmix(state.h1);
state.h2 = fmix(state.h2);
state.h1 += state.h2;
state.h2 += state.h1;
return state.h1;
}
/**
* Hash a value using the x64 32 bit variant of MurmurHash3
*
* @param key value to hash
* @param seed random value
* @return 32 bit hashed key
*/
public static int MurmurHash3_x64_32(final byte[] key, final int seed) {
return (int) (MurmurHash3_x64_64(key, seed) >>> 32);
}
/**
* Hash a value using the x64 128 bit variant of MurmurHash3
*
* @param key value to hash
* @param seed random value
* @return 128 bit hashed key, in an array containing two longs
*/
public static long[] MurmurHash3_x64_128(final long[] key, final int seed) {
State state = new State();
state.h1 = 0x9368e53c2f6af274L ^ seed;
state.h2 = 0x586dcd208f7cd3fdL ^ seed;
state.c1 = 0x87c37b91114253d5L;
state.c2 = 0x4cf5ad432745937fL;
for (int i = 0; i < key.length / 2; i++) {
state.k1 = key[i * 2];
state.k2 = key[i * 2 + 1];
bmix(state);
}
long tail = key[key.length - 1];
// Key length is odd
if ((key.length & 1) == 1) {
state.k1 ^= tail;
bmix(state);
}
state.h2 ^= key.length * 8;
state.h1 += state.h2;
state.h2 += state.h1;
state.h1 = fmix(state.h1);
state.h2 = fmix(state.h2);
state.h1 += state.h2;
state.h2 += state.h1;
return new long[] { state.h1, state.h2 };
}
/**
* Hash a value using the x64 64 bit variant of MurmurHash3
*
* @param key value to hash
* @param seed random value
* @return 64 bit hashed key
*/
public static long MurmurHash3_x64_64(final long[] key, final int seed) {
// Exactly the same as MurmurHash3_x64_128, except it only returns state.h1
State state = new State();
state.h1 = 0x9368e53c2f6af274L ^ seed;
state.h2 = 0x586dcd208f7cd3fdL ^ seed;
state.c1 = 0x87c37b91114253d5L;
state.c2 = 0x4cf5ad432745937fL;
for (int i = 0; i < key.length / 2; i++) {
state.k1 = key[i * 2];
state.k2 = key[i * 2 + 1];
bmix(state);
}
long tail = key[key.length - 1];
if (key.length % 2 != 0) {
state.k1 ^= tail;
bmix(state);
}
state.h2 ^= key.length * 8;
state.h1 += state.h2;
state.h2 += state.h1;
state.h1 = fmix(state.h1);
state.h2 = fmix(state.h2);
state.h1 += state.h2;
state.h2 += state.h1;
return state.h1;
}
/**
* Hash a value using the x64 32 bit variant of MurmurHash3
*
* @param key value to hash
* @param seed random value
* @return 32 bit hashed key
*/
public static int MurmurHash3_x64_32(final long[] key, final int seed) {
return (int) (MurmurHash3_x64_64(key, seed) >>> 32);
}
@Override
public int hash(byte[] payload) {
return MurmurHash3_x64_32(payload, 9001);
}
/**
* Hashes a byte array efficiently.
*
* @param payload a byte array to hash
* @return a hash code for the byte array
*/
public static int hash(long[] payload) {
return MurmurHash3_x64_32(payload, 9001);
}
@Override
public int hash(int hashcode) {
// Obtained by inlining MurmurHash3_x64_32(byte[], 9001) and removing all the unused code
// (since we know the input is always 4 bytes and we only need 4 bytes of output)
byte b0 = (byte) hashcode;
byte b1 = (byte) (hashcode >>> 8);
byte b2 = (byte) (hashcode >>> 16);
byte b3 = (byte) (hashcode >>> 24);
State state = new State();
state.h1 = 0x9368e53c2f6af274L ^ 9001;
state.h2 = 0x586dcd208f7cd3fdL ^ 9001;
state.c1 = 0x87c37b91114253d5L;
state.c2 = 0x4cf5ad432745937fL;
state.k1 = 0;
state.k2 = 0;
state.k1 ^= (long) b3 << 24;
state.k1 ^= (long) b2 << 16;
state.k1 ^= (long) b1 << 8;
state.k1 ^= b0;
bmix(state);
state.h2 ^= 4;
state.h1 += state.h2;
state.h2 += state.h1;
state.h1 = fmix(state.h1);
state.h2 = fmix(state.h2);
state.h1 += state.h2;
state.h2 += state.h1;
return (int) (state.h1 >>> 32);
}
@Override
public int hash(Object o) {
if (o instanceof byte[])
return hash((byte[]) o);
else if (o instanceof WrappedBytes) {
return hash(((WrappedBytes) o).getBytes());
}
else if (o instanceof long[])
return hash((long[]) o);
else if (o instanceof String)
return hashString((String) o);
else
return hash(o.hashCode());
}
private int hashString(String s) {
return (int) (MurmurHash3_x64_64_String(s, 9001) >> 32);
}
private long MurmurHash3_x64_64_String(String s, long seed) {
// Exactly the same as MurmurHash3_x64_64, except it works directly on a String's chars
MurmurHash3.State state = new MurmurHash3.State();
state.h1 = 0x9368e53c2f6af274L ^ seed;
state.h2 = 0x586dcd208f7cd3fdL ^ seed;
state.c1 = 0x87c37b91114253d5L;
state.c2 = 0x4cf5ad432745937fL;
int byteLen = 0;
int stringLen = s.length();
for (int i = 0; i < stringLen; i++) {
char c1 = s.charAt(i);
int cp;
if (!Character.isSurrogate(c1)) {
cp = c1;
} else if (Character.isHighSurrogate(c1)){
if (i + 1 < stringLen) {
char c2 = s.charAt(i + 1);
if (Character.isLowSurrogate(c2)) {
i++;
cp = Character.toCodePoint(c1, c2);
} else {
cp = INVALID_CHAR;
}
} else {
cp = INVALID_CHAR;
}
} else {
cp = INVALID_CHAR;
}
if (cp <= 0x7f) {
addByte(state, (byte) cp, byteLen++);
} else if (cp <= 0x07ff) {
byte b1 = (byte) (0xc0 | (0x1f & (cp >> 6)));
byte b2 = (byte) (0x80 | (0x3f & cp));
addByte(state, b1, byteLen++);
addByte(state, b2, byteLen++);
} else if (cp <= 0xffff) {
byte b1 = (byte) (0xe0 | (0x0f & (cp >> 12)));
byte b2 = (byte) (0x80 | (0x3f & (cp >> 6)));
byte b3 = (byte) (0x80 | (0x3f & cp));
addByte(state, b1, byteLen++);
addByte(state, b2, byteLen++);
addByte(state, b3, byteLen++);
} else {
byte b1 = (byte) (0xf0 | (0x07 & (cp >> 18)));
byte b2 = (byte) (0x80 | (0x3f & (cp >> 12)));
byte b3 = (byte) (0x80 | (0x3f & (cp >> 6)));
byte b4 = (byte) (0x80 | (0x3f & cp));
addByte(state, b1, byteLen++);
addByte(state, b2, byteLen++);
addByte(state, b3, byteLen++);
addByte(state, b4, byteLen++);
}
}
long savedK1 = state.k1;
long savedK2 = state.k2;
state.k1 = 0;
state.k2 = 0;
switch (byteLen & 15) {
case 15:
state.k2 ^= (long) ((byte)(savedK2 >> 48)) << 48;
case 14:
state.k2 ^= (long) ((byte) (savedK2 >> 40)) << 40;
case 13:
state.k2 ^= (long) ((byte) (savedK2 >> 32)) << 32;
case 12:
state.k2 ^= (long) ((byte) (savedK2 >> 24)) << 24;
case 11:
state.k2 ^= (long) ((byte) (savedK2 >> 16)) << 16;
case 10:
state.k2 ^= (long) ((byte) (savedK2 >> 8)) << 8;
case 9:
state.k2 ^= ((byte) savedK2);
case 8:
state.k1 ^= (long) ((byte) (savedK1 >> 56)) << 56;
case 7:
state.k1 ^= (long) ((byte) (savedK1 >> 48)) << 48;
case 6:
state.k1 ^= (long) ((byte) (savedK1 >> 40)) << 40;
case 5:
state.k1 ^= (long) ((byte) (savedK1 >> 32)) << 32;
case 4:
state.k1 ^= (long) ((byte) (savedK1 >> 24)) << 24;
case 3:
state.k1 ^= (long) ((byte) (savedK1 >> 16)) << 16;
case 2:
state.k1 ^= (long) ((byte) (savedK1 >> 8)) << 8;
case 1:
state.k1 ^= ((byte) savedK1);
bmix(state);
}
state.h2 ^= byteLen;
state.h1 += state.h2;
state.h2 += state.h1;
state.h1 = fmix(state.h1);
state.h2 = fmix(state.h2);
state.h1 += state.h2;
state.h2 += state.h1;
return state.h1;
}
private void addByte(State state, byte b, int len) {
int shift = (len & 0x7) * 8;
long bb = (b & 0xffL) << shift;
if ((len & 0x8) == 0) {
state.k1 |= bb;
} else {
state.k2 |= bb;
if ((len & 0xf) == 0xf) {
bmix(state);
state.k1 = 0;
state.k2 = 0;
}
}
}
@Override
public boolean equals(Object other) {
return other != null && other.getClass() == getClass();
}
@Override
public int hashCode() {
return 0;
}
@Override
public String toString() {
return "MurmurHash3";
}
public static class Externalizer extends NoStateExternalizer<MurmurHash3> {
@Override
public Set<Class<? extends MurmurHash3>> getTypeClasses() {
return Collections.singleton(MurmurHash3.class);
}
@Override
public MurmurHash3 readObject(ObjectInput input) {
return instance;
}
@Override
public Integer getId() {
return Ids.MURMURHASH_3;
}
}
}
| 16,043
| 27.39646
| 95
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/hash/package-info.java
|
/**
* Commons Hash package
*
* @api.public
*/
package org.infinispan.commons.hash;
| 87
| 11.571429
| 36
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/hash/Hash.java
|
package org.infinispan.commons.hash;
/**
* Interface that governs implementations
*
* @author Manik Surtani
* @author Patrick McFarland
* @see MurmurHash3
*/
public interface Hash {
/**
* Hashes a byte array efficiently.
*
* @param payload a byte array to hash
* @return a hash code for the byte array
*/
int hash(byte[] payload);
/**
* An incremental version of the hash function, that spreads a pre-calculated
* hash code, such as one derived from {@link Object#hashCode()}.
*
* @param hashcode an object's hashcode
* @return a spread and hashed version of the hashcode
*/
int hash(int hashcode);
/**
* A helper that calculates the hashcode of an object, choosing the optimal
* mechanism of hash calculation after considering the type of the object
* (byte array, String or Object).
*
* @param o object to hash
* @return a hashcode
*/
int hash(Object o);
}
| 959
| 23.615385
| 80
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/hash/CRC16.java
|
package org.infinispan.commons.hash;
import java.io.IOException;
import java.io.ObjectInput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.Ids;
import org.infinispan.commons.marshall.WrappedBytes;
import org.infinispan.commons.marshall.exts.NoStateExternalizer;
import net.jcip.annotations.Immutable;
import net.jcip.annotations.ThreadSafe;
/**
* A CRC16 implementation in Java.
*
* @see <a href="https://github.com/lettuce-io/lettuce-core/blob/2ad862f5a1db860d57236c21c473cfd9aefebfea/src/main/java/io/lettuce/core/codec/CRC16.java">Lettuce Implementation.</a>
* @see <a href="https://introcs.cs.princeton.edu/java/61data/CRC16.java">Princeton implementation.</a>
* @since 15.0
*/
@ThreadSafe
@Immutable
public class CRC16 implements Hash {
private final static CRC16 instance = new CRC16();
private CRC16() { }
public static CRC16 getInstance() {
return instance;
}
@Override
public int hash(byte[] payload) {
int crc = 0x0000;
for (byte b : payload) {
crc = (crc >>> 8) ^ CRC16Table.table[(crc ^ b) & 0xff];
}
return crc;
}
@Override
public int hash(int hashcode) {
byte b0 = (byte) hashcode;
byte b1 = (byte) (hashcode >>> 8);
byte b2 = (byte) (hashcode >>> 16);
byte b3 = (byte) (hashcode >>> 24);
return hash(new byte[] { b0, b1, b2, b3 });
}
@Override
public int hash(Object o) {
if (o instanceof byte[]) {
return hash((byte[]) o);
}
if (o instanceof WrappedBytes) {
return hash(((WrappedBytes) o).getBytes());
}
return hash(o.hashCode());
}
@Override
public String toString() {
return "CRC16";
}
private static class CRC16Table {
private CRC16Table() { }
// See: https://github.com/lettuce-io/lettuce-core/blob/2ad862f5a1db860d57236c21c473cfd9aefebfea/src/main/java/io/lettuce/core/codec/CRC16.java#L35
private static final int[] table = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129,
0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7,
0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630,
0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5,
0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58,
0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD,
0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE,
0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C,
0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589,
0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA,
0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1,
0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16,
0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07,
0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 };
}
public static class Externalizer extends NoStateExternalizer<CRC16> {
@Override
public Set<Class<? extends CRC16>> getTypeClasses() {
return Collections.singleton(CRC16.class);
}
@Override
public CRC16 readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return getInstance();
}
@Override
public Integer getId() {
return Ids.CRC16_HASH;
}
}
}
| 4,734
| 40.535088
| 181
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/package-info.java
|
/**
* Commons Configuration package
*
* @api.public
*/
package org.infinispan.commons.configuration;
| 105
| 14.142857
| 45
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/Builder.java
|
package org.infinispan.commons.configuration;
import org.infinispan.commons.configuration.attributes.AttributeSet;
/**
* Builder. Validates and constructs a configuration bean
*
* @author Tristan Tarrant
* @since 5.2
*/
public interface Builder<T> {
default void reset() {
attributes().reset();
}
/**
* Validate the data in this builder before building the configuration bean
*/
default void validate() {}
/**
* Create the configuration bean
*
* @return
*/
T create();
/**
* Reads the configuration from an already created configuration bean into this builder.
* Returns an appropriate builder to allow fluent configuration
*
* @param template the configuration from which to "clone" this config if needed.
* @param combine the way attributes and children of this instance and the template should be combined.
*/
Builder<?> read(T template, Combine combine);
default Builder<?> read(T template) {
return read(template, Combine.DEFAULT);
}
AttributeSet attributes();
}
| 1,073
| 23.976744
| 106
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/BuiltBy.java
|
package org.infinispan.commons.configuration;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* BuiltBy. An annotation for configuration beans to specify what builder builds them.
* This annotation is required on all non-core configuration classes (i.e. ones which reside
* in external modules)
*
* @author Tristan Tarrant
* @since 5.2
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface BuiltBy {
@SuppressWarnings("rawtypes")
Class<? extends Builder> value();
}
| 627
| 27.545455
| 92
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/ConfigurationFor.java
|
package org.infinispan.commons.configuration;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* ConfigurationFor. Indicates the class that this object is a configuration for
*
* @author Tristan Tarrant
* @since 6.0
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ConfigurationFor {
Class<?> value();
}
| 361
| 21.625
| 80
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/AbstractTypedPropertiesConfiguration.java
|
package org.infinispan.commons.configuration;
import static org.infinispan.commons.util.Immutables.immutableTypedProperties;
import java.util.Properties;
import org.infinispan.commons.configuration.attributes.Attribute;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.configuration.attributes.PropertiesAttributeSerializer;
import org.infinispan.commons.configuration.attributes.TypedPropertiesAttributeCopier;
import org.infinispan.commons.util.TypedProperties;
public abstract class AbstractTypedPropertiesConfiguration {
public static final AttributeDefinition<TypedProperties> PROPERTIES = AttributeDefinition.builder("properties", null, TypedProperties.class)
.copier(TypedPropertiesAttributeCopier.INSTANCE).initializer(() -> new TypedProperties()).serializer(PropertiesAttributeSerializer.PROPERTIES).build();
public static AttributeSet attributeSet() {
return new AttributeSet(AbstractTypedPropertiesConfiguration.class, PROPERTIES);
};
protected AttributeSet attributes;
private final Attribute<TypedProperties> properties;
/**
* @deprecated use {@link AbstractTypedPropertiesConfiguration#AbstractTypedPropertiesConfiguration(AttributeSet)} instead
*/
@Deprecated
protected AbstractTypedPropertiesConfiguration(Properties properties) {
this.attributes = attributeSet();
this.attributes = attributes.protect();
this.properties = this.attributes.attribute(PROPERTIES);
this.attributes.attribute(PROPERTIES).set(immutableTypedProperties(TypedProperties.toTypedProperties(properties)));
}
protected AbstractTypedPropertiesConfiguration(AttributeSet attributes) {
this.attributes = attributes.checkProtection();
this.properties = this.attributes.attribute(PROPERTIES);
if (properties.isModified()) {
properties.set(immutableTypedProperties(properties.get()));
}
}
@Override
public String toString() {
return attributes.toString(null);
}
public TypedProperties properties() {
return properties.get();
}
@Override
public final boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractTypedPropertiesConfiguration other = (AbstractTypedPropertiesConfiguration) obj;
if (attributes == null) {
if (other.attributes != null)
return false;
} else if (!attributes.equals(other.attributes))
return false;
return true;
}
@Override
public final int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((attributes == null) ? 0 : attributes.hashCode());
return result;
}
}
| 2,900
| 36.192308
| 160
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/Combine.java
|
package org.infinispan.commons.configuration;
/**
* <p>
* Defines how {@link org.infinispan.commons.configuration.attributes.Attribute}s and {@link org.infinispan.commons.configuration.attributes.ConfigurationElement}s
* are combined when overlaying a configuration (the overlay) on top of another (the template) using {@link Builder#read(Object, Combine)}.
* </p>
* <p>
* The strategies for combining attributes:
* <li>
* <ul><strong>MERGE</strong>: the overlay attributes overwrite those of the template only if they have been modified</ul>
* <ul><strong>OVERRIDE</strong>: the overlay attributes are used, regardless of their modification status.</ul>
* </li>
* <p>
* The strategies for combining repeatable attributes:
* <li>
* <ul><strong>MERGE</strong>: repeatable attributes will be a combination of both the template and the overlay.</ul>
* <ul><strong>OVERRIDE</strong>: only the overlay repeatable attributes will be used.</ul>
* </li>
* </p>
*
* @since 15.0
**/
public class Combine {
public static final Combine DEFAULT = new Combine(RepeatedAttributes.OVERRIDE, Attributes.MERGE);
public enum RepeatedAttributes {
MERGE,
OVERRIDE
}
public enum Attributes {
MERGE,
OVERRIDE
}
private final RepeatedAttributes repeatedAttributes;
private final Attributes attributes;
public Combine(RepeatedAttributes repeatedAttributes, Attributes attributes) {
this.repeatedAttributes = repeatedAttributes;
this.attributes = attributes;
}
public RepeatedAttributes repeatedAttributes() {
return repeatedAttributes;
}
public Attributes attributes() {
return attributes;
}
@Override
public String toString() {
return "Combine{" +
"repeatedAttributes=" + repeatedAttributes +
", attributes=" + attributes +
'}';
}
}
| 1,887
| 29.95082
| 163
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/BasicConfiguration.java
|
package org.infinispan.commons.configuration;
/**
* BasicConfiguration provides the basis for concrete configurations.
*
* @author Tristan Tarrant
* @since 9.2
*/
public interface BasicConfiguration {
@Deprecated
default String toXMLString() {
return toXMLString("configuration");
}
/**
* Converts this configuration to its XML representation. The name of the configuration in the XML will be the one
* supplied in the argument.
*
* @return a String containing the XML representation of an Infinispan configuration using the Infinispan schema.
*/
@Deprecated
default String toXMLString(String name) {
return toStringConfiguration(name);
}
/**
* Converts this configuration to a string-based representation. The name of the configuration in the will be the one
* supplied in the argument. The string must be in one of the supported formats (XML, JSON, YAML).
*
* @return a String containing the representation of an Infinispan configuration using the Infinispan schema in one of the supported formats (XML, JSON, YAML).
*/
String toStringConfiguration(String name);
}
| 1,154
| 32.970588
| 162
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/ClassWhiteList.java
|
package org.infinispan.commons.configuration;
import java.util.Collection;
import java.util.List;
/**
* @deprecated since 12.0. Will be removed in 14.0. Use {@link ClassAllowList}.
**/
@Deprecated
public final class ClassWhiteList extends ClassAllowList {
public ClassWhiteList() {
}
public ClassWhiteList(List<String> regexps) {
super(regexps);
}
public ClassWhiteList(Collection<String> classes, List<String> regexps, ClassLoader classLoader) {
super(classes, regexps, classLoader);
}
}
| 525
| 22.909091
| 101
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/ConfigurationUtils.java
|
package org.infinispan.commons.configuration;
import org.infinispan.commons.CacheConfigurationException;
/**
* ConfigurationUtils. Contains utility methods used in configuration
*
* @author Tristan Tarrant
* @since 5.2
*/
public final class ConfigurationUtils {
private ConfigurationUtils() {}
/**
* Returns the builder that was used to build this class. This is determined by the instance having a class that
* has a {@link org.infinispan.commons.configuration.BuiltBy} annotation present on it. If one is not present
* a {@link org.infinispan.commons.CacheConfigurationException} is thrown
* @param built The instance to find the builder for
* @param <B> The type of builder
* @return The builder for this instance
* @throws CacheConfigurationException thrown if the instance class can't provide the builder
*/
@SuppressWarnings("unchecked")
public static <B> Class<? extends Builder<B>> builderFor(B built) throws CacheConfigurationException {
BuiltBy builtBy = built.getClass().getAnnotation(BuiltBy.class);
if (builtBy == null) {
throw new CacheConfigurationException("Missing BuiltBy annotation for configuration bean " + built.getClass().getName());
}
return (Class<? extends Builder<B>>) builtBy.value();
}
/**
* The same as {@link org.infinispan.commons.configuration.ConfigurationUtils#builderFor(Object)} except that it won't
* throw an exception if no builder class is found. Instead null will be returned.
* @param built The instance to find the builder for
* @param <B> The type of builder
* @return The builder for this instance or null if there isn't one
*/
@SuppressWarnings("unchecked")
public static <B> Class<? extends Builder<B>> builderForNonStrict(B built) {
BuiltBy builtBy = built.getClass().getAnnotation(BuiltBy.class);
if (builtBy == null) {
return null;
}
return (Class<? extends Builder<B>>) builtBy.value();
}
}
| 2,005
| 39.938776
| 130
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/ConfiguredBy.java
|
package org.infinispan.commons.configuration;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Defines the configuration used to configure the given class instances
*
* @author wburns
* @since 7.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ConfiguredBy {
Class<?> value();
}
| 443
| 22.368421
| 72
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/Self.java
|
package org.infinispan.commons.configuration;
/**
* This interface simplifies the task of writing fluent builders which need to inherit from
* other builders (abstract or concrete). It overcomes Java's limitation of not being able to
* return an instance of a class narrowed to the class itself. It should be used by all {@link Builder}
* classes which require inheritance.
*
* @author Tristan Tarrant
* @since 5.2
*/
public interface Self<S extends Self<S>> {
S self();
}
| 485
| 31.4
| 103
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/ClassAllowList.java
|
package org.infinispan.commons.configuration;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static java.util.Objects.requireNonNull;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.KeyValueWithPrevious;
/**
* The {@link ClassAllowList} maintains classes definitions either by name or regular expression and is used for
* permissioning.
* <p>
* By default it includes regular expressions from the system property "infinispan.deserialization.allowlist.regexps"
* and fully qualified class names from "infinispan.deserialization.allowlist.classes".
* <p>
* Classes are checked first against the set of class names, and in case not present each of the regular expressions are
* evaluated in the order supplied.
*
* @since 9.4
*/
public class ClassAllowList {
private static final Log log = LogFactory.getLog(ClassAllowList.class);
@Deprecated
private static final String CLASSES_PROPERTY_NAME_LEGACY = "infinispan.deserialization.whitelist.classes";
@Deprecated
private static final String REGEXPS_PROPERTY_NAME_LEGACY = "infinispan.deserialization.whitelist.regexps";
private static final String CLASSES_PROPERTY_NAME = "infinispan.deserialization.allowlist.classes";
private static final String REGEXPS_PROPERTY_NAME = "infinispan.deserialization.allowlist.regexps";
private static final Set<String> SYS_ALLOWED_CLASSES = new HashSet<>();
private static final List<String> SYS_ALLOWED_REGEXP = new ArrayList<>();
static {
// Classes always allowed
// Primitive Arrays
SYS_ALLOWED_CLASSES.add(byte[].class.getName());
SYS_ALLOWED_CLASSES.add(short[].class.getName());
SYS_ALLOWED_CLASSES.add(int[].class.getName());
SYS_ALLOWED_CLASSES.add(long[].class.getName());
SYS_ALLOWED_CLASSES.add(float[].class.getName());
SYS_ALLOWED_CLASSES.add(double[].class.getName());
SYS_ALLOWED_CLASSES.add(char[].class.getName());
SYS_ALLOWED_CLASSES.add(boolean[].class.getName());
// Boxed Primitives
SYS_ALLOWED_CLASSES.add(Byte.class.getName());
SYS_ALLOWED_CLASSES.add(Short.class.getName());
SYS_ALLOWED_CLASSES.add(Integer.class.getName());
SYS_ALLOWED_CLASSES.add(Long.class.getName());
SYS_ALLOWED_CLASSES.add(Float.class.getName());
SYS_ALLOWED_CLASSES.add(Double.class.getName());
SYS_ALLOWED_CLASSES.add(Character.class.getName());
SYS_ALLOWED_CLASSES.add(String.class.getName());
SYS_ALLOWED_CLASSES.add(Boolean.class.getName());
// Java.math
SYS_ALLOWED_CLASSES.add(BigInteger.class.getName());
SYS_ALLOWED_CLASSES.add(BigDecimal.class.getName());
// Java.time
SYS_ALLOWED_CLASSES.add(Instant.class.getName());
SYS_ALLOWED_CLASSES.add("java.time.Ser");
// Util
SYS_ALLOWED_CLASSES.add(Date.class.getName());
// Misc
SYS_ALLOWED_CLASSES.add(Enum.class.getName());
SYS_ALLOWED_CLASSES.add(Number.class.getName());
// Reference array regex, for arrray representations of allowed classes e.g '[Ljava.lang.Byte;'
SYS_ALLOWED_REGEXP.add("^\\[[\\[L].*\\;$");
// Infinispan classes
// Used by client listeners
SYS_ALLOWED_CLASSES.add(KeyValueWithPrevious.class.getName());
// Legacy handling
String regexps = System.getProperty(REGEXPS_PROPERTY_NAME_LEGACY);
if (regexps != null) {
log.deprecatedProperty(REGEXPS_PROPERTY_NAME_LEGACY, REGEXPS_PROPERTY_NAME);
SYS_ALLOWED_REGEXP.addAll(asList(regexps.trim().split(",")));
}
regexps = System.getProperty(REGEXPS_PROPERTY_NAME);
if (regexps != null) {
SYS_ALLOWED_REGEXP.addAll(asList(regexps.trim().split(",")));
}
String cls = System.getProperty(CLASSES_PROPERTY_NAME_LEGACY);
if (cls != null) {
log.deprecatedProperty(CLASSES_PROPERTY_NAME_LEGACY, CLASSES_PROPERTY_NAME);
SYS_ALLOWED_CLASSES.addAll(asList(cls.trim().split(",")));
}
cls = System.getProperty(CLASSES_PROPERTY_NAME);
if (cls != null) {
SYS_ALLOWED_CLASSES.addAll(asList(cls.trim().split(",")));
}
}
private final Set<String> classes = new CopyOnWriteArraySet<>(SYS_ALLOWED_CLASSES);
private final List<String> regexps = new CopyOnWriteArrayList<>(SYS_ALLOWED_REGEXP);
private final List<Pattern> compiled = new CopyOnWriteArrayList<>();
private final ClassLoader classLoader;
public ClassAllowList() {
this(Collections.emptySet(), Collections.emptyList(), null);
}
public ClassAllowList(List<String> regexps) {
this(Collections.emptySet(), regexps, null);
}
public ClassAllowList(Collection<String> classes, List<String> regexps, ClassLoader classLoader) {
Collection<String> classList = requireNonNull(classes, "Classes must not be null");
Collection<String> regexList = requireNonNull(regexps, "Regexps must not be null");
this.classes.addAll(classList);
this.regexps.addAll(regexList);
this.compiled.addAll(this.regexps.stream().map(Pattern::compile).collect(Collectors.toList()));
this.classLoader = classLoader;
}
public boolean isSafeClass(String className) {
// Test for classes first (faster)
boolean isClassAllowed = classes.contains(className);
if (isClassAllowed) return true;
boolean regexMatch = compiled.stream().anyMatch(p -> p.matcher(className).find());
if (regexMatch) {
// Add the class name to the classes set to avoid future regex checks
classes.add(className);
return true;
}
if (log.isTraceEnabled())
log.tracef("Class '%s' not in allowlist", className);
return false;
}
public void addClasses(Class<?>... classes) {
stream(classes).forEach(c -> this.classes.add(c.getName()));
}
public void addClasses(String... classes) {
this.classes.addAll(Arrays.asList(classes));
}
public void addRegexps(String... regexps) {
this.regexps.addAll(asList(regexps));
this.compiled.addAll(stream(regexps).map(Pattern::compile).collect(Collectors.toList()));
}
public void read(ClassAllowList allowList) {
this.regexps.addAll(allowList.regexps);
this.compiled.addAll(allowList.compiled);
this.classes.addAll(allowList.classes);
}
public ClassLoader getClassLoader() {
return classLoader;
}
}
| 6,942
| 37.572222
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/StringConfiguration.java
|
package org.infinispan.commons.configuration;
/**
* A simple wrapper for a configuration represented as a String. The configuration can be in any
* of the supported formats: XML, JSON, and YAML.
*
* @author Tristan Tarrant
* @since 14.0
*/
public class StringConfiguration implements BasicConfiguration {
private final String string;
public StringConfiguration(String string) {
this.string = string;
}
@Override
public String toStringConfiguration(String name) {
return string;
}
}
| 521
| 22.727273
| 96
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/XMLStringConfiguration.java
|
package org.infinispan.commons.configuration;
/**
* A simple wrapper for an XML configuration represented as a String.
*
* @author Tristan Tarrant
* @since 9.2
* @deprecated Use {@link StringConfiguration} instead
*/
@Deprecated
public class XMLStringConfiguration extends StringConfiguration {
public XMLStringConfiguration(String xml) {
super(xml);
}
}
| 374
| 22.4375
| 69
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/AbstractConfigurationWriter.java
|
package org.infinispan.commons.configuration.io;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commons.util.Util;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public abstract class AbstractConfigurationWriter implements ConfigurationWriter {
final protected Writer writer;
final protected Deque<Tag> tagStack = new ArrayDeque<>();
final protected Map<String, String> namespaces = new HashMap<>();
protected int currentIndent = 0;
private final int indent;
protected final boolean prettyPrint;
protected final boolean clearTextSecrets;
protected final NamingStrategy naming;
protected AbstractConfigurationWriter(Writer writer, int indent, boolean prettyPrint, boolean clearTextSecrets, NamingStrategy naming) {
this.writer = writer;
this.indent = indent;
this.prettyPrint = prettyPrint;
this.clearTextSecrets = clearTextSecrets;
this.naming = naming;
}
@Override
public boolean clearTextSecrets() {
return clearTextSecrets;
}
@Override
public void writeStartElement(Enum<?> name) {
writeStartElement(name.toString());
}
@Override
public void writeStartElement(String prefix, String namespace, Enum<?> name) {
writeStartElement(prefix, namespace, name.toString());
}
@Override
public void writeStartArrayElement(Enum<?> name) {
writeStartArrayElement(name.toString());
}
@Override
public void writeArrayElement(Enum<?> outer, Enum<?> inner, Enum<?> attribute, Iterable<String> values) {
writeArrayElement(outer.toString(), inner.toString(), attribute != null ? attribute.toString(): null, values);
}
@Override
public void writeStartListElement(Enum<?> name, boolean explicit) {
writeStartListElement(name.toString(), explicit);
}
@Override
public void writeStartListElement(String prefix, String namespace, Enum<?> name, boolean explicit) {
writeStartListElement(prefix, namespace, name.toString(), explicit);
}
@Override
public void writeEndListElement() {
writeEndElement();
}
@Override
public void writeAttribute(Enum<?> name, String value) {
writeAttribute(name.toString(), value);
}
@Override
public void writeAttribute(Enum<?> name, Iterable<String> value) {
writeAttribute(name.toString(), value);
}
@Override
public void writeAttribute(Enum<?> name, boolean value) {
writeAttribute(name.toString(), value);
}
@Override
public void writeAttribute(String name, boolean value) {
writeAttribute(name, String.valueOf(value));
}
@Override
public void writeEmptyElement(Enum<?> name) {
writeEmptyElement(name.toString());
}
@Override
public void writeStartMap(Enum<?> name) {
writeStartMap(name.toString());
}
@Override
public void writeMapItem(Enum<?> element, Enum<?> name, String key, String value) {
writeMapItem(element.toString(), name.toString(), key, value);
}
@Override
public void writeMapItem(Enum<?> element, Enum<?> name, String key) {
writeMapItem(element.toString(), name.toString(), key);
}
protected void nl() throws IOException {
if (prettyPrint) {
writer.write(System.lineSeparator());
}
}
protected void tab() throws IOException {
if (prettyPrint) {
for (int i = 0; i < currentIndent; i++) {
writer.write(' ');
}
}
}
protected void indent() {
currentIndent += indent;
}
protected void outdent() {
currentIndent -= indent;
}
@Override
public void close() {
Util.close(writer);
}
public static class Tag {
final String name;
final boolean repeating;
final boolean explicitOuter;
final boolean explicitInner;
int children;
public Tag(String name, boolean repeating, boolean explicitOuter, boolean explicitInner) {
this.name = name;
this.repeating = repeating;
this.explicitOuter = explicitOuter;
this.explicitInner = explicitInner;
}
public Tag(String name) {
this(name, false, false, true);
}
public String getName() {
return name;
}
public boolean isRepeating() {
return repeating;
}
public boolean isExplicitOuter() {
return explicitOuter;
}
public boolean isExplicitInner() {
return explicitInner;
}
@Override
public String toString() {
return name + (repeating ? "+" : "");
}
}
}
| 4,730
| 25.138122
| 139
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/AbstractConfigurationReader.java
|
package org.infinispan.commons.configuration.io;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public abstract class AbstractConfigurationReader implements ConfigurationReader {
private final String name;
private final Properties properties;
private final PropertyReplacer replacer;
private final ConfigurationResourceResolver resolver;
protected final NamingStrategy namingStrategy;
private ConfigurationSchemaVersion schema;
protected AbstractConfigurationReader(ConfigurationResourceResolver resolver, Properties properties, PropertyReplacer replacer, NamingStrategy namingStrategy) {
URL context = resolver.getContext();
this.name = context != null ? context.getPath() : null;
this.resolver = resolver;
this.properties = properties;
this.replacer = replacer;
this.namingStrategy = namingStrategy;
}
@Override
public String getName() {
return name;
}
@Override
public ConfigurationResourceResolver getResourceResolver() {
return resolver;
}
@Override
public NamingStrategy getNamingStrategy() {
return namingStrategy;
}
@Override
public <T> T getProperty(String name) {
return (T) properties.get(name);
}
@Override
public Properties getProperties() {
return properties;
}
@Override
public ConfigurationSchemaVersion getSchema() {
return schema;
}
@Override
public void setSchema(ConfigurationSchemaVersion schema) {
this.schema = schema;
}
@Override
public void handleAny(ConfigurationReaderContext context) {
require(ElementType.START_ELEMENT);
context.handleAnyElement(this);
}
@Override
public void handleAttribute(ConfigurationReaderContext context, int i) {
require(ElementType.START_ELEMENT);
context.handleAnyAttribute(this, i);
}
@Override
public String getAttributeName(int index) {
return getAttributeName(index, namingStrategy);
}
@Override
public String getLocalName() {
return getLocalName(namingStrategy);
}
@Override
public String getAttributeValue(String name) {
return getAttributeValue(name, namingStrategy);
}
@Override
public Map.Entry<String, String> getMapItem(Enum<?> nameAttribute) {
return getMapItem(nameAttribute.toString());
}
@Override
public String[] readArray(Enum<?> outer, Enum<?> inner) {
return readArray(outer.toString(), inner.toString());
}
protected String replaceProperties(String value) {
return replacer.replaceProperties(value, properties);
}
}
| 2,711
| 25.076923
| 163
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/ConfigurationWriter.java
|
package org.infinispan.commons.configuration.io;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.infinispan.commons.configuration.io.json.JsonConfigurationWriter;
import org.infinispan.commons.configuration.io.xml.XmlConfigurationWriter;
import org.infinispan.commons.configuration.io.yaml.YamlConfigurationWriter;
import org.infinispan.commons.dataconversion.MediaType;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public interface ConfigurationWriter extends AutoCloseable {
class Builder {
private final BufferedWriter writer;
private MediaType type = MediaType.APPLICATION_XML;
private boolean prettyPrint = false;
private boolean clearTextSecrets = false;
private Builder(OutputStream os) {
this(new OutputStreamWriter(os));
}
private Builder(Writer writer) {
this.writer = writer instanceof BufferedWriter ? (BufferedWriter) writer : new BufferedWriter(writer);
}
public ConfigurationWriter.Builder withType(MediaType type) {
this.type = type;
return this;
}
public ConfigurationWriter.Builder prettyPrint(boolean prettyPrint) {
this.prettyPrint = prettyPrint;
return this;
}
public ConfigurationWriter.Builder clearTextSecrets(boolean clearTextSecrets) {
this.clearTextSecrets = clearTextSecrets;
return this;
}
public ConfigurationWriter build() {
switch (type.getTypeSubtype()) {
case MediaType.APPLICATION_XML_TYPE:
return new XmlConfigurationWriter(writer, prettyPrint, clearTextSecrets);
case MediaType.APPLICATION_YAML_TYPE:
return new YamlConfigurationWriter(writer, clearTextSecrets);
case MediaType.APPLICATION_JSON_TYPE:
return new JsonConfigurationWriter(writer, prettyPrint, clearTextSecrets);
default:
throw new IllegalArgumentException(type.toString());
}
}
}
static ConfigurationWriter.Builder to(OutputStream os) {
return new ConfigurationWriter.Builder(os);
}
static ConfigurationWriter.Builder to(Writer writer) {
return new ConfigurationWriter.Builder(writer);
}
boolean clearTextSecrets();
void writeStartDocument();
void writeStartElement(String name);
void writeStartElement(Enum<?> name);
void writeStartElement(String prefix, String namespace, String name);
void writeStartElement(String prefix, String namespace, Enum<?> name);
/**
* Writes an array element. This will be treated as follows by the various implementations:
* <ul>
* <li><strong>XML</strong> <outer></outer></li>
* <li><strong>YAML</strong> <pre>
* name:<br>
* - item1
* - item2
* </pre>
* </li>
* <li><strong>JSON</strong> name: [ item1, item2 ]</li>
* </ul>
*
* @param name
*/
void writeStartArrayElement(String name);
void writeStartArrayElement(Enum<?> name);
void writeEndArrayElement();
void writeArrayElement(String outer, String inner, String attribute, Iterable<String> values);
void writeArrayElement(Enum<?> outer, Enum<?> inner, Enum<?> attribute, Iterable<String> values);
/**
* Starts a list element.
* @param name
* @param explicit
*/
void writeStartListElement(String name, boolean explicit);
void writeStartListElement(Enum<?> name, boolean explicit);
void writeStartListElement(String prefix, String namespace, String name, boolean explicit);
void writeStartListElement(String prefix, String namespace, Enum<?> name, boolean explicit);
void writeEndListElement();
void writeStartMap(String name);
void writeStartMap(Enum<?> name);
/**
* Writes a simple map entry.
* <ul>
* <li><strong>XML</strong>: <tt><element name="key">value<element></tt></li>
* <li><strong>JSON</strong>: <tt>{ key: value }</tt></li>
* <li><strong>YAML</strong>: <tt>key: value</tt></li>
* </ul>
* <p>
* The key name is not translated by the underlying serialization implementation and is used as is
*
* @param element Used only by XML
* @param name Used only by XML
* @param key
* @param value
*/
void writeMapItem(String element, String name, String key, String value);
/**
* @see #writeMapItem(String, String, String, String)
*/
void writeMapItem(Enum<?> element, Enum<?> name, String key, String value);
/**
* Writes a complex map entry.
* <ul>
* <li><strong>XML</strong>: <tt><element name="key">...<element></tt></li>
* <li><strong>JSON</strong>: <tt>{ key: { ... } }</tt></li>
* <li><strong>YAML</strong>: <tt>key:</tt></li>
* </ul>
* <p>
* The key name is not translated by the underlying serialization implementation and is used as is
*
* @param element Used only by XML
* @param name Used only by XML
* @param key
*/
void writeMapItem(String element, String name, String key);
void writeMapItem(Enum<?> element, Enum<?> name, String key);
void writeEndMapItem();
void writeEndMap();
void writeDefaultNamespace(String namespace);
void writeEndElement();
void writeEndDocument();
void writeAttribute(Enum<?> name, String value);
void writeAttribute(String name, String value);
void writeAttribute(Enum<?> name, boolean value);
void writeAttribute(String name, boolean value);
void writeAttribute(Enum<?> name, Iterable<String> values);
void writeAttribute(String name, Iterable<String> values);
void writeCharacters(String chars);
void writeEmptyElement(String name);
void writeEmptyElement(Enum<?> name);
void writeComment(String comment);
void writeNamespace(String prefix, String namespace);
boolean hasFeature(ConfigurationFormatFeature feature);
@Override
void close();
}
| 6,079
| 28.950739
| 111
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/ConfigurationFormatFeature.java
|
package org.infinispan.commons.configuration.io;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 13.0
**/
public enum ConfigurationFormatFeature {
/**
* The underlying format supports elements which can have both attributes and an array of child elements.
* True for XML, false for JSON and YAML.
*/
MIXED_ELEMENTS,
/**
* The underlying format supports collections without the need for wrapping in a container element.
* True for XML, false for JSON and YAML.
*/
BARE_COLLECTIONS;
}
| 545
| 27.736842
| 108
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/ConfigurationReaderException.java
|
package org.infinispan.commons.configuration.io;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public class ConfigurationReaderException extends RuntimeException {
private final Location location;
public ConfigurationReaderException(String message, Location location) {
super(message + location);
this.location = location;
}
public ConfigurationReaderException(Throwable t, Location location) {
super(t.getMessage(), t);
this.location = location;
}
public Location getLocation() {
return location;
}
}
| 593
| 23.75
| 75
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/ConfigurationReader.java
|
package org.infinispan.commons.configuration.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import org.infinispan.commons.configuration.io.json.JsonConfigurationReader;
import org.infinispan.commons.configuration.io.xml.XmlConfigurationReader;
import org.infinispan.commons.configuration.io.yaml.YamlConfigurationReader;
import org.infinispan.commons.dataconversion.MediaType;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public interface ConfigurationReader extends AutoCloseable {
class Builder {
final private BufferedReader reader;
private MediaType type;
private PropertyReplacer replacer = PropertyReplacer.DEFAULT;
private Properties properties = new Properties();
private ConfigurationResourceResolver resolver = ConfigurationResourceResolvers.DEFAULT;
private NamingStrategy namingStrategy = NamingStrategy.IDENTITY;
private Builder(InputStream is) {
this(new InputStreamReader(is));
}
private Builder(Reader reader) {
this.reader = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
}
public Builder withProperties(Properties properties) {
this.properties = properties;
return this;
}
public Builder withType(MediaType type) {
this.type = type;
return this;
}
public Builder withReplacer(PropertyReplacer replacer) {
this.replacer = Objects.requireNonNull(replacer);
return this;
}
public Builder withResolver(ConfigurationResourceResolver resolver) {
this.resolver = Objects.requireNonNull(resolver);
return this;
}
public Builder withNamingStrategy(NamingStrategy namingStrategy) {
this.namingStrategy = Objects.requireNonNull(namingStrategy);
return this;
}
private int firstChar() {
try {
reader.mark(16);
int first = reader.read();
reader.reset();
return first;
} catch (IOException e) {
String name = null;
URL context = resolver.getContext();
if (context != null) {
name = context.getPath();
}
throw new ConfigurationReaderException(e, new Location(name, 1, 1));
}
}
public ConfigurationReader build() {
if (type == null) {
// Auto-detect
int first = firstChar();
switch (first) {
case '<':
type = MediaType.APPLICATION_XML;
break;
case '{':
type = MediaType.APPLICATION_JSON;
break;
default:
// no way to detect it easily
type = MediaType.APPLICATION_YAML;
break;
}
}
switch (type.getTypeSubtype()) {
case MediaType.APPLICATION_XML_TYPE:
return new XmlConfigurationReader(reader, resolver, properties, replacer, namingStrategy);
case MediaType.APPLICATION_YAML_TYPE:
return new YamlConfigurationReader(reader, resolver, properties, replacer, namingStrategy);
case MediaType.APPLICATION_JSON_TYPE:
return new JsonConfigurationReader(reader, resolver, properties, replacer, namingStrategy);
default:
throw new IllegalArgumentException(type.toString());
}
}
}
static Builder from(InputStream is) {
return new Builder(is);
}
static Builder from(Reader reader) {
return new Builder(reader);
}
static Builder from(String s) {
return new Builder(new StringReader(s));
}
String getName();
/**
* @return the resource resolver used by this ConfigurationReader to find external references (e.g. includes)
*/
ConfigurationResourceResolver getResourceResolver();
/**
* @return the naming strategy used by this ConfigurationReader
*/
NamingStrategy getNamingStrategy();
/**
* @param schema the ConfigurationSchema in use
*/
void setSchema(ConfigurationSchemaVersion schema);
/**
* @return the schema
*/
ConfigurationSchemaVersion getSchema();
/**
* @return the next element
*/
ElementType nextElement();
default boolean inTag() {
return hasNext() && (nextElement() != ConfigurationReader.ElementType.END_ELEMENT);
}
default boolean inTag(String name) {
return hasNext() && (nextElement() != ConfigurationReader.ElementType.END_ELEMENT || !name.equals(getLocalName()));
}
default boolean inTag(Enum<?> name) {
return inTag(name.toString());
}
Location getLocation();
<T> T getProperty(String name);
Properties getProperties();
String getAttributeName(int index);
String getAttributeName(int index, NamingStrategy strategy);
String getAttributeNamespace(int index);
String getAttributeValue(String localName);
default String getAttributeValue(Enum<?> localName) {
return getAttributeValue(localName.toString());
}
String getAttributeValue(String localName, NamingStrategy strategy);
default String getAttributeValue(Enum<?> localName, NamingStrategy strategy) {
return getAttributeValue(localName.toString(), strategy);
}
String getAttributeValue(int index);
/**
* Get the value of an attribute as a space-delimited string list.
*
* @param index the index of the attribute
*/
default String[] getListAttributeValue(int index) {
return getAttributeValue(index).split("\\s+");
}
String getElementText();
String getLocalName();
String getLocalName(NamingStrategy strategy);
String getNamespace();
boolean hasNext();
int getAttributeCount();
void handleAny(ConfigurationReaderContext context);
void handleAttribute(ConfigurationReaderContext context, int i);
default void require(ElementType type) {
require(type, null, (String) null);
}
void require(ElementType type, String namespace, String name);
default void require(ElementType type, String namespace, Enum<?> name) {
require(type, namespace, name.toString());
}
Map.Entry<String, String> getMapItem(String nameAttribute);
Map.Entry<String, String> getMapItem(Enum<?> nameAttribute);
void endMapItem();
String[] readArray(Enum<?> outer, Enum<?> inner);
String[] readArray(String outer, String inner);
boolean hasFeature(ConfigurationFormatFeature feature);
@Override
void close();
void setAttributeValue(String namespace, String name, String value);
default void setAttributeValue(String namespace, Enum<?> localName, String value) {
setAttributeValue(namespace, localName.toString(), value);
}
enum ElementType {
START_DOCUMENT,
END_DOCUMENT,
START_ELEMENT,
END_ELEMENT,
TEXT
}
}
| 7,220
| 27.541502
| 121
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/URLConfigurationResourceResolver.java
|
package org.infinispan.commons.configuration.io;
import java.io.IOException;
import java.net.URL;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public class URLConfigurationResourceResolver implements ConfigurationResourceResolver {
private final URL context;
public URLConfigurationResourceResolver(URL context) {
this.context = context;
}
@Override
public URL resolveResource(String href) throws IOException {
return new URL(context, href);
}
@Override
public URL getContext() {
return context;
}
}
| 587
| 20.777778
| 88
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/ConfigurationResourceResolver.java
|
package org.infinispan.commons.configuration.io;
import java.io.IOException;
import java.net.URL;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public interface ConfigurationResourceResolver {
// ISPN-15004 Lazily resolve URLConfigurationResourceResolver instance to prevent circular dependency
// Replaced by ConfigurationResourceResolvers.DEFAULT instead. Variable only retained for backwards-compatibility.
@Deprecated
ConfigurationResourceResolver DEFAULT = href -> new URLConfigurationResourceResolver(null).resolveResource(href);
URL resolveResource(String href) throws IOException;
default URL getContext() {
return null;
}
}
| 701
| 29.521739
| 117
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/ConfigurationReaderContext.java
|
package org.infinispan.commons.configuration.io;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public interface ConfigurationReaderContext {
void handleAnyElement(ConfigurationReader reader);
void handleAnyAttribute(ConfigurationReader reader, int i);
}
| 298
| 23.916667
| 62
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/PropertyReplacer.java
|
package org.infinispan.commons.configuration.io;
import java.util.Properties;
import org.infinispan.commons.util.StringPropertyReplacer;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public interface PropertyReplacer {
PropertyReplacer DEFAULT = new Default();
String replaceProperties(final String string, final Properties props);
class Default implements PropertyReplacer {
private Default() {
}
@Override
public String replaceProperties(String string, Properties props) {
return StringPropertyReplacer.replaceProperties(string, props);
}
}
}
| 638
| 23.576923
| 73
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/ConfigurationResourceResolvers.java
|
package org.infinispan.commons.configuration.io;
/**
* @since 15.0
**/
public class ConfigurationResourceResolvers {
public static final ConfigurationResourceResolver DEFAULT = new URLConfigurationResourceResolver(null);
private ConfigurationResourceResolvers() {
}
}
| 281
| 22.5
| 106
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/ConfigurationWriterException.java
|
package org.infinispan.commons.configuration.io;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public class ConfigurationWriterException extends RuntimeException {
public ConfigurationWriterException(String message) {
super(message);
}
public ConfigurationWriterException(Throwable t) {
super(t);
}
}
| 365
| 19.333333
| 68
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/ConfigurationSchemaVersion.java
|
package org.infinispan.commons.configuration.io;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public interface ConfigurationSchemaVersion {
String getURI();
int getMajor();
int getMinor();
boolean since(int major, int minor);
}
| 281
| 16.625
| 57
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/NamingStrategy.java
|
package org.infinispan.commons.configuration.io;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public enum NamingStrategy {
IDENTITY {
@Override
public String convert(String s) {
return s;
}
},
CAMEL_CASE {
@Override
public String convert(String s) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c == '-' || c == '_') && (i < s.length() - 1)) {
b.append(Character.toUpperCase(s.charAt(++i)));
} else {
b.append(c);
}
}
return b.toString();
}
},
KEBAB_CASE {
@Override
public String convert(String s) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (i > 0 && isWordBoundary(c, s.charAt(i - 1))) {
b.append('-');
b.append(Character.toLowerCase(c));
} else if (c == '_') {
b.append('-');
} else {
b.append(c);
}
}
return b.toString();
}
},
SNAKE_CASE {
@Override
public String convert(String s) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (i > 0 && isWordBoundary(c, s.charAt(i - 1))) {
b.append('_');
b.append(Character.toLowerCase(c));
} else if (c == '-') {
b.append('_');
} else {
b.append(c);
}
}
return b.toString();
}
};
static boolean isWordBoundary(char ch1, char ch2) {
return Character.isUpperCase(ch1) && (Character.isLowerCase(ch2) || Character.isDigit(ch2));
}
public abstract String convert(String s);
}
| 1,979
| 26.5
| 98
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/Location.java
|
package org.infinispan.commons.configuration.io;
/**
* @since 12.1
* @author Tristan Tarrant <tristan@infinispan.org%gt;
*/
public class Location {
private final String name;
private final int line;
private final int column;
public Location(String name, int line, int column) {
this.name = name;
this.line = line;
this.column = column;
}
public String getName() {
return name;
}
public int getLineNumber() {
return line;
}
public int getColumnNumber(){
return column;
}
public String toString() {
return (name != null ? name : "") + "[" + line + ',' + column + ']';
}
}
| 636
| 17.735294
| 72
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/xml/MXParser.java
|
package org.infinispan.commons.configuration.io.xml;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
/**
* Absolutely minimal implementation of XMLPULL V1 API
*
* @author <a href="http://www.extreme.indiana.edu/~aslom/">Aleksander Slominski</a>
*/
public class MXParser implements XmlPullParser {
protected final static String XML_URI = "http://www.w3.org/XML/1998/namespace";
protected final static String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
protected final static String FEATURE_XML_ROUNDTRIP =
"http://xmlpull.org/v1/doc/features.html#xml-roundtrip";
protected final static String FEATURE_NAMES_INTERNED =
"http://xmlpull.org/v1/doc/features.html#names-interned";
protected final static String PROPERTY_XMLDECL_VERSION =
"http://xmlpull.org/v1/doc/properties.html#xmldecl-version";
protected final static String PROPERTY_XMLDECL_STANDALONE =
"http://xmlpull.org/v1/doc/properties.html#xmldecl-standalone";
protected final static String PROPERTY_XMLDECL_CONTENT =
"http://xmlpull.org/v1/doc/properties.html#xmldecl-content";
protected final static String PROPERTY_LOCATION =
"http://xmlpull.org/v1/doc/properties.html#location";
/**
* Implementation notice: the is instance variable that controls if newString() is interning.
* <p><b>NOTE:</b> newStringIntern <b>always</b> returns interned strings
* and newString MAY return interned String depending on this variable.
* <p><b>NOTE:</b> by default in this minimal implementation it is false!
*/
protected boolean allStringsInterned;
protected String newString(char[] cbuf, int off, int len) {
return new String(cbuf, off, len);
}
protected String newStringIntern(char[] cbuf, int off, int len) {
return (new String(cbuf, off, len)).intern();
}
private static final boolean TRACE_SIZING = false;
// NOTE: features are not resettable and typically defaults to false ...
protected boolean processNamespaces;
protected boolean roundtripSupported;
// global parser state
protected String location;
protected int lineNumber;
protected int columnNumber;
protected boolean seenRoot;
protected boolean reachedEnd;
protected int eventType;
protected boolean emptyElementTag;
// element stack
protected int depth;
protected char[] elRawName[];
protected int elRawNameEnd[];
protected int elRawNameLine[];
protected String elName[];
protected String elPrefix[];
protected String elUri[];
//protected String elValue[];
protected int elNamespaceCount[];
/**
* Make sure that we have enough space to keep element stack if passed size. It will always create one additional
* slot then current depth
*/
protected void ensureElementsCapacity() {
final int elStackSize = elName != null ? elName.length : 0;
if ((depth + 1) >= elStackSize) {
// we add at least one extra slot ...
final int newSize = (depth >= 7 ? 2 * depth : 8) + 2; // = lucky 7 + 1 //25
if (TRACE_SIZING) {
System.err.println("TRACE_SIZING elStackSize " + elStackSize + " ==> " + newSize);
}
final boolean needsCopying = elStackSize > 0;
String[] arr = null;
// reuse arr local variable slot
arr = new String[newSize];
if (needsCopying) System.arraycopy(elName, 0, arr, 0, elStackSize);
elName = arr;
arr = new String[newSize];
if (needsCopying) System.arraycopy(elPrefix, 0, arr, 0, elStackSize);
elPrefix = arr;
arr = new String[newSize];
if (needsCopying) System.arraycopy(elUri, 0, arr, 0, elStackSize);
elUri = arr;
int[] iarr = new int[newSize];
if (needsCopying) {
System.arraycopy(elNamespaceCount, 0, iarr, 0, elStackSize);
} else {
// special initialization
iarr[0] = 0;
}
elNamespaceCount = iarr;
//TODO: avoid using element raw name ...
iarr = new int[newSize];
if (needsCopying) {
System.arraycopy(elRawNameEnd, 0, iarr, 0, elStackSize);
}
elRawNameEnd = iarr;
iarr = new int[newSize];
if (needsCopying) {
System.arraycopy(elRawNameLine, 0, iarr, 0, elStackSize);
}
elRawNameLine = iarr;
final char[][] carr = new char[newSize][];
if (needsCopying) {
System.arraycopy(elRawName, 0, carr, 0, elStackSize);
}
elRawName = carr;
}
}
// attribute stack
protected int attributeCount;
protected String attributeName[];
protected int attributeNameHash[];
protected String attributePrefix[];
protected String attributeUri[];
protected String attributeValue[];
/**
* Make sure that in attributes temporary array is enough space.
*/
protected void ensureAttributesCapacity(int size) {
final int attrPosSize = attributeName != null ? attributeName.length : 0;
if (size >= attrPosSize) {
final int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25
if (TRACE_SIZING) {
System.err.println("TRACE_SIZING attrPosSize " + attrPosSize + " ==> " + newSize);
}
final boolean needsCopying = attrPosSize > 0;
String[] arr = null;
arr = new String[newSize];
if (needsCopying) System.arraycopy(attributeName, 0, arr, 0, attrPosSize);
attributeName = arr;
arr = new String[newSize];
if (needsCopying) System.arraycopy(attributePrefix, 0, arr, 0, attrPosSize);
attributePrefix = arr;
arr = new String[newSize];
if (needsCopying) System.arraycopy(attributeUri, 0, arr, 0, attrPosSize);
attributeUri = arr;
arr = new String[newSize];
if (needsCopying) System.arraycopy(attributeValue, 0, arr, 0, attrPosSize);
attributeValue = arr;
if (!allStringsInterned) {
final int[] iarr = new int[newSize];
if (needsCopying) System.arraycopy(attributeNameHash, 0, iarr, 0, attrPosSize);
attributeNameHash = iarr;
}
arr = null;
// //assert attrUri.length > size
}
}
// namespace stack
protected int namespaceEnd;
protected String namespacePrefix[];
protected int namespacePrefixHash[];
protected String namespaceUri[];
protected void ensureNamespacesCapacity(int size) {
final int namespaceSize = namespacePrefix != null ? namespacePrefix.length : 0;
if (size >= namespaceSize) {
final int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25
if (TRACE_SIZING) {
System.err.println("TRACE_SIZING namespaceSize " + namespaceSize + " ==> " + newSize);
}
final String[] newNamespacePrefix = new String[newSize];
final String[] newNamespaceUri = new String[newSize];
if (namespacePrefix != null) {
System.arraycopy(
namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd);
System.arraycopy(
namespaceUri, 0, newNamespaceUri, 0, namespaceEnd);
}
namespacePrefix = newNamespacePrefix;
namespaceUri = newNamespaceUri;
if (!allStringsInterned) {
final int[] newNamespacePrefixHash = new int[newSize];
if (namespacePrefixHash != null) {
System.arraycopy(
namespacePrefixHash, 0, newNamespacePrefixHash, 0, namespaceEnd);
}
namespacePrefixHash = newNamespacePrefixHash;
}
//prefixesSize = newSize;
// //assert nsPrefixes.length > size && nsPrefixes.length == newSize
}
}
/**
* simplistic implementation of hash function that has <b>constant</b> time to compute - so it also means diminishing
* hash quality for long strings but for XML parsing it should be good enough ...
*/
protected static final int fastHash(char ch[], int off, int len) {
if (len == 0) return 0;
//assert len >0
int hash = ch[off]; // hash at beginning
//try {
hash = (hash << 7) + ch[off + len - 1]; // hash at the end
//} catch(ArrayIndexOutOfBoundsException aie) {
// aie.printStackTrace(); //should never happen ...
// throw new RuntimeException("this is violation of pre-condition");
//}
if (len > 16) hash = (hash << 7) + ch[off + (len / 4)]; // 1/4 from beginning
if (len > 8) hash = (hash << 7) + ch[off + (len / 2)]; // 1/2 of string size ...
// notice that hash is at most done 3 times <<7 so shifted by 21 bits 8 bit value
// so max result == 29 bits so it is quite just below 31 bits for long (2^32) ...
//assert hash >= 0;
return hash;
}
// entity replacement stack
protected int entityEnd;
protected String entityName[];
protected char[] entityNameBuf[];
protected String entityReplacement[];
protected char[] entityReplacementBuf[];
protected int entityNameHash[];
protected void ensureEntityCapacity() {
final int entitySize = entityReplacementBuf != null ? entityReplacementBuf.length : 0;
if (entityEnd >= entitySize) {
final int newSize = entityEnd > 7 ? 2 * entityEnd : 8; // = lucky 7 + 1 //25
if (TRACE_SIZING) {
System.err.println("TRACE_SIZING entitySize " + entitySize + " ==> " + newSize);
}
final String[] newEntityName = new String[newSize];
final char[] newEntityNameBuf[] = new char[newSize][];
final String[] newEntityReplacement = new String[newSize];
final char[] newEntityReplacementBuf[] = new char[newSize][];
if (entityName != null) {
System.arraycopy(entityName, 0, newEntityName, 0, entityEnd);
System.arraycopy(entityNameBuf, 0, newEntityNameBuf, 0, entityEnd);
System.arraycopy(entityReplacement, 0, newEntityReplacement, 0, entityEnd);
System.arraycopy(entityReplacementBuf, 0, newEntityReplacementBuf, 0, entityEnd);
}
entityName = newEntityName;
entityNameBuf = newEntityNameBuf;
entityReplacement = newEntityReplacement;
entityReplacementBuf = newEntityReplacementBuf;
if (!allStringsInterned) {
final int[] newEntityNameHash = new int[newSize];
if (entityNameHash != null) {
System.arraycopy(entityNameHash, 0, newEntityNameHash, 0, entityEnd);
}
entityNameHash = newEntityNameHash;
}
}
}
// input buffer management
protected static final int READ_CHUNK_SIZE = 8 * 1024; //max data chars in one read() call
protected Reader reader;
protected String inputEncoding;
protected InputStream inputStream;
protected int bufLoadFactor = 95; // 99%
//protected int bufHardLimit; // only matters when expanding
protected char buf[] = new char[
Runtime.getRuntime().freeMemory() > 1000000L ? READ_CHUNK_SIZE : 256];
protected int bufSoftLimit = (bufLoadFactor * buf.length) / 100; // desirable size of buffer
protected boolean preventBufferCompaction;
protected int bufAbsoluteStart; // this is buf
protected int bufStart;
protected int bufEnd;
protected int pos;
protected int posStart;
protected int posEnd;
protected char pc[] = new char[
Runtime.getRuntime().freeMemory() > 1000000L ? READ_CHUNK_SIZE : 64];
protected int pcStart;
protected int pcEnd;
// parsing state
protected boolean usePC;
protected boolean seenStartTag;
protected boolean seenEndTag;
protected boolean pastEndTag;
protected boolean seenAmpersand;
protected boolean seenMarkup;
protected boolean seenDocdecl;
// transient variable set during each call to next/Token()
protected boolean tokenize;
protected String text;
protected String entityRefName;
protected String xmlDeclVersion;
protected Boolean xmlDeclStandalone;
protected String xmlDeclContent;
protected void reset() {
location = null;
lineNumber = 1;
columnNumber = 0;
seenRoot = false;
reachedEnd = false;
eventType = START_DOCUMENT;
emptyElementTag = false;
depth = 0;
attributeCount = 0;
namespaceEnd = 0;
entityEnd = 0;
reader = null;
inputEncoding = null;
preventBufferCompaction = false;
bufAbsoluteStart = 0;
bufEnd = bufStart = 0;
pos = posStart = posEnd = 0;
pcEnd = pcStart = 0;
usePC = false;
seenStartTag = false;
seenEndTag = false;
pastEndTag = false;
seenAmpersand = false;
seenMarkup = false;
seenDocdecl = false;
xmlDeclVersion = null;
xmlDeclStandalone = null;
xmlDeclContent = null;
}
public MXParser() {
}
public MXParser(Reader reader) {
setInput(reader);
}
/**
* Method setFeature
*
* @param name a String
* @param state a boolean
* @throws XmlPullParserException
*/
public void setFeature(String name,
boolean state) throws XmlPullParserException {
if (name == null) throw new IllegalArgumentException("feature name should not be null");
if (FEATURE_PROCESS_NAMESPACES.equals(name)) {
if (eventType != START_DOCUMENT) throw new XmlPullParserException(
"namespace processing feature can only be changed before parsing", this, null);
processNamespaces = state;
} else if (FEATURE_NAMES_INTERNED.equals(name)) {
if (state != false) {
throw new XmlPullParserException(
"interning names in this implementation is not supported");
}
} else if (FEATURE_PROCESS_DOCDECL.equals(name)) {
if (state != false) {
throw new XmlPullParserException(
"processing DOCDECL is not supported");
}
} else if (FEATURE_XML_ROUNDTRIP.equals(name)) {
roundtripSupported = state;
} else {
throw new XmlPullParserException("unsupported feature " + name);
}
}
/**
* Unknown properties are <strong>always</strong> returned as false
*/
public boolean getFeature(String name) {
if (name == null) throw new IllegalArgumentException("feature name should not be null");
if (FEATURE_PROCESS_NAMESPACES.equals(name)) {
return processNamespaces;
} else if (FEATURE_NAMES_INTERNED.equals(name)) {
return false;
} else if (FEATURE_PROCESS_DOCDECL.equals(name)) {
return false;
} else if (FEATURE_XML_ROUNDTRIP.equals(name)) {
return roundtripSupported;
}
return false;
}
public void setProperty(String name,
Object value)
throws XmlPullParserException {
if (PROPERTY_LOCATION.equals(name)) {
location = (String) value;
} else {
throw new XmlPullParserException("unsupported property: '" + name + "'");
}
}
public Object getProperty(String name) {
if (name == null) throw new IllegalArgumentException("property name should not be null");
if (PROPERTY_XMLDECL_VERSION.equals(name)) {
return xmlDeclVersion;
} else if (PROPERTY_XMLDECL_STANDALONE.equals(name)) {
return xmlDeclStandalone;
} else if (PROPERTY_XMLDECL_CONTENT.equals(name)) {
return xmlDeclContent;
} else if (PROPERTY_LOCATION.equals(name)) {
return location;
}
return null;
}
public void setInput(Reader in) {
reset();
reader = in;
}
public void setInput(java.io.InputStream inputStream, String inputEncoding) {
if (inputStream == null) {
throw new IllegalArgumentException("input stream can not be null");
}
this.inputStream = inputStream;
Reader reader;
try {
if (inputEncoding != null) {
reader = new InputStreamReader(inputStream, inputEncoding);
} else {
//by default use UTF-8 (InputStreamReader(inputStream)) would use OS default ...
reader = new InputStreamReader(inputStream, "UTF-8");
}
} catch (UnsupportedEncodingException une) {
throw new XmlPullParserException(
"could not create reader for encoding " + inputEncoding + " : " + une, this, une);
}
setInput(reader);
this.inputEncoding = inputEncoding;
}
public String getInputEncoding() {
return inputEncoding;
}
public void defineEntityReplacementText(String entityName,
String replacementText)
throws XmlPullParserException {
ensureEntityCapacity();
this.entityName[entityEnd] = newString(entityName.toCharArray(), 0, entityName.length());
entityNameBuf[entityEnd] = entityName.toCharArray();
entityReplacement[entityEnd] = replacementText;
entityReplacementBuf[entityEnd] = replacementText.toCharArray();
if (!allStringsInterned) {
entityNameHash[entityEnd] =
fastHash(entityNameBuf[entityEnd], 0, entityNameBuf[entityEnd].length);
}
++entityEnd;
}
public int getNamespaceCount(int depth)
throws XmlPullParserException {
if (processNamespaces == false || depth == 0) {
return 0;
}
if (depth < 0 || depth > this.depth) throw new IllegalArgumentException(
"allowed namespace depth 0.." + this.depth + " not " + depth);
return elNamespaceCount[depth];
}
public String getNamespacePrefix(int pos)
throws XmlPullParserException {
if (pos < namespaceEnd) {
return namespacePrefix[pos];
} else {
throw new XmlPullParserException(
"position " + pos + " exceeded number of available namespaces " + namespaceEnd);
}
}
public String getNamespaceUri(int pos) throws XmlPullParserException {
if (pos < namespaceEnd) {
return namespaceUri[pos];
} else {
throw new XmlPullParserException(
"position " + pos + " exceeded number of available namespaces " + namespaceEnd);
}
}
public String getNamespace(String prefix) {
if (prefix != null) {
for (int i = namespaceEnd - 1; i >= 0; i--) {
if (prefix.equals(namespacePrefix[i])) {
return namespaceUri[i];
}
}
if ("xml".equals(prefix)) {
return XML_URI;
} else if ("xmlns".equals(prefix)) {
return XMLNS_URI;
}
} else {
for (int i = namespaceEnd - 1; i >= 0; i--) {
if (namespacePrefix[i] == null) {
return namespaceUri[i];
}
}
}
return null;
}
public int getDepth() {
return depth;
}
private static int findFragment(int bufMinPos, char[] b, int start, int end) {
if (start < bufMinPos) {
start = bufMinPos;
if (start > end) start = end;
return start;
}
if (end - start > 65) {
start = end - 10; // try to find good location
}
int i = start + 1;
while (--i > bufMinPos) {
if ((end - i) > 65) break;
final char c = b[i];
if (c == '<' && (start - i) > 10) break;
}
return i;
}
/**
* Return string describing current position of parsers as text 'STATE [seen %s...] @line:column'.
*/
public String getPositionDescription() {
String fragment = null;
if (posStart <= pos) {
final int start = findFragment(0, buf, posStart, pos);
if (start < pos) {
fragment = new String(buf, start, pos - start);
}
if (bufAbsoluteStart > 0 || start > 0) fragment = "..." + fragment;
}
return " " + TYPES[eventType] +
(fragment != null ? " seen " + printable(fragment) + "..." : "")
+ " " + (location != null ? location : "")
+ "@" + getLineNumber() + ":" + getColumnNumber();
}
public int getLineNumber() {
return lineNumber;
}
public int getColumnNumber() {
return columnNumber;
}
public boolean isWhitespace() throws XmlPullParserException {
if (eventType == TEXT || eventType == CDSECT) {
if (usePC) {
for (int i = pcStart; i < pcEnd; i++) {
if (!isS(pc[i])) return false;
}
return true;
} else {
for (int i = posStart; i < posEnd; i++) {
if (!isS(buf[i])) return false;
}
return true;
}
} else if (eventType == IGNORABLE_WHITESPACE) {
return true;
}
throw new XmlPullParserException("no content available to check for white spaces");
}
public String getText() {
if (eventType == START_DOCUMENT || eventType == END_DOCUMENT) {
return null;
} else if (eventType == ENTITY_REF) {
return text;
}
if (text == null) {
if (!usePC || eventType == START_TAG || eventType == END_TAG) {
text = new String(buf, posStart, posEnd - posStart);
} else {
text = new String(pc, pcStart, pcEnd - pcStart);
}
}
return text;
}
public char[] getTextCharacters(int[] holderForStartAndLength) {
if (eventType == TEXT) {
if (usePC) {
holderForStartAndLength[0] = pcStart;
holderForStartAndLength[1] = pcEnd - pcStart;
return pc;
} else {
holderForStartAndLength[0] = posStart;
holderForStartAndLength[1] = posEnd - posStart;
return buf;
}
} else if (eventType == START_TAG
|| eventType == END_TAG
|| eventType == CDSECT
|| eventType == COMMENT
|| eventType == ENTITY_REF
|| eventType == PROCESSING_INSTRUCTION
|| eventType == IGNORABLE_WHITESPACE
|| eventType == DOCDECL) {
holderForStartAndLength[0] = posStart;
holderForStartAndLength[1] = posEnd - posStart;
return buf;
} else if (eventType == START_DOCUMENT
|| eventType == END_DOCUMENT) {
//throw new XmlPullParserException("no content available to read");
holderForStartAndLength[0] = holderForStartAndLength[1] = -1;
return null;
} else {
throw new IllegalArgumentException("unknown text eventType: " + eventType);
}
// String s = getText();
// char[] cb = null;
// if(s!= null) {
// cb = s.toCharArray();
// holderForStartAndLength[0] = 0;
// holderForStartAndLength[1] = s.length();
// } else {
// }
// return cb;
}
public String getNamespace() {
if (eventType == START_TAG) {
//return processNamespaces ? elUri[ depth - 1 ] : NO_NAMESPACE;
return processNamespaces ? elUri[depth] : NO_NAMESPACE;
} else if (eventType == END_TAG) {
return processNamespaces ? elUri[depth] : NO_NAMESPACE;
}
return null;
}
public String getName() {
if (eventType == START_TAG) {
//return elName[ depth - 1 ] ;
return elName[depth];
} else if (eventType == END_TAG) {
return elName[depth];
} else if (eventType == ENTITY_REF) {
if (entityRefName == null) {
entityRefName = newString(buf, posStart, posEnd - posStart);
}
return entityRefName;
} else {
return null;
}
}
public String getPrefix() {
if (eventType == START_TAG) {
return elPrefix[depth];
} else if (eventType == END_TAG) {
return elPrefix[depth];
}
return null;
}
public boolean isEmptyElementTag() throws XmlPullParserException {
if (eventType != START_TAG) throw new XmlPullParserException(
"parser must be on START_TAG to check for empty element", this, null);
return emptyElementTag;
}
public int getAttributeCount() {
if (eventType != START_TAG) return -1;
return attributeCount;
}
public String getAttributeNamespace(int index) {
if (eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if (processNamespaces == false) return NO_NAMESPACE;
if (index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
return attributeUri[index];
}
public String getAttributeName(int index) {
if (eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if (index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
return attributeName[index];
}
public String getAttributePrefix(int index) {
if (eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if (processNamespaces == false) return null;
if (index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
return attributePrefix[index];
}
public String getAttributeType(int index) {
if (eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if (index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
return "CDATA";
}
public boolean isAttributeDefault(int index) {
if (eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if (index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
return false;
}
public String getAttributeValue(int index) {
if (eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes");
if (index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException(
"attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
return attributeValue[index];
}
public String getAttributeValue(String namespace,
String name) {
if (eventType != START_TAG) throw new IndexOutOfBoundsException(
"only START_TAG can have attributes" + getPositionDescription());
if (name == null) {
throw new IllegalArgumentException("attribute name can not be null");
}
// TODO make check if namespace is interned!!! etc. for names!!!
if (processNamespaces) {
if (namespace == null) {
namespace = "";
}
for (int i = 0; i < attributeCount; ++i) {
if ((namespace == attributeUri[i] ||
namespace.equals(attributeUri[i]))
//(namespace != null && namespace.equals(attributeUri[ i ]))
// taking advantage of String.intern()
&& name.equals(attributeName[i])) {
return attributeValue[i];
}
}
} else {
if (namespace != null && namespace.length() == 0) {
namespace = null;
}
if (namespace != null) throw new IllegalArgumentException(
"when namespaces processing is disabled attribute namespace must be null");
for (int i = 0; i < attributeCount; ++i) {
if (name.equals(attributeName[i])) {
return attributeValue[i];
}
}
}
return null;
}
public int getEventType()
throws XmlPullParserException {
return eventType;
}
public void require(int type, String namespace, String name)
throws XmlPullParserException, IOException {
if (processNamespaces == false && namespace != null) {
throw new XmlPullParserException(
"processing namespaces must be enabled on parser (or factory)" +
" to have possible namespaces declared on elements"
+ (" (position:" + getPositionDescription()) + ")");
}
if (type != getEventType()
|| (namespace != null && !namespace.equals(getNamespace()))
|| (name != null && !name.equals(getName()))) {
throw new XmlPullParserException(
"expected event " + TYPES[type]
+ (name != null ? " with name '" + name + "'" : "")
+ (namespace != null && name != null ? " and" : "")
+ (namespace != null ? " with namespace '" + namespace + "'" : "")
+ " but got"
+ (type != getEventType() ? " " + TYPES[getEventType()] : "")
+ (name != null && getName() != null && !name.equals(getName())
? " name '" + getName() + "'" : "")
+ (namespace != null && name != null
&& getName() != null && !name.equals(getName())
&& getNamespace() != null && !namespace.equals(getNamespace())
? " and" : "")
+ (namespace != null && getNamespace() != null && !namespace.equals(getNamespace())
? " namespace '" + getNamespace() + "'" : "")
+ (" (position:" + getPositionDescription()) + ")");
}
}
/**
* Skip sub tree that is currently parser positioned on.
* <br>NOTE: parser must be on START_TAG and when function returns
* parser will be positioned on corresponding END_TAG
*/
public void skipSubTree()
throws XmlPullParserException, IOException {
require(START_TAG, null, null);
int level = 1;
while (level > 0) {
int eventType = next();
if (eventType == END_TAG) {
--level;
} else if (eventType == START_TAG) {
++level;
}
}
}
public String nextText() throws XmlPullParserException, IOException {
if (getEventType() != START_TAG) {
throw new XmlPullParserException(
"parser must be on START_TAG to read next text", this, null);
}
int eventType = next();
if (eventType == TEXT) {
final String result = getText();
eventType = next();
if (eventType != END_TAG) {
throw new XmlPullParserException(
"TEXT must be immediately followed by END_TAG and not "
+ TYPES[getEventType()], this, null);
}
return result;
} else if (eventType == END_TAG) {
return "";
} else {
throw new XmlPullParserException(
"parser must be on START_TAG or TEXT to read text", this, null);
}
}
public int nextTag() throws XmlPullParserException, IOException {
next();
if (eventType == TEXT && isWhitespace()) { // skip whitespace
next();
}
if (eventType != START_TAG && eventType != END_TAG) {
throw new XmlPullParserException("expected START_TAG or END_TAG not "
+ TYPES[getEventType()], this, null);
}
return eventType;
}
public int next()
throws XmlPullParserException, IOException {
tokenize = false;
return nextImpl();
}
public int nextToken()
throws XmlPullParserException, IOException {
tokenize = true;
return nextImpl();
}
protected int nextImpl()
throws XmlPullParserException, IOException {
text = null;
pcEnd = pcStart = 0;
usePC = false;
bufStart = posEnd;
if (pastEndTag) {
pastEndTag = false;
--depth;
namespaceEnd = elNamespaceCount[depth]; // less namespaces available
}
if (emptyElementTag) {
emptyElementTag = false;
pastEndTag = true;
return eventType = END_TAG;
}
// [1] document ::= prolog element Misc*
if (depth > 0) {
if (seenStartTag) {
seenStartTag = false;
return eventType = parseStartTag();
}
if (seenEndTag) {
seenEndTag = false;
return eventType = parseEndTag();
}
// ASSUMPTION: we are _on_ first character of content or markup!!!!
// [43] content ::= CharData? ((element | Reference | CDSect | PI | Comment) CharData?)*
char ch;
if (seenMarkup) { // we have read ahead ...
seenMarkup = false;
ch = '<';
} else if (seenAmpersand) {
seenAmpersand = false;
ch = '&';
} else {
ch = more();
}
posStart = pos - 1; // VERY IMPORTANT: this is correct start of event!!!
// when true there is some potential event TEXT to return - keep gathering
boolean hadCharData = false;
// when true TEXT data is not continual (like <![CDATA[text]]>) and requires PC merging
boolean needsMerging = false;
MAIN_LOOP:
while (true) {
// work on MARKUP
if (ch == '<') {
if (hadCharData) {
//posEnd = pos - 1;
if (tokenize) {
seenMarkup = true;
return eventType = TEXT;
}
}
ch = more();
if (ch == '/') {
if (!tokenize && hadCharData) {
seenEndTag = true;
//posEnd = pos - 2;
return eventType = TEXT;
}
return eventType = parseEndTag();
} else if (ch == '!') {
ch = more();
if (ch == '-') {
// note: if(tokenize == false) posStart/End is NOT changed!!!!
parseComment();
if (tokenize) return eventType = COMMENT;
if (!usePC && hadCharData) {
needsMerging = true;
} else {
posStart = pos; //completely ignore comment
}
} else if (ch == '[') {
parseCDSect(hadCharData);
if (tokenize) return eventType = CDSECT;
final int cdStart = posStart;
final int cdEnd = posEnd;
final int cdLen = cdEnd - cdStart;
if (cdLen > 0) { // was there anything inside CDATA section?
hadCharData = true;
if (!usePC) {
needsMerging = true;
}
}
} else {
throw new XmlPullParserException(
"unexpected character in markup " + printable(ch), this, null);
}
} else if (ch == '?') {
parsePI();
if (tokenize) return eventType = PROCESSING_INSTRUCTION;
if (!usePC && hadCharData) {
needsMerging = true;
} else {
posStart = pos; //completely ignore PI
}
} else if (isNameStartChar(ch)) {
if (!tokenize && hadCharData) {
seenStartTag = true;
//posEnd = pos - 2;
return eventType = TEXT;
}
return eventType = parseStartTag();
} else {
throw new XmlPullParserException(
"unexpected character in markup " + printable(ch), this, null);
}
// do content compaction if it makes sense!!!!
} else if (ch == '&') {
// work on ENTITTY
//posEnd = pos - 1;
if (tokenize && hadCharData) {
seenAmpersand = true;
return eventType = TEXT;
}
final int oldStart = posStart + bufAbsoluteStart;
final int oldEnd = posEnd + bufAbsoluteStart;
final char[] resolvedEntity = parseEntityRef();
if (tokenize) return eventType = ENTITY_REF;
// check if replacement text can be resolved !!!
if (resolvedEntity == null) {
if (entityRefName == null) {
entityRefName = newString(buf, posStart, posEnd - posStart);
}
throw new XmlPullParserException(
"could not resolve entity named '" + printable(entityRefName) + "'",
this, null);
}
//int entStart = posStart;
//int entEnd = posEnd;
posStart = oldStart - bufAbsoluteStart;
posEnd = oldEnd - bufAbsoluteStart;
if (!usePC) {
if (hadCharData) {
joinPC(); // posEnd is already set correctly!!!
needsMerging = false;
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
for (int i = 0; i < resolvedEntity.length; i++) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = resolvedEntity[i];
}
hadCharData = true;
} else {
if (needsMerging) {
joinPC(); // posEnd is already set correctly!!!
needsMerging = false;
}
hadCharData = true;
boolean normalizedCR = false;
final boolean normalizeInput = tokenize == false || roundtripSupported == false;
boolean seenBracket = false;
boolean seenBracketBracket = false;
do {
if (ch == ']') {
if (seenBracket) {
seenBracketBracket = true;
} else {
seenBracket = true;
}
} else if (seenBracketBracket && ch == '>') {
throw new XmlPullParserException(
"characters ]]> are not allowed in content", this, null);
} else {
if (seenBracket) {
seenBracketBracket = seenBracket = false;
}
// assert seenTwoBrackets == seenBracket == false;
}
if (normalizeInput) {
// deal with normalization issues ...
if (ch == '\r') {
normalizedCR = true;
posEnd = pos - 1;
// posEnd is already is set
if (!usePC) {
if (posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if (ch == '\n') {
// if(!usePC) { joinPC(); } else { if(pcEnd >= pc.length) ensurePC(); }
if (!normalizedCR && usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if (usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
ch = more();
} while (ch != '<' && ch != '&');
posEnd = pos - 1;
continue MAIN_LOOP; // skip ch = more() from below - we are alreayd ahead ...
}
ch = more();
} // endless while(true)
} else {
if (seenRoot) {
return parseEpilog();
} else {
return parseProlog();
}
}
}
protected int parseProlog()
throws XmlPullParserException, IOException {
char ch;
if (seenMarkup) {
ch = buf[pos - 1];
} else {
ch = more();
}
if (eventType == START_DOCUMENT) {
// bootstrap parsing with getting first character input!
// deal with BOM
// detect BOM and drop it (Unicode int Order Mark)
if (ch == '\uFFFE') {
throw new XmlPullParserException(
"first character in input was UNICODE noncharacter (0xFFFE)" +
"- input requires int swapping", this, null);
}
if (ch == '\uFEFF') {
// skipping UNICODE int Order Mark (so called BOM)
ch = more();
}
}
seenMarkup = false;
boolean gotS = false;
posStart = pos - 1;
final boolean normalizeIgnorableWS = tokenize == true && roundtripSupported == false;
boolean normalizedCR = false;
while (true) {
// deal with Misc
// [27] Misc ::= Comment | PI | S
// deal with docdecl --> mark it!
// else parseStartTag seen <[^/]
if (ch == '<') {
if (gotS && tokenize) {
posEnd = pos - 1;
seenMarkup = true;
return eventType = IGNORABLE_WHITESPACE;
}
ch = more();
if (ch == '?') {
// check if it is 'xml'
// deal with XMLDecl
if (parsePI()) { // make sure to skip XMLDecl
if (tokenize) {
return eventType = PROCESSING_INSTRUCTION;
}
} else {
// skip over - continue tokenizing
posStart = pos;
gotS = false;
}
} else if (ch == '!') {
ch = more();
if (ch == 'D') {
if (seenDocdecl) {
throw new XmlPullParserException(
"only one docdecl allowed in XML document", this, null);
}
seenDocdecl = true;
parseDocdecl();
if (tokenize) return eventType = DOCDECL;
} else if (ch == '-') {
parseComment();
if (tokenize) return eventType = COMMENT;
} else {
throw new XmlPullParserException(
"unexpected markup <!" + printable(ch), this, null);
}
} else if (ch == '/') {
throw new XmlPullParserException(
"expected start tag name and not " + printable(ch), this, null);
} else if (isNameStartChar(ch)) {
seenRoot = true;
return parseStartTag();
} else {
throw new XmlPullParserException(
"expected start tag name and not " + printable(ch), this, null);
}
} else if (isS(ch)) {
gotS = true;
if (normalizeIgnorableWS) {
if (ch == '\r') {
normalizedCR = true;
//posEnd = pos -1;
//joinPC();
// posEnd is already is set
if (!usePC) {
posEnd = pos - 1;
if (posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if (ch == '\n') {
if (!normalizedCR && usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if (usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
} else {
throw new XmlPullParserException(
"only whitespace content allowed before start tag and not " + printable(ch),
this, null);
}
ch = more();
}
}
protected int parseEpilog()
throws XmlPullParserException, IOException {
if (eventType == END_DOCUMENT) {
throw new XmlPullParserException("already reached end of XML input", this, null);
}
if (reachedEnd) {
return eventType = END_DOCUMENT;
}
boolean gotS = false;
final boolean normalizeIgnorableWS = tokenize == true && roundtripSupported == false;
boolean normalizedCR = false;
try {
// epilog: Misc*
char ch;
if (seenMarkup) {
ch = buf[pos - 1];
} else {
ch = more();
}
seenMarkup = false;
posStart = pos - 1;
if (!reachedEnd) {
while (true) {
// deal with Misc
// [27] Misc ::= Comment | PI | S
if (ch == '<') {
if (gotS && tokenize) {
posEnd = pos - 1;
seenMarkup = true;
return eventType = IGNORABLE_WHITESPACE;
}
ch = more();
if (reachedEnd) {
break;
}
if (ch == '?') {
// check if it is 'xml'
// deal with XMLDecl
parsePI();
if (tokenize) return eventType = PROCESSING_INSTRUCTION;
} else if (ch == '!') {
ch = more();
if (reachedEnd) {
break;
}
if (ch == 'D') {
parseDocdecl(); //FIXME
if (tokenize) return eventType = DOCDECL;
} else if (ch == '-') {
parseComment();
if (tokenize) return eventType = COMMENT;
} else {
throw new XmlPullParserException(
"unexpected markup <!" + printable(ch), this, null);
}
} else if (ch == '/') {
throw new XmlPullParserException(
"end tag not allowed in epilog but got " + printable(ch), this, null);
} else if (isNameStartChar(ch)) {
throw new XmlPullParserException(
"start tag not allowed in epilog but got " + printable(ch), this, null);
} else {
throw new XmlPullParserException(
"in epilog expected ignorable content and not " + printable(ch),
this, null);
}
} else if (isS(ch)) {
gotS = true;
if (normalizeIgnorableWS) {
if (ch == '\r') {
normalizedCR = true;
//posEnd = pos -1;
//joinPC();
// posEnd is alreadys set
if (!usePC) {
posEnd = pos - 1;
if (posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if (ch == '\n') {
if (!normalizedCR && usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if (usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
} else {
throw new XmlPullParserException(
"in epilog non whitespace content is not allowed but got " + printable(ch),
this, null);
}
ch = more();
if (reachedEnd) {
break;
}
}
}
// throw Exception("unexpected content in epilog
// catch EOFException return END_DOCUEMENT
//try {
} catch (EOFException ex) {
reachedEnd = true;
}
if (reachedEnd) {
if (tokenize && gotS) {
posEnd = pos; // well - this is LAST available character pos
return eventType = IGNORABLE_WHITESPACE;
}
return eventType = END_DOCUMENT;
} else {
throw new XmlPullParserException("internal error in parseEpilog");
}
}
public int parseEndTag() throws XmlPullParserException, IOException {
//ASSUMPTION ch is past "</"
// [42] ETag ::= '</' Name S? '>'
char ch = more();
if (!isNameStartChar(ch)) {
throw new XmlPullParserException(
"expected name start and not " + printable(ch), this, null);
}
posStart = pos - 3;
final int nameStart = pos - 1 + bufAbsoluteStart;
do {
ch = more();
} while (isNameChar(ch));
// now we go one level down -- do checks
//--depth; //FIXME
// check that end tag name is the same as start tag
//String name = new String(buf, nameStart - bufAbsoluteStart,
// (pos - 1) - (nameStart - bufAbsoluteStart));
//int last = pos - 1;
int off = nameStart - bufAbsoluteStart;
//final int len = last - off;
final int len = (pos - 1) - off;
final char[] cbuf = elRawName[depth];
if (elRawNameEnd[depth] != len) {
// construct strings for exception
final String startname = new String(cbuf, 0, elRawNameEnd[depth]);
final String endname = new String(buf, off, len);
throw new XmlPullParserException(
"end tag name </" + endname + "> must match start tag name <" + startname + ">"
+ " from line " + elRawNameLine[depth], this, null);
}
for (int i = 0; i < len; i++) {
if (buf[off++] != cbuf[i]) {
// construct strings for exception
final String startname = new String(cbuf, 0, len);
final String endname = new String(buf, off - i - 1, len);
throw new XmlPullParserException(
"end tag name </" + endname + "> must be the same as start tag <" + startname + ">"
+ " from line " + elRawNameLine[depth], this, null);
}
}
while (isS(ch)) {
ch = more();
} // skip additional white spaces
if (ch != '>') {
throw new XmlPullParserException(
"expected > to finish end tag not " + printable(ch)
+ " from line " + elRawNameLine[depth], this, null);
}
//namespaceEnd = elNamespaceCount[ depth ]; //FIXME
posEnd = pos;
pastEndTag = true;
return eventType = END_TAG;
}
public int parseStartTag() throws XmlPullParserException, IOException {
//ASSUMPTION ch is past <T
// [40] STag ::= '<' Name (S Attribute)* S? '>'
// [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
++depth; //FIXME
posStart = pos - 2;
emptyElementTag = false;
attributeCount = 0;
// retrieve name
final int nameStart = pos - 1 + bufAbsoluteStart;
int colonPos = -1;
char ch = buf[pos - 1];
if (ch == ':' && processNamespaces) throw new XmlPullParserException(
"when namespaces processing enabled colon can not be at element name start",
this, null);
while (true) {
ch = more();
if (!isNameChar(ch)) break;
if (ch == ':' && processNamespaces) {
if (colonPos != -1) throw new XmlPullParserException(
"only one colon is allowed in name of element when namespaces are enabled",
this, null);
colonPos = pos - 1 + bufAbsoluteStart;
}
}
// retrieve name
ensureElementsCapacity();
//TODO check for efficient interning and then use elRawNameInterned!!!!
int elLen = (pos - 1) - (nameStart - bufAbsoluteStart);
if (elRawName[depth] == null || elRawName[depth].length < elLen) {
elRawName[depth] = new char[2 * elLen];
}
System.arraycopy(buf, nameStart - bufAbsoluteStart, elRawName[depth], 0, elLen);
elRawNameEnd[depth] = elLen;
elRawNameLine[depth] = lineNumber;
String name = null;
// work on prefixes and namespace URI
String prefix = null;
if (processNamespaces) {
if (colonPos != -1) {
prefix = elPrefix[depth] = newString(buf, nameStart - bufAbsoluteStart,
colonPos - nameStart);
name = elName[depth] = newString(buf, colonPos + 1 - bufAbsoluteStart,
//(pos -1) - (colonPos + 1));
pos - 2 - (colonPos - bufAbsoluteStart));
} else {
prefix = elPrefix[depth] = null;
name = elName[depth] = newString(buf, nameStart - bufAbsoluteStart, elLen);
}
} else {
name = elName[depth] = newString(buf, nameStart - bufAbsoluteStart, elLen);
}
while (true) {
while (isS(ch)) {
ch = more();
} // skip additional white spaces
if (ch == '>') {
break;
} else if (ch == '/') {
if (emptyElementTag) throw new XmlPullParserException(
"repeated / in tag declaration", this, null);
emptyElementTag = true;
ch = more();
if (ch != '>') throw new XmlPullParserException(
"expected > to end empty tag not " + printable(ch), this, null);
break;
} else if (isNameStartChar(ch)) {
ch = parseAttribute();
ch = more();
continue;
} else {
throw new XmlPullParserException(
"start tag unexpected character " + printable(ch), this, null);
}
//ch = more(); // skip space
}
// now when namespaces were declared we can resolve them
if (processNamespaces) {
String uri = getNamespace(prefix);
if (uri == null) {
if (prefix == null) { // no prefix and no uri => use default namespace
uri = NO_NAMESPACE;
} else {
throw new XmlPullParserException(
"could not determine namespace bound to element prefix " + prefix,
this, null);
}
}
elUri[depth] = uri;
//String uri = getNamespace(prefix);
//if(uri == null && prefix == null) { // no prefix and no uri => use default namespace
// uri = "";
//}
// resolve attribute namespaces
for (int i = 0; i < attributeCount; i++) {
final String attrPrefix = attributePrefix[i];
if (attrPrefix != null) {
final String attrUri = getNamespace(attrPrefix);
if (attrUri == null) {
throw new XmlPullParserException(
"could not determine namespace bound to attribute prefix " + attrPrefix,
this, null);
}
attributeUri[i] = attrUri;
} else {
attributeUri[i] = NO_NAMESPACE;
}
}
//TODO
//[ WFC: Unique Att Spec ]
// check attribute uniqueness constraint for attributes that has namespace!!!
for (int i = 1; i < attributeCount; i++) {
for (int j = 0; j < i; j++) {
if (attributeUri[j] == attributeUri[i]
&& (allStringsInterned && attributeName[j].equals(attributeName[i])
|| (!allStringsInterned
&& attributeNameHash[j] == attributeNameHash[i]
&& attributeName[j].equals(attributeName[i])))
) {
// prepare data for nice error message?
String attr1 = attributeName[j];
if (attributeUri[j] != null) attr1 = attributeUri[j] + ":" + attr1;
String attr2 = attributeName[i];
if (attributeUri[i] != null) attr2 = attributeUri[i] + ":" + attr2;
throw new XmlPullParserException(
"duplicated attributes " + attr1 + " and " + attr2, this, null);
}
}
}
} else { // ! processNamespaces
//[ WFC: Unique Att Spec ]
// check raw attribute uniqueness constraint!!!
for (int i = 1; i < attributeCount; i++) {
for (int j = 0; j < i; j++) {
if ((allStringsInterned && attributeName[j].equals(attributeName[i])
|| (!allStringsInterned
&& attributeNameHash[j] == attributeNameHash[i]
&& attributeName[j].equals(attributeName[i])))
) {
// prepare data for nice error message?
final String attr1 = attributeName[j];
final String attr2 = attributeName[i];
throw new XmlPullParserException(
"duplicated attributes " + attr1 + " and " + attr2, this, null);
}
}
}
}
elNamespaceCount[depth] = namespaceEnd;
posEnd = pos;
return eventType = START_TAG;
}
protected char parseAttribute() throws XmlPullParserException, IOException {
// parse attribute
// [41] Attribute ::= Name Eq AttValue
// [WFC: No External Entity References]
// [WFC: No < in Attribute Values]
final int prevPosStart = posStart + bufAbsoluteStart;
final int nameStart = pos - 1 + bufAbsoluteStart;
int colonPos = -1;
char ch = buf[pos - 1];
if (ch == ':' && processNamespaces) throw new XmlPullParserException(
"when namespaces processing enabled colon can not be at attribute name start",
this, null);
boolean startsWithXmlns = processNamespaces && ch == 'x';
int xmlnsPos = 0;
ch = more();
while (isNameChar(ch)) {
if (processNamespaces) {
if (startsWithXmlns && xmlnsPos < 5) {
++xmlnsPos;
if (xmlnsPos == 1) {
if (ch != 'm') startsWithXmlns = false;
} else if (xmlnsPos == 2) {
if (ch != 'l') startsWithXmlns = false;
} else if (xmlnsPos == 3) {
if (ch != 'n') startsWithXmlns = false;
} else if (xmlnsPos == 4) {
if (ch != 's') startsWithXmlns = false;
} else if (xmlnsPos == 5) {
if (ch != ':') throw new XmlPullParserException(
"after xmlns in attribute name must be colon"
+ "when namespaces are enabled", this, null);
//colonPos = pos - 1 + bufAbsoluteStart;
}
}
if (ch == ':') {
if (colonPos != -1) throw new XmlPullParserException(
"only one colon is allowed in attribute name"
+ " when namespaces are enabled", this, null);
colonPos = pos - 1 + bufAbsoluteStart;
}
}
ch = more();
}
ensureAttributesCapacity(attributeCount);
// --- start processing attributes
String name = null;
String prefix = null;
// work on prefixes and namespace URI
if (processNamespaces) {
if (xmlnsPos < 4) startsWithXmlns = false;
if (startsWithXmlns) {
if (colonPos != -1) {
//prefix = attributePrefix[ attributeCount ] = null;
final int nameLen = pos - 2 - (colonPos - bufAbsoluteStart);
if (nameLen == 0) {
throw new XmlPullParserException(
"namespace prefix is required after xmlns: "
+ " when namespaces are enabled", this, null);
}
name = //attributeName[ attributeCount ] =
newString(buf, colonPos - bufAbsoluteStart + 1, nameLen);
//pos - 1 - (colonPos + 1 - bufAbsoluteStart)
}
} else {
if (colonPos != -1) {
int prefixLen = colonPos - nameStart;
prefix = attributePrefix[attributeCount] =
newString(buf, nameStart - bufAbsoluteStart, prefixLen);
//colonPos - (nameStart - bufAbsoluteStart));
int nameLen = pos - 2 - (colonPos - bufAbsoluteStart);
name = attributeName[attributeCount] =
newString(buf, colonPos - bufAbsoluteStart + 1, nameLen);
//pos - 1 - (colonPos + 1 - bufAbsoluteStart));
//name.substring(0, colonPos-nameStart);
} else {
prefix = attributePrefix[attributeCount] = null;
name = attributeName[attributeCount] =
newString(buf, nameStart - bufAbsoluteStart,
pos - 1 - (nameStart - bufAbsoluteStart));
}
if (!allStringsInterned) {
attributeNameHash[attributeCount] = name.hashCode();
}
}
} else {
// retrieve name
name = attributeName[attributeCount] =
newString(buf, nameStart - bufAbsoluteStart,
pos - 1 - (nameStart - bufAbsoluteStart));
////assert name != null;
if (!allStringsInterned) {
attributeNameHash[attributeCount] = name.hashCode();
}
}
// [25] Eq ::= S? '=' S?
while (isS(ch)) {
ch = more();
} // skip additional spaces
if (ch != '=') throw new XmlPullParserException(
"expected = after attribute name", this, null);
ch = more();
while (isS(ch)) {
ch = more();
} // skip additional spaces
// [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
// | "'" ([^<&'] | Reference)* "'"
final char delimit = ch;
if (delimit != '"' && delimit != '\'') throw new XmlPullParserException(
"attribute value must start with quotation or apostrophe not "
+ printable(delimit), this, null);
// parse until delimit or < and resolve Reference
//[67] Reference ::= EntityRef | CharRef
//int valueStart = pos + bufAbsoluteStart;
boolean normalizedCR = false;
usePC = false;
pcStart = pcEnd;
posStart = pos;
while (true) {
ch = more();
if (ch == delimit) {
break;
}
if (ch == '<') {
throw new XmlPullParserException(
"markup not allowed inside attribute value - illegal < ", this, null);
}
if (ch == '&') {
// extractEntityRef
posEnd = pos - 1;
if (!usePC) {
final boolean hadCharData = posEnd > posStart;
if (hadCharData) {
// posEnd is already set correctly!!!
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
final char[] resolvedEntity = parseEntityRef();
// check if replacement text can be resolved !!!
if (resolvedEntity == null) {
if (entityRefName == null) {
entityRefName = newString(buf, posStart, posEnd - posStart);
}
throw new XmlPullParserException(
"could not resolve entity named '" + printable(entityRefName) + "'",
this, null);
}
// write into PC replacement text - do merge for replacement text!!!!
for (int i = 0; i < resolvedEntity.length; i++) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = resolvedEntity[i];
}
} else if (ch == '\t' || ch == '\n' || ch == '\r') {
// do attribute value normalization
// as described in http://www.w3.org/TR/REC-xml#AVNormalize
// TODO add test for it form spec ...
// handle EOL normalization ...
if (!usePC) {
posEnd = pos - 1;
if (posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcEnd = pcStart = 0;
}
}
//assert usePC == true;
if (pcEnd >= pc.length) ensurePC(pcEnd);
if (ch != '\n' || !normalizedCR) {
pc[pcEnd++] = ' '; //'\n';
}
} else {
if (usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
}
normalizedCR = ch == '\r';
}
if (processNamespaces && startsWithXmlns) {
String ns = null;
if (!usePC) {
ns = newStringIntern(buf, posStart, pos - 1 - posStart);
} else {
ns = newStringIntern(pc, pcStart, pcEnd - pcStart);
}
ensureNamespacesCapacity(namespaceEnd);
int prefixHash = -1;
if (colonPos != -1) {
if (ns.length() == 0) {
throw new XmlPullParserException(
"non-default namespace can not be declared to be empty string", this, null);
}
// declare new namespace
namespacePrefix[namespaceEnd] = name;
if (!allStringsInterned) {
prefixHash = namespacePrefixHash[namespaceEnd] = name.hashCode();
}
} else {
// declare new default namespace ...
namespacePrefix[namespaceEnd] = null; //""; //null; //TODO check FIXME Alek
if (!allStringsInterned) {
prefixHash = namespacePrefixHash[namespaceEnd] = -1;
}
}
namespaceUri[namespaceEnd] = ns;
// detect duplicate namespace declarations!!!
final int startNs = elNamespaceCount[depth - 1];
for (int i = namespaceEnd - 1; i >= startNs; --i) {
if (((allStringsInterned || name == null) && namespacePrefix[i] == name)
|| (!allStringsInterned && name != null &&
namespacePrefixHash[i] == prefixHash
&& name.equals(namespacePrefix[i])
)) {
final String s = name == null ? "default" : "'" + name + "'";
throw new XmlPullParserException(
"duplicated namespace declaration for " + s + " prefix", this, null);
}
}
++namespaceEnd;
} else {
if (!usePC) {
attributeValue[attributeCount] =
new String(buf, posStart, pos - 1 - posStart);
} else {
attributeValue[attributeCount] =
new String(pc, pcStart, pcEnd - pcStart);
}
++attributeCount;
}
posStart = prevPosStart - bufAbsoluteStart;
return ch;
}
protected char[] charRefOneCharBuf = new char[1];
protected char[] parseEntityRef()
throws XmlPullParserException, IOException {
// entity reference http://www.w3.org/TR/2000/REC-xml-20001006#NT-Reference
// [67] Reference ::= EntityRef | CharRef
// ASSUMPTION just after &
entityRefName = null;
posStart = pos;
char ch = more();
if (ch == '#') {
// parse character reference
char charRef = 0;
ch = more();
if (ch == 'x') {
//encoded in hex
while (true) {
ch = more();
if (ch >= '0' && ch <= '9') {
charRef = (char) (charRef * 16 + (ch - '0'));
} else if (ch >= 'a' && ch <= 'f') {
charRef = (char) (charRef * 16 + (ch - ('a' - 10)));
} else if (ch >= 'A' && ch <= 'F') {
charRef = (char) (charRef * 16 + (ch - ('A' - 10)));
} else if (ch == ';') {
break;
} else {
throw new XmlPullParserException(
"character reference (with hex value) may not contain "
+ printable(ch), this, null);
}
}
} else {
// encoded in decimal
while (true) {
if (ch >= '0' && ch <= '9') {
charRef = (char) (charRef * 10 + (ch - '0'));
} else if (ch == ';') {
break;
} else {
throw new XmlPullParserException(
"character reference (with decimal value) may not contain "
+ printable(ch), this, null);
}
ch = more();
}
}
posEnd = pos - 1;
charRefOneCharBuf[0] = charRef;
if (tokenize) {
text = newString(charRefOneCharBuf, 0, 1);
}
return charRefOneCharBuf;
} else {
// [68] EntityRef ::= '&' Name ';'
// scan name until ;
if (!isNameStartChar(ch)) {
throw new XmlPullParserException(
"entity reference names can not start with character '"
+ printable(ch) + "'", this, null);
}
while (true) {
ch = more();
if (ch == ';') {
break;
}
if (!isNameChar(ch)) {
throw new XmlPullParserException(
"entity reference name can not contain character "
+ printable(ch) + "'", this, null);
}
}
posEnd = pos - 1;
// determine what name maps to
final int len = posEnd - posStart;
if (len == 2 && buf[posStart] == 'l' && buf[posStart + 1] == 't') {
if (tokenize) {
text = "<";
}
charRefOneCharBuf[0] = '<';
return charRefOneCharBuf;
//if(paramPC || isParserTokenizing) {
// if(pcEnd >= pc.length) ensurePC();
// pc[pcEnd++] = '<';
//}
} else if (len == 3 && buf[posStart] == 'a'
&& buf[posStart + 1] == 'm' && buf[posStart + 2] == 'p') {
if (tokenize) {
text = "&";
}
charRefOneCharBuf[0] = '&';
return charRefOneCharBuf;
} else if (len == 2 && buf[posStart] == 'g' && buf[posStart + 1] == 't') {
if (tokenize) {
text = ">";
}
charRefOneCharBuf[0] = '>';
return charRefOneCharBuf;
} else if (len == 4 && buf[posStart] == 'a' && buf[posStart + 1] == 'p'
&& buf[posStart + 2] == 'o' && buf[posStart + 3] == 's') {
if (tokenize) {
text = "'";
}
charRefOneCharBuf[0] = '\'';
return charRefOneCharBuf;
} else if (len == 4 && buf[posStart] == 'q' && buf[posStart + 1] == 'u'
&& buf[posStart + 2] == 'o' && buf[posStart + 3] == 't') {
if (tokenize) {
text = "\"";
}
charRefOneCharBuf[0] = '"';
return charRefOneCharBuf;
} else {
final char[] result = lookuEntityReplacement(len);
if (result != null) {
return result;
}
}
if (tokenize) text = null;
return null;
}
}
protected char[] lookuEntityReplacement(int entitNameLen)
throws XmlPullParserException, IOException {
if (!allStringsInterned) {
final int hash = fastHash(buf, posStart, posEnd - posStart);
LOOP:
for (int i = entityEnd - 1; i >= 0; --i) {
if (hash == entityNameHash[i] && entitNameLen == entityNameBuf[i].length) {
final char[] entityBuf = entityNameBuf[i];
for (int j = 0; j < entitNameLen; j++) {
if (buf[posStart + j] != entityBuf[j]) continue LOOP;
}
if (tokenize) text = entityReplacement[i];
return entityReplacementBuf[i];
}
}
} else {
entityRefName = newString(buf, posStart, posEnd - posStart);
for (int i = entityEnd - 1; i >= 0; --i) {
// take advantage that interning for newStirng is enforced
if (entityRefName == entityName[i]) {
if (tokenize) text = entityReplacement[i];
return entityReplacementBuf[i];
}
}
}
return null;
}
protected void parseComment()
throws XmlPullParserException, IOException {
// implements XML 1.0 Section 2.5 Comments
//ASSUMPTION: seen <!-
char ch = more();
if (ch != '-') throw new XmlPullParserException(
"expected <!-- for comment start", this, null);
if (tokenize) posStart = pos;
final int curLine = lineNumber;
final int curColumn = columnNumber;
try {
final boolean normalizeIgnorableWS = tokenize == true && roundtripSupported == false;
boolean normalizedCR = false;
boolean seenDash = false;
boolean seenDashDash = false;
while (true) {
// scan until it hits -->
ch = more();
if (seenDashDash && ch != '>') {
throw new XmlPullParserException(
"in comment after two dashes (--) next character must be >"
+ " not " + printable(ch), this, null);
}
if (ch == '-') {
if (!seenDash) {
seenDash = true;
} else {
seenDashDash = true;
seenDash = false;
}
} else if (ch == '>') {
if (seenDashDash) {
break; // found end sequence!!!!
} else {
seenDashDash = false;
}
seenDash = false;
} else {
seenDash = false;
}
if (normalizeIgnorableWS) {
if (ch == '\r') {
normalizedCR = true;
//posEnd = pos -1;
//joinPC();
// posEnd is already set
if (!usePC) {
posEnd = pos - 1;
if (posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if (ch == '\n') {
if (!normalizedCR && usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if (usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
}
} catch (EOFException ex) {
// detect EOF and create meaningful error ...
throw new XmlPullParserException(
"comment started on line " + curLine + " and column " + curColumn + " was not closed",
this, ex);
}
if (tokenize) {
posEnd = pos - 3;
if (usePC) {
pcEnd -= 2;
}
}
}
protected boolean parsePI()
throws XmlPullParserException, IOException {
// implements XML 1.0 Section 2.6 Processing Instructions
// [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
// [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
//ASSUMPTION: seen <?
if (tokenize) posStart = pos;
final int curLine = lineNumber;
final int curColumn = columnNumber;
int piTargetStart = pos + bufAbsoluteStart;
int piTargetEnd = -1;
final boolean normalizeIgnorableWS = tokenize == true && roundtripSupported == false;
boolean normalizedCR = false;
try {
boolean seenQ = false;
char ch = more();
if (isS(ch)) {
throw new XmlPullParserException(
"processing instruction PITarget must be exactly after <? and not white space character",
this, null);
}
while (true) {
// scan until it hits ?>
//ch = more();
if (ch == '?') {
seenQ = true;
} else if (ch == '>') {
if (seenQ) {
break; // found end sequence!!!!
}
seenQ = false;
} else {
if (piTargetEnd == -1 && isS(ch)) {
piTargetEnd = pos - 1 + bufAbsoluteStart;
// [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
if ((piTargetEnd - piTargetStart) == 3) {
if ((buf[piTargetStart] == 'x' || buf[piTargetStart] == 'X')
&& (buf[piTargetStart + 1] == 'm' || buf[piTargetStart + 1] == 'M')
&& (buf[piTargetStart + 2] == 'l' || buf[piTargetStart + 2] == 'L')
) {
if (piTargetStart > 3) { //<?xml is allowed as first characters in input ...
throw new XmlPullParserException(
"processing instruction can not have PITarget with reserveld xml name",
this, null);
} else {
if (buf[piTargetStart] != 'x'
&& buf[piTargetStart + 1] != 'm'
&& buf[piTargetStart + 2] != 'l') {
throw new XmlPullParserException(
"XMLDecl must have xml name in lowercase",
this, null);
}
}
parseXmlDecl(ch);
if (tokenize) posEnd = pos - 2;
final int off = piTargetStart - bufAbsoluteStart + 3;
final int len = pos - 2 - off;
xmlDeclContent = newString(buf, off, len);
return false;
}
}
}
seenQ = false;
}
if (normalizeIgnorableWS) {
if (ch == '\r') {
normalizedCR = true;
//posEnd = pos -1;
//joinPC();
// posEnd is already set
if (!usePC) {
posEnd = pos - 1;
if (posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if (ch == '\n') {
if (!normalizedCR && usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if (usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
ch = more();
}
} catch (EOFException ex) {
// detect EOF and create meaningful error ...
throw new XmlPullParserException(
"processing instruction started on line " + curLine + " and column " + curColumn
+ " was not closed",
this, ex);
}
if (piTargetEnd == -1) {
piTargetEnd = pos - 2 + bufAbsoluteStart;
//throw new XmlPullParserException(
// "processing instruction must have PITarget name", this, null);
}
piTargetStart -= bufAbsoluteStart;
piTargetEnd -= bufAbsoluteStart;
if (tokenize) {
posEnd = pos - 2;
if (normalizeIgnorableWS) {
--pcEnd;
}
}
return true;
}
// protected final static char[] VERSION = {'v','e','r','s','i','o','n'};
// protected final static char[] NCODING = {'n','c','o','d','i','n','g'};
// protected final static char[] TANDALONE = {'t','a','n','d','a','l','o','n','e'};
// protected final static char[] YES = {'y','e','s'};
// protected final static char[] NO = {'n','o'};
protected final static char[] VERSION = "version".toCharArray();
protected final static char[] NCODING = "ncoding".toCharArray();
protected final static char[] TANDALONE = "tandalone".toCharArray();
protected final static char[] YES = "yes".toCharArray();
protected final static char[] NO = "no".toCharArray();
protected void parseXmlDecl(char ch)
throws XmlPullParserException, IOException {
// [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
// first make sure that relative positions will stay OK
preventBufferCompaction = true;
bufStart = 0; // necessary to keep pos unchanged during expansion!
// --- parse VersionInfo
// [24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
// parse is positioned just on first S past <?xml
ch = skipS(ch);
ch = requireInput(ch, VERSION);
// [25] Eq ::= S? '=' S?
ch = skipS(ch);
if (ch != '=') {
throw new XmlPullParserException(
"expected equals sign (=) after version and not " + printable(ch), this, null);
}
ch = more();
ch = skipS(ch);
if (ch != '\'' && ch != '"') {
throw new XmlPullParserException(
"expected apostrophe (') or quotation mark (\") after version and not "
+ printable(ch), this, null);
}
final char quotChar = ch;
//int versionStart = pos + bufAbsoluteStart; // required if preventBufferCompaction==false
final int versionStart = pos;
ch = more();
// [26] VersionNum ::= ([a-zA-Z0-9_.:] | '-')+
while (ch != quotChar) {
if ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9')
&& ch != '_' && ch != '.' && ch != ':' && ch != '-') {
throw new XmlPullParserException(
"<?xml version value expected to be in ([a-zA-Z0-9_.:] | '-')"
+ " not " + printable(ch), this, null);
}
ch = more();
}
final int versionEnd = pos - 1;
parseXmlDeclWithVersion(versionStart, versionEnd);
preventBufferCompaction = false; // alow again buffer commpaction - pos MAY chnage
}
protected void parseXmlDeclWithVersion(int versionStart, int versionEnd)
throws XmlPullParserException, IOException {
String oldEncoding = this.inputEncoding;
// check version is "1.0"
if ((versionEnd - versionStart != 3)
|| buf[versionStart] != '1'
|| buf[versionStart + 1] != '.'
|| buf[versionStart + 2] != '0') {
throw new XmlPullParserException(
"only 1.0 is supported as <?xml version not '"
+ printable(new String(buf, versionStart, versionEnd - versionStart)) + "'", this, null);
}
xmlDeclVersion = newString(buf, versionStart, versionEnd - versionStart);
// [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" )
char ch = more();
ch = skipS(ch);
if (ch == 'e') {
ch = more();
ch = requireInput(ch, NCODING);
ch = skipS(ch);
if (ch != '=') {
throw new XmlPullParserException(
"expected equals sign (=) after encoding and not " + printable(ch), this, null);
}
ch = more();
ch = skipS(ch);
if (ch != '\'' && ch != '"') {
throw new XmlPullParserException(
"expected apostrophe (') or quotation mark (\") after encoding and not "
+ printable(ch), this, null);
}
final char quotChar = ch;
final int encodingStart = pos;
ch = more();
// [81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
if ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z')) {
throw new XmlPullParserException(
"<?xml encoding name expected to start with [A-Za-z]"
+ " not " + printable(ch), this, null);
}
ch = more();
while (ch != quotChar) {
if ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9')
&& ch != '.' && ch != '_' && ch != '-') {
throw new XmlPullParserException(
"<?xml encoding value expected to be in ([A-Za-z0-9._] | '-')"
+ " not " + printable(ch), this, null);
}
ch = more();
}
final int encodingEnd = pos - 1;
// TODO reconcile with setInput encodingName
inputEncoding = newString(buf, encodingStart, encodingEnd - encodingStart);
ch = more();
}
ch = skipS(ch);
// [32] SDDecl ::= S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"'))
if (ch == 's') {
ch = more();
ch = requireInput(ch, TANDALONE);
ch = skipS(ch);
if (ch != '=') {
throw new XmlPullParserException(
"expected equals sign (=) after standalone and not " + printable(ch),
this, null);
}
ch = more();
ch = skipS(ch);
if (ch != '\'' && ch != '"') {
throw new XmlPullParserException(
"expected apostrophe (') or quotation mark (\") after encoding and not "
+ printable(ch), this, null);
}
char quotChar = ch;
int standaloneStart = pos;
ch = more();
if (ch == 'y') {
ch = requireInput(ch, YES);
//Boolean standalone = new Boolean(true);
xmlDeclStandalone = new Boolean(true);
} else if (ch == 'n') {
ch = requireInput(ch, NO);
//Boolean standalone = new Boolean(false);
xmlDeclStandalone = new Boolean(false);
} else {
throw new XmlPullParserException(
"expected 'yes' or 'no' after standalone and not "
+ printable(ch), this, null);
}
if (ch != quotChar) {
throw new XmlPullParserException(
"expected " + quotChar + " after standalone value not "
+ printable(ch), this, null);
}
ch = more();
}
ch = skipS(ch);
if (ch != '?') {
throw new XmlPullParserException(
"expected ?> as last part of <?xml not "
+ printable(ch), this, null);
}
ch = more();
if (ch != '>') {
throw new XmlPullParserException(
"expected ?> as last part of <?xml not "
+ printable(ch), this, null);
}
}
protected void parseDocdecl()
throws XmlPullParserException, IOException {
//ASSUMPTION: seen <!D
char ch = more();
if (ch != 'O') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
ch = more();
if (ch != 'C') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
ch = more();
if (ch != 'T') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
ch = more();
if (ch != 'Y') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
ch = more();
if (ch != 'P') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
ch = more();
if (ch != 'E') throw new XmlPullParserException(
"expected <!DOCTYPE", this, null);
posStart = pos;
// do simple and crude scanning for end of doctype
// [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S? ('['
// (markupdecl | DeclSep)* ']' S?)? '>'
int bracketLevel = 0;
final boolean normalizeIgnorableWS = tokenize == true && roundtripSupported == false;
boolean normalizedCR = false;
while (true) {
ch = more();
if (ch == '[') ++bracketLevel;
if (ch == ']') --bracketLevel;
if (ch == '>' && bracketLevel == 0) break;
if (normalizeIgnorableWS) {
if (ch == '\r') {
normalizedCR = true;
//posEnd = pos -1;
//joinPC();
// posEnd is alreadys set
if (!usePC) {
posEnd = pos - 1;
if (posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if (ch == '\n') {
if (!normalizedCR && usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if (usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
}
posEnd = pos - 1;
}
protected void parseCDSect(boolean hadCharData)
throws XmlPullParserException, IOException {
// implements XML 1.0 Section 2.7 CDATA Sections
// [18] CDSect ::= CDStart CData CDEnd
// [19] CDStart ::= '<![CDATA['
// [20] CData ::= (Char* - (Char* ']]>' Char*))
// [21] CDEnd ::= ']]>'
//ASSUMPTION: seen <![
char ch = more();
if (ch != 'C') throw new XmlPullParserException(
"expected <[CDATA[ for comment start", this, null);
ch = more();
if (ch != 'D') throw new XmlPullParserException(
"expected <[CDATA[ for comment start", this, null);
ch = more();
if (ch != 'A') throw new XmlPullParserException(
"expected <[CDATA[ for comment start", this, null);
ch = more();
if (ch != 'T') throw new XmlPullParserException(
"expected <[CDATA[ for comment start", this, null);
ch = more();
if (ch != 'A') throw new XmlPullParserException(
"expected <[CDATA[ for comment start", this, null);
ch = more();
if (ch != '[') throw new XmlPullParserException(
"expected <![CDATA[ for comment start", this, null);
//if(tokenize) {
final int cdStart = pos + bufAbsoluteStart;
final int curLine = lineNumber;
final int curColumn = columnNumber;
final boolean normalizeInput = tokenize == false || roundtripSupported == false;
try {
if (normalizeInput) {
if (hadCharData) {
if (!usePC) {
// posEnd is correct already!!!
if (posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
}
}
boolean seenBracket = false;
boolean seenBracketBracket = false;
boolean normalizedCR = false;
while (true) {
// scan until it hits "]]>"
ch = more();
if (ch == ']') {
if (!seenBracket) {
seenBracket = true;
} else {
seenBracketBracket = true;
//seenBracket = false;
}
} else if (ch == '>') {
if (seenBracket && seenBracketBracket) {
break; // found end sequence!!!!
} else {
seenBracketBracket = false;
}
seenBracket = false;
} else {
if (seenBracket) {
seenBracket = false;
}
}
if (normalizeInput) {
// deal with normalization issues ...
if (ch == '\r') {
normalizedCR = true;
posStart = cdStart - bufAbsoluteStart;
posEnd = pos - 1; // posEnd is alreadys set
if (!usePC) {
if (posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if (ch == '\n') {
if (!normalizedCR && usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if (usePC) {
if (pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
}
} catch (EOFException ex) {
// detect EOF and create meaningful error ...
throw new XmlPullParserException(
"CDATA section started on line " + curLine + " and column " + curColumn + " was not closed",
this, ex);
}
if (normalizeInput) {
if (usePC) {
pcEnd = pcEnd - 2;
}
}
posStart = cdStart - bufAbsoluteStart;
posEnd = pos - 3;
}
protected void fillBuf() throws IOException, XmlPullParserException {
if (reader == null) throw new XmlPullParserException(
"reader must be set before parsing is started");
// see if we are in compaction area
if (bufEnd > bufSoftLimit) {
// expand buffer it makes sense!!!!
boolean compact = bufStart > bufSoftLimit;
boolean expand = false;
if (preventBufferCompaction) {
compact = false;
expand = true;
} else if (!compact) {
//freeSpace
if (bufStart < buf.length / 2) {
// less then half buffer available forcompactin --> expand instead!!!
expand = true;
} else {
// at least half of buffer can be reclaimed --> worthwhile effort!!!
compact = true;
}
}
// if buffer almost full then compact it
if (compact) {
//TODO: look on trashing
// //assert bufStart > 0
System.arraycopy(buf, bufStart, buf, 0, bufEnd - bufStart);
if (TRACE_SIZING) System.out.println(
"TRACE_SIZING fillBuf() compacting " + bufStart
+ " bufEnd=" + bufEnd
+ " pos=" + pos + " posStart=" + posStart + " posEnd=" + posEnd
+ " buf first 100 chars:" + new String(buf, bufStart,
bufEnd - bufStart < 100 ? bufEnd - bufStart : 100));
} else if (expand) {
final int newSize = 2 * buf.length;
final char newBuf[] = new char[newSize];
if (TRACE_SIZING) System.out.println("TRACE_SIZING fillBuf() " + buf.length + " => " + newSize);
System.arraycopy(buf, bufStart, newBuf, 0, bufEnd - bufStart);
buf = newBuf;
if (bufLoadFactor > 0) {
//bufSoftLimit = ( bufLoadFactor * buf.length ) /100;
bufSoftLimit = (int) ((((long) bufLoadFactor) * buf.length) / 100);
}
} else {
throw new XmlPullParserException("internal error in fillBuffer()");
}
bufEnd -= bufStart;
pos -= bufStart;
posStart -= bufStart;
posEnd -= bufStart;
bufAbsoluteStart += bufStart;
bufStart = 0;
if (TRACE_SIZING) System.out.println(
"TRACE_SIZING fillBuf() after bufEnd=" + bufEnd
+ " pos=" + pos + " posStart=" + posStart + " posEnd=" + posEnd
+ " buf first 100 chars:" + new String(buf, 0, bufEnd < 100 ? bufEnd : 100));
}
// at least one character must be read or error
final int len = buf.length - bufEnd > READ_CHUNK_SIZE ? READ_CHUNK_SIZE : buf.length - bufEnd;
final int ret = reader.read(buf, bufEnd, len);
if (ret > 0) {
bufEnd += ret;
if (TRACE_SIZING) System.out.println(
"TRACE_SIZING fillBuf() after filling in buffer"
+ " buf first 100 chars:" + new String(buf, 0, bufEnd < 100 ? bufEnd : 100));
return;
}
if (ret == -1) {
if (bufAbsoluteStart == 0 && pos == 0) {
throw new EOFException("input contained no data");
} else {
if (seenRoot && depth == 0) { // inside parsing epilog!!!
reachedEnd = true;
return;
} else {
StringBuilder expectedTagStack = new StringBuilder();
if (depth > 0) {
//final char[] cbuf = elRawName[depth];
//final String startname = new String(cbuf, 0, elRawNameEnd[depth]);
expectedTagStack.append(" - expected end tag");
if (depth > 1) {
expectedTagStack.append("s"); //more than one end tag
}
expectedTagStack.append(" ");
for (int i = depth; i > 0; i--) {
String tagName = new String(elRawName[i], 0, elRawNameEnd[i]);
expectedTagStack.append("</").append(tagName).append('>');
}
expectedTagStack.append(" to close");
for (int i = depth; i > 0; i--) {
if (i != depth) {
expectedTagStack.append(" and"); //more than one end tag
}
String tagName = new String(elRawName[i], 0, elRawNameEnd[i]);
expectedTagStack.append(" start tag <" + tagName + ">");
expectedTagStack.append(" from line " + elRawNameLine[i]);
}
expectedTagStack.append(", parser stopped on");
}
throw new EOFException("no more data available"
+ expectedTagStack.toString() + getPositionDescription());
}
}
} else {
throw new IOException("error reading input, returned " + ret);
}
}
protected char more() throws IOException, XmlPullParserException {
if (pos >= bufEnd) {
fillBuf();
// this return value should be ignonored as it is used in epilog parsing ...
if (reachedEnd) return (char) -1;
}
final char ch = buf[pos++];
//line/columnNumber
if (ch == '\n') {
++lineNumber;
columnNumber = 1;
} else {
++columnNumber;
}
//System.out.print(ch);
return ch;
}
// /**
// * This function returns position of parser in XML input stream
// * (how many <b>characters</b> were processed.
// * <p><b>NOTE:</b> this logical position and not byte offset as encodings
// * such as UTF8 may use more than one byte to encode one character.
// */
// public int getCurrentInputPosition() {
// return pos + bufAbsoluteStart;
// }
protected void ensurePC(int end) {
//assert end >= pc.length;
final int newSize = end > READ_CHUNK_SIZE ? 2 * end : 2 * READ_CHUNK_SIZE;
final char[] newPC = new char[newSize];
if (TRACE_SIZING) System.out.println("TRACE_SIZING ensurePC() " + pc.length + " ==> " + newSize + " end=" + end);
System.arraycopy(pc, 0, newPC, 0, pcEnd);
pc = newPC;
//assert end < pc.length;
}
protected void joinPC() {
//assert usePC == false;
//assert posEnd > posStart;
final int len = posEnd - posStart;
final int newEnd = pcEnd + len + 1;
if (newEnd >= pc.length) ensurePC(newEnd); // add 1 for extra space for one char
//assert newEnd < pc.length;
System.arraycopy(buf, posStart, pc, pcEnd, len);
pcEnd += len;
usePC = true;
}
protected char requireInput(char ch, char[] input)
throws XmlPullParserException, IOException {
for (int i = 0; i < input.length; i++) {
if (ch != input[i]) {
throw new XmlPullParserException(
"expected " + printable(input[i]) + " in " + new String(input)
+ " and not " + printable(ch), this, null);
}
ch = more();
}
return ch;
}
protected char requireNextS()
throws XmlPullParserException, IOException {
final char ch = more();
if (!isS(ch)) {
throw new XmlPullParserException(
"white space is required and not " + printable(ch), this, null);
}
return skipS(ch);
}
protected char skipS(char ch)
throws XmlPullParserException, IOException {
while (isS(ch)) {
ch = more();
} // skip additional spaces
return ch;
}
// nameStart / name lookup tables based on XML 1.1 http://www.w3.org/TR/2001/WD-xml11-20011213/
protected static final int LOOKUP_MAX = 0x400;
protected static final char LOOKUP_MAX_CHAR = (char) LOOKUP_MAX;
// protected static int lookupNameStartChar[] = new int[ LOOKUP_MAX_CHAR / 32 ];
// protected static int lookupNameChar[] = new int[ LOOKUP_MAX_CHAR / 32 ];
protected static boolean lookupNameStartChar[] = new boolean[LOOKUP_MAX];
protected static boolean lookupNameChar[] = new boolean[LOOKUP_MAX];
private static final void setName(char ch)
//{ lookupNameChar[ (int)ch / 32 ] |= (1 << (ch % 32)); }
{
lookupNameChar[ch] = true;
}
private static final void setNameStart(char ch)
//{ lookupNameStartChar[ (int)ch / 32 ] |= (1 << (ch % 32)); setName(ch); }
{
lookupNameStartChar[ch] = true;
setName(ch);
}
static {
setNameStart(':');
for (char ch = 'A'; ch <= 'Z'; ++ch) setNameStart(ch);
setNameStart('_');
for (char ch = 'a'; ch <= 'z'; ++ch) setNameStart(ch);
for (char ch = '\u00c0'; ch <= '\u02FF'; ++ch) setNameStart(ch);
for (char ch = '\u0370'; ch <= '\u037d'; ++ch) setNameStart(ch);
for (char ch = '\u037f'; ch < '\u0400'; ++ch) setNameStart(ch);
setName('-');
setName('.');
for (char ch = '0'; ch <= '9'; ++ch) setName(ch);
setName('\u00b7');
for (char ch = '\u0300'; ch <= '\u036f'; ++ch) setName(ch);
}
//private final static boolean isNameStartChar(char ch) {
protected boolean isNameStartChar(char ch) {
return (ch < LOOKUP_MAX_CHAR && lookupNameStartChar[ch])
|| (ch >= LOOKUP_MAX_CHAR && ch <= '\u2027')
|| (ch >= '\u202A' && ch <= '\u218F')
|| (ch >= '\u2800' && ch <= '\uFFEF')
;
// if(ch < LOOKUP_MAX_CHAR) return lookupNameStartChar[ ch ];
// else return ch <= '\u2027'
// || (ch >= '\u202A' && ch <= '\u218F')
// || (ch >= '\u2800' && ch <= '\uFFEF')
// ;
//return false;
// return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == ':'
// || (ch >= '0' && ch <= '9');
// if(ch < LOOKUP_MAX_CHAR) return (lookupNameStartChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0;
// if(ch <= '\u2027') return true;
// //[#x202A-#x218F]
// if(ch < '\u202A') return false;
// if(ch <= '\u218F') return true;
// // added pairts [#x2800-#xD7FF] | [#xE000-#xFDCF] | [#xFDE0-#xFFEF] | [#x10000-#x10FFFF]
// if(ch < '\u2800') return false;
// if(ch <= '\uFFEF') return true;
// return false;
// else return (supportXml11 && ( (ch < '\u2027') || (ch > '\u2029' && ch < '\u2200') ...
}
//private final static boolean isNameChar(char ch) {
protected boolean isNameChar(char ch) {
//return isNameStartChar(ch);
// if(ch < LOOKUP_MAX_CHAR) return (lookupNameChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0;
return (ch < LOOKUP_MAX_CHAR && lookupNameChar[ch])
|| (ch >= LOOKUP_MAX_CHAR && ch <= '\u2027')
|| (ch >= '\u202A' && ch <= '\u218F')
|| (ch >= '\u2800' && ch <= '\uFFEF')
;
//return false;
// return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == ':'
// || (ch >= '0' && ch <= '9');
// if(ch < LOOKUP_MAX_CHAR) return (lookupNameStartChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0;
//else return
// else if(ch <= '\u2027') return true;
// //[#x202A-#x218F]
// else if(ch < '\u202A') return false;
// else if(ch <= '\u218F') return true;
// // added pairts [#x2800-#xD7FF] | [#xE000-#xFDCF] | [#xFDE0-#xFFEF] | [#x10000-#x10FFFF]
// else if(ch < '\u2800') return false;
// else if(ch <= '\uFFEF') return true;
//else return false;
}
protected boolean isS(char ch) {
return (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t');
// || (supportXml11 && (ch == '\u0085' || ch == '\u2028');
}
//protected boolean isChar(char ch) { return (ch < '\uD800' || ch > '\uDFFF')
// ch != '\u0000' ch < '\uFFFE'
//protected char printable(char ch) { return ch; }
protected String printable(char ch) {
if (ch == '\n') {
return "\\n";
} else if (ch == '\r') {
return "\\r";
} else if (ch == '\t') {
return "\\t";
} else if (ch == '\'') {
return "\\'";
}
if (ch > 127 || ch < 32) {
return "\\u" + Integer.toHexString((int) ch);
}
return "" + ch;
}
protected String printable(String s) {
if (s == null) return null;
final int sLen = s.length();
StringBuilder buf = new StringBuilder(sLen + 10);
for (int i = 0; i < sLen; ++i) {
buf.append(printable(s.charAt(i)));
}
s = buf.toString();
return s;
}
}
/*
* Indiana University Extreme! Lab Software License, Version 1.2
*
* Copyright (C) 2003 The Trustees of Indiana University.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1) All redistributions of source code must retain the above
* copyright notice, the list of authors in the original source
* code, this list of conditions and the disclaimer listed in this
* license;
*
* 2) All redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the disclaimer
* listed in this license in the documentation and/or other
* materials provided with the distribution;
*
* 3) Any documentation included with all redistributions must include
* the following acknowledgement:
*
* "This product includes software developed by the Indiana
* University Extreme! Lab. For further information please visit
* http://www.extreme.indiana.edu/"
*
* Alternatively, this acknowledgment may appear in the software
* itself, and wherever such third-party acknowledgments normally
* appear.
*
* 4) The name "Indiana University" or "Indiana University
* Extreme! Lab" shall not be used to endorse or promote
* products derived from this software without prior written
* permission from Indiana University. For written permission,
* please contact http://www.extreme.indiana.edu/.
*
* 5) Products derived from this software may not use "Indiana
* University" name nor may "Indiana University" appear in their name,
* without prior written permission of the Indiana University.
*
* Indiana University provides no reassurances that the source code
* provided does not infringe the patent or any other intellectual
* property rights of any other entity. Indiana University disclaims any
* liability to any recipient for claims brought by any other entity
* based on infringement of intellectual property rights or otherwise.
*
* LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH
* NO WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA
* UNIVERSITY GIVES NO WARRANTIES AND MAKES NO REPRESENTATION THAT
* SOFTWARE IS FREE OF INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR
* OTHER PROPRIETARY RIGHTS. INDIANA UNIVERSITY MAKES NO WARRANTIES THAT
* SOFTWARE IS FREE FROM "BUGS", "VIRUSES", "TROJAN HORSES", "TRAP
* DOORS", "WORMS", OR OTHER HARMFUL CODE. LICENSEE ASSUMES THE ENTIRE
* RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR ASSOCIATED MATERIALS,
* AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION GENERATED USING
* SOFTWARE.
*/
| 112,842
| 36.340503
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/xml/XmlPullParser.java
|
package org.infinispan.commons.configuration.io.xml;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
/**
* XML Pull Parser is an interface that defines parsing functionlity provided in <a
* href="http://www.xmlpull.org/">XMLPULL V1 API</a> (visit this website to learn more about API and its
* implementations).
*
* <p>There are following different
* kinds of parser depending on which features are set:<ul>
* <li><b>non-validating</b> parser as defined in XML 1.0 spec when
* FEATURE_PROCESS_DOCDECL is set to true
* <li><b>validating parser</b> as defined in XML 1.0 spec when
* FEATURE_VALIDATION is true (and that implies that FEATURE_PROCESS_DOCDECL is true)
* <li>when FEATURE_PROCESS_DOCDECL is false (this is default and
* if different value is required necessary must be changed before parsing is started) then parser behaves like XML 1.0
* compliant non-validating parser under condition that
* <em>no DOCDECL is present</em> in XML documents
* (internal entites can still be defined with defineEntityReplacementText()). This mode of operation is intened <b>for
* operation in constrained environments</b> such as J2ME.
* </ul>
*
*
* <p>There are two key methods: next() and nextToken(). While next() provides
* access to high level parsing events, nextToken() allows access to lower level tokens.
*
* <p>The current event state of the parser
* can be determined by calling the
* <a href="#getEventType()">getEventType()</a> method.
* Initially, the parser is in the <a href="#START_DOCUMENT">START_DOCUMENT</a> state.
*
* <p>The method <a href="#next()">next()</a> advances the parser to the
* next event. The int value returned from next determines the current parser state and is identical to the value
* returned from following calls to getEventType ().
*
* <p>Th following event types are seen by next()<dl>
* <dt><a href="#START_TAG">START_TAG</a><dd> An XML start tag was read.
* <dt><a href="#TEXT">TEXT</a><dd> Text content was read;
* the text content can be retreived using the getText() method. (when in validating mode next() will not report
* ignorable whitespaces, use nextToken() instead)
* <dt><a href="#END_TAG">END_TAG</a><dd> An end tag was read
* <dt><a href="#END_DOCUMENT">END_DOCUMENT</a><dd> No more events are available
* </dl>
*
* <p>after first next() or nextToken() (or any other next*() method)
* is called user application can obtain XML version, standalone and encoding from XML declaration in following
* ways:<ul>
* <li><b>version</b>:
* getProperty("<a href="http://xmlpull.org/v1/doc/properties.html#xmldecl-version">http://xmlpull.org/v1/doc/properties.html#xmldecl-version</a>")
* returns String ("1.0") or null if XMLDecl was not read or if property is not supported
* <li><b>standalone</b>:
* getProperty("<a href="http://xmlpull.org/v1/doc/features.html#xmldecl-standalone">http://xmlpull.org/v1/doc/features.html#xmldecl-standalone</a>")
* returns Boolean: null if there was no standalone declaration or if property is not supported otherwise returns
* Boolean(true) if standalon="yes" and Boolean(false) when standalone="no"
* <li><b>encoding</b>: obtained from getInputEncoding()
* null if stream had unknown encoding (not set in setInputStream) and it was not declared in XMLDecl
* </ul>
* <p>
* A minimal example for using this API may look as follows:
* <pre>
* import java.io.IOException;
* import java.io.StringReader;
*
* import org.xmlpull.v1.XmlPullParser;
* import org.xmlpull.v1.<a href="XmlPullParserException.html">XmlPullParserException.html</a>;
* import org.xmlpull.v1.<a href="XmlPullParserFactory.html">XmlPullParserFactory</a>;
*
* public class SimpleXmlPullApp
* {
*
* public static void main (String args[])
* throws XmlPullParserException, IOException
* {
* XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
* factory.setNamespaceAware(true);
* XmlPullParser xpp = factory.newPullParser();
*
* xpp.<a href="#setInput">setInput</a>( new StringReader ( "<foo>Hello World!</foo>" ) );
* int eventType = xpp.getEventType();
* while (eventType != XmlPullParser.END_DOCUMENT) {
* if(eventType == XmlPullParser.START_DOCUMENT) {
* System.out.println("Start document");
* } else if(eventType == XmlPullParser.END_DOCUMENT) {
* System.out.println("End document");
* } else if(eventType == XmlPullParser.START_TAG) {
* System.out.println("Start tag "+xpp.<a href="#getName()">getName()</a>);
* } else if(eventType == XmlPullParser.END_TAG) {
* System.out.println("End tag "+xpp.getName());
* } else if(eventType == XmlPullParser.TEXT) {
* System.out.println("Text "+xpp.<a href="#getText()">getText()</a>);
* }
* eventType = xpp.next();
* }
* }
* }
* </pre>
*
* <p>The above example will generate the following output:
* <pre>
* Start document
* Start tag foo
* Text Hello World!
* End tag foo
* </pre>
*
* <p>For more details on API usage, please refer to the
* quick Introduction available at <a href="http://www.xmlpull.org">http://www.xmlpull.org</a>
*
* @author <a href="http://www-ai.cs.uni-dortmund.de/PERSONAL/haustein.html">Stefan Haustein</a>
* @author <a href="http://www.extreme.indiana.edu/~aslom/">Aleksander Slominski</a>
* @see #defineEntityReplacementText
* @see #getName
* @see #getNamespace
* @see #getText
* @see #next
* @see #nextToken
* @see #setInput
* @see #FEATURE_PROCESS_DOCDECL
* @see #FEATURE_VALIDATION
* @see #START_DOCUMENT
* @see #START_TAG
* @see #TEXT
* @see #END_TAG
* @see #END_DOCUMENT
*/
public interface XmlPullParser {
/**
* This constant represents the default namespace (empty string "")
*/
String NO_NAMESPACE = "";
// ----------------------------------------------------------------------------
// EVENT TYPES as reported by next()
/**
* Signalize that parser is at the very beginning of the document and nothing was read yet. This event type can only
* be observed by calling getEvent() before the first call to next(), nextToken, or nextTag()</a>).
*
* @see #next
* @see #nextToken
*/
int START_DOCUMENT = 0;
/**
* Logical end of the xml document. Returned from getEventType, next() and nextToken() when the end of the input
* document has been reached.
* <p><strong>NOTE:</strong> calling again
* <a href="#next()">next()</a> or <a href="#nextToken()">nextToken()</a>
* will result in exception being thrown.
*
* @see #next
* @see #nextToken
*/
int END_DOCUMENT = 1;
/**
* Returned from getEventType(),
* <a href="#next()">next()</a>, <a href="#nextToken()">nextToken()</a> when
* a start tag was read. The name of start tag is available from getName(), its namespace and prefix are available
* from getNamespace() and getPrefix() if <a href='#FEATURE_PROCESS_NAMESPACES'>namespaces are enabled</a>. See
* getAttribute* methods to retrieve element attributes. See getNamespace* methods to retrieve newly declared
* namespaces.
*
* @see #next
* @see #nextToken
* @see #getName
* @see #getPrefix
* @see #getNamespace
* @see #getAttributeCount
* @see #getDepth
* @see #getNamespaceCount
* @see #getNamespace
* @see #FEATURE_PROCESS_NAMESPACES
*/
int START_TAG = 2;
/**
* Returned from getEventType(), <a href="#next()">next()</a>, or
* <a href="#nextToken()">nextToken()</a> when an end tag was read.
* The name of start tag is available from getName(), its namespace and prefix are available from getNamespace() and
* getPrefix().
*
* @see #next
* @see #nextToken
* @see #getName
* @see #getPrefix
* @see #getNamespace
* @see #FEATURE_PROCESS_NAMESPACES
*/
int END_TAG = 3;
/**
* Character data was read and will is available by calling getText().
* <p><strong>Please note:</strong> <a href="#next()">next()</a> will
* accumulate multiple events into one TEXT event, skipping IGNORABLE_WHITESPACE, PROCESSING_INSTRUCTION and COMMENT
* events, In contrast, <a href="#nextToken()">nextToken()</a> will stop reading text when any other event is
* observed. Also, when the state was reached by calling next(), the text value will be normalized, whereas getText()
* will return unnormalized content in the case of nextToken(). This allows an exact roundtrip without chnanging line
* ends when examining low level events, whereas for high level applications the text is normalized apropriately.
*
* @see #next
* @see #nextToken
* @see #getText
*/
int TEXT = 4;
// ----------------------------------------------------------------------------
// additional events exposed by lower level nextToken()
/**
* A CDATA sections was just read; this token is available only from calls to <a href="#nextToken()">nextToken()</a>.
* A call to next() will accumulate various text events into a single event of type TEXT. The text contained in the
* CDATA section is available by callling getText().
*
* @see #nextToken
* @see #getText
*/
int CDSECT = 5;
/**
* An entity reference was just read; this token is available from <a href="#nextToken()">nextToken()</a> only. The
* entity name is available by calling getName(). If available, the replacement text can be obtained by calling
* getTextt(); otherwise, the user is responsibile for resolving the entity reference. This event type is never
* returned from next(); next() will accumulate the replacement text and other text events to a single TEXT event.
*
* @see #nextToken
* @see #getText
*/
int ENTITY_REF = 6;
/**
* Ignorable whitespace was just read. This token is available only from <a href="#nextToken()">nextToken()</a>). For
* non-validating parsers, this event is only reported by nextToken() when outside the root element. Validating
* parsers may be able to detect ignorable whitespace at other locations. The ignorable whitespace string is
* available by calling getText()
*
* <p><strong>NOTE:</strong> this is different from calling the
* isWhitespace() method, since text content may be whitespace but not ignorable.
* <p>
* Ignorable whitespace is skipped by next() automatically; this event type is never returned from next().
*
* @see #nextToken
* @see #getText
*/
int IGNORABLE_WHITESPACE = 7;
/**
* An XML processing instruction declaration was just read. This event type is available only via <a
* href="#nextToken()">nextToken()</a>. getText() will return text that is inside the processing instruction. Calls
* to next() will skip processing instructions automatically.
*
* @see #nextToken
* @see #getText
*/
int PROCESSING_INSTRUCTION = 8;
/**
* An XML comment was just read. This event type is this token is available via <a
* href="#nextToken()">nextToken()</a> only; calls to next() will skip comments automatically. The content of the
* comment can be accessed using the getText() method.
*
* @see #nextToken
* @see #getText
*/
int COMMENT = 9;
/**
* An XML document type declaration was just read. This token is available from <a
* href="#nextToken()">nextToken()</a> only. The unparsed text inside the doctype is available via the getText()
* method.
*
* @see #nextToken
* @see #getText
*/
int DOCDECL = 10;
/**
* This array can be used to convert the event type integer constants such as START_TAG or TEXT to to a string. For
* example, the value of TYPES[START_TAG] is the string "START_TAG".
* <p>
* This array is intended for diagnostic output only. Relying on the contents of the array may be dangerous since
* malicous applications may alter the array, although it is final, due to limitations of the Java language.
*/
String[] TYPES = {
"START_DOCUMENT",
"END_DOCUMENT",
"START_TAG",
"END_TAG",
"TEXT",
"CDSECT",
"ENTITY_REF",
"IGNORABLE_WHITESPACE",
"PROCESSING_INSTRUCTION",
"COMMENT",
"DOCDECL"
};
// ----------------------------------------------------------------------------
// namespace related features
/**
* This feature determines whether the parser processes namespaces. As for all features, the default value is false.
* <p><strong>NOTE:</strong> The value can not be changed during
* parsing an must be set before parsing.
*
* @see #getFeature
* @see #setFeature
*/
String FEATURE_PROCESS_NAMESPACES =
"http://xmlpull.org/v1/doc/features.html#process-namespaces";
/**
* This feature determines whether namespace attributes are exposed via the attribute access methods. Like all
* features, the default value is false. This feature cannot be changed during parsing.
*
* @see #getFeature
* @see #setFeature
*/
String FEATURE_REPORT_NAMESPACE_ATTRIBUTES =
"http://xmlpull.org/v1/doc/features.html#report-namespace-prefixes";
/**
* This feature determines whether the document declaration is processed. If set to false, the DOCDECL event type is
* reported by nextToken() and ignored by next().
* <p>
* If this featue is activated, then the document declaration must be processed by the parser.
*
* <p><strong>Please note:</strong> If the document type declaration
* was ignored, entity references may cause exceptions later in the parsing process. The default value of this
* feature is false. It cannot be changed during parsing.
*
* @see #getFeature
* @see #setFeature
*/
String FEATURE_PROCESS_DOCDECL =
"http://xmlpull.org/v1/doc/features.html#process-docdecl";
/**
* If this feature is activated, all validation errors as defined in the XML 1.0 sepcification are reported. This
* implies that FEATURE_PROCESS_DOCDECL is true and both, the internal and external document type declaration will be
* processed.
* <p><strong>Please Note:</strong> This feature can not be changed
* during parsing. The default value is false.
*
* @see #getFeature
* @see #setFeature
*/
String FEATURE_VALIDATION =
"http://xmlpull.org/v1/doc/features.html#validation";
/**
* Use this call to change the general behaviour of the parser, such as namespace processing or doctype declaration
* handling. This method must be called before the first call to next or nextToken. Otherwise, an exception is
* thrown.
* <p>Example: call setFeature(FEATURE_PROCESS_NAMESPACES, true) in order
* to switch on namespace processing. The initial settings correspond to the properties requested from the XML Pull
* Parser factory. If none were requested, all feautures are deactivated by default.
*
* @throws XmlPullParserException If the feature is not supported or can not be set
* @throws IllegalArgumentException If string with the feature name is null
*/
void setFeature(String name,
boolean state) throws XmlPullParserException;
/**
* Returns the current value of the given feature.
* <p><strong>Please note:</strong> unknown features are
* <strong>always</strong> returned as false.
*
* @param name The name of feature to be retrieved.
* @return The value of the feature.
* @throws IllegalArgumentException if string the feature name is null
*/
boolean getFeature(String name);
/**
* Set the value of a property.
* <p>
* The property name is any fully-qualified URI.
*
* @throws XmlPullParserException If the property is not supported or can not be set
* @throws IllegalArgumentException If string with the property name is null
*/
void setProperty(String name,
Object value) throws XmlPullParserException;
/**
* Look up the value of a property.
* <p>
* The property name is any fully-qualified URI.
* <p><strong>NOTE:</strong> unknown properties are <strong>always</strong>
* returned as null.
*
* @param name The name of property to be retrieved.
* @return The value of named property.
*/
Object getProperty(String name);
/**
* Set the input source for parser to the given reader and resets the parser. The event type is set to the initial
* value START_DOCUMENT. Setting the reader to null will just stop parsing and reset parser state, allowing the
* parser to free internal resources such as parsing buffers.
*/
void setInput(Reader in);
/**
* Sets the input stream the parser is going to process. This call resets the parser state and sets the event type to
* the initial value START_DOCUMENT.
*
* <p><strong>NOTE:</strong> If an input encoding string is passed,
* it MUST be used. Otherwise, if inputEncoding is null, the parser SHOULD try to determine input encoding following
* XML 1.0 specification (see below). If encoding detection is supported then following feature
* <a href="http://xmlpull.org/v1/doc/features.html#detect-encoding">http://xmlpull.org/v1/doc/features.html#detect-encoding</a>
* MUST be true amd otherwise it must be false
*
* @param inputStream contains a raw byte input stream of possibly unknown encoding (when inputEncoding is null).
* @param inputEncoding if not null it MUST be used as encoding for inputStream
*/
void setInput(InputStream inputStream, String inputEncoding);
/**
* Returns the input encoding if known, null otherwise. If setInput(InputStream, inputEncoding) was called with an
* inputEncoding value other than null, this value must be returned from this method. Otherwise, if inputEncoding is
* null and the parser suppports the encoding detection feature (http://xmlpull.org/v1/doc/features.html#detect-encoding),
* it must return the detected encoding. If setInput(Reader) was called, null is returned. After first call to next
* if XML declaration was present this method will return encoding declared.
*/
String getInputEncoding();
/**
* Set new value for entity replacement text as defined in
* <a href="http://www.w3.org/TR/REC-xml#intern-replacement">XML 1.0 Section 4.5
* Construction of Internal Entity Replacement Text</a>. If FEATURE_PROCESS_DOCDECL or FEATURE_VALIDATION are set,
* calling this function will result in an exception -- when processing of DOCDECL is enabled, there is no need to
* the entity replacement text manually.
*
* <p>The motivation for this function is to allow very small
* implementations of XMLPULL that will work in J2ME environments. Though these implementations may not be able to
* process the document type declaration, they still can work with known DTDs by using this function.
*
* <p><b>Please notes:</b> The given value is used literally as replacement text
* and it corresponds to declaring entity in DTD that has all special characters escaped: left angle bracket is
* replaced with &lt;, ampersnad with &amp; and so on.
*
* <p><b>Note:</b> The given value is the literal replacement text and must not
* contain any other entity reference (if it contains any entity reference there will be no further replacement).
*
* <p><b>Note:</b> The list of pre-defined entity names will
* always contain standard XML entities such as amp (&amp;), lt (&lt;), gt (&gt;), quot (&quot;), and
* apos (&apos;). Those cannot be redefined by this method!
*
* @see #setInput
* @see #FEATURE_PROCESS_DOCDECL
* @see #FEATURE_VALIDATION
*/
void defineEntityReplacementText(String entityName,
String replacementText) throws XmlPullParserException;
/**
* Returns the numbers of elements in the namespace stack for the given depth. If namespaces are not enabled, 0 is
* returned.
*
* <p><b>NOTE:</b> when parser is on END_TAG then it is allowed to call
* this function with getDepth()+1 argument to retrieve position of namespace prefixes and URIs that were declared on
* corresponding START_TAG.
* <p><b>NOTE:</b> to retrieve lsit of namespaces declared in current element:<pre>
* XmlPullParser pp = ...
* int nsStart = pp.getNamespaceCount(pp.getDepth()-1);
* int nsEnd = pp.getNamespaceCount(pp.getDepth());
* for (int i = nsStart; i < nsEnd; i++) {
* String prefix = pp.getNamespacePrefix(i);
* String ns = pp.getNamespaceUri(i);
* // ...
* }
* </pre>
*
* @see #getNamespacePrefix
* @see #getNamespaceUri
* @see #getNamespace()
* @see #getNamespace(String)
*/
int getNamespaceCount(int depth) throws XmlPullParserException;
/**
* Returns the namespace prefixe for the given position in the namespace stack. Default namespace declaration
* (xmlns='...') will have null as prefix. If the given index is out of range, an exception is thrown.
* <p><b>Please note:</b> when the parser is on an END_TAG,
* namespace prefixes that were declared in the corresponding START_TAG are still accessible although they are no
* longer in scope.
*/
String getNamespacePrefix(int pos) throws XmlPullParserException;
/**
* Returns the namespace URI for the given position in the namespace stack If the position is out of range, an
* exception is thrown.
* <p><b>NOTE:</b> when parser is on END_TAG then namespace prefixes that were declared
* in corresponding START_TAG are still accessible even though they are not in scope
*/
String getNamespaceUri(int pos) throws XmlPullParserException;
/**
* Returns the URI corresponding to the given prefix, depending on current state of the parser.
*
* <p>If the prefix was not declared in the current scope,
* null is returned. The default namespace is included in the namespace table and is available via getNamespace
* (null).
*
* <p>This method is a convenience method for
*
* <pre>
* for (int i = getNamespaceCount(getDepth ())-1; i >= 0; i--) {
* if (getNamespacePrefix(i).equals( prefix )) {
* return getNamespaceUri(i);
* }
* }
* return null;
* </pre>
*
* <p><strong>Please note:</strong> parser implementations
* may provide more efifcient lookup, e.g. using a Hashtable. The 'xml' prefix is bound to
* "http://www.w3.org/XML/1998/namespace", as defined in the
* <a href="http://www.w3.org/TR/REC-xml-names/#ns-using">Namespaces in XML</a>
* specification. Analogous, the 'xmlns' prefix is resolved to
* <a href="http://www.w3.org/2000/xmlns/">http://www.w3.org/2000/xmlns/</a>
*
* @see #getNamespaceCount
* @see #getNamespacePrefix
* @see #getNamespaceUri
*/
String getNamespace(String prefix);
// --------------------------------------------------------------------------
// miscellaneous reporting methods
/**
* Returns the current depth of the element. Outside the root element, the depth is 0. The depth is incremented by 1
* when a start tag is reached. The depth is decremented AFTER the end tag event was observed.
*
* <pre>
* <!-- outside --> 0
* <root> 1
* sometext 1
* <foobar> 2
* </foobar> 2
* </root> 1
* <!-- outside --> 0
* </pre>
*/
int getDepth();
/**
* Returns a short text describing the current parser state, including the position, a description of the current
* event and the data source if known. This method is especially useful to provide meaningful error messages and for
* debugging purposes.
*/
String getPositionDescription();
/**
* Returns the current line number, starting from 1. When the parser does not know the current line number or can not
* determine it, -1 is returned (e.g. for WBXML).
*
* @return current line number or -1 if unknown.
*/
int getLineNumber();
/**
* Returns the current column number, starting from 0. When the parser does not know the current column number or can
* not determine it, -1 is returned (e.g. for WBXML).
*
* @return current column number or -1 if unknown.
*/
int getColumnNumber();
// --------------------------------------------------------------------------
// TEXT related methods
/**
* Checks whether the current TEXT event contains only whitespace characters. For IGNORABLE_WHITESPACE, this is
* always true. For TEXT and CDSECT, false is returned when the current event text contains at least one non-white
* space character. For any other event type an exception is thrown.
*
* <p><b>Please note:</b> non-validating parsers are not
* able to distinguish whitespace and ignorable whitespace, except from whitespace outside the root element.
* Ignorable whitespace is reported as separate event, which is exposed via nextToken only.
*/
boolean isWhitespace() throws XmlPullParserException;
/**
* Returns the text content of the current event as String. The value returned depends on current event type, for
* example for TEXT event it is element content (this is typical case when next() is used).
* <p>
* See description of nextToken() for detailed description of possible returned values for different types of
* events.
*
* <p><strong>NOTE:</strong> in case of ENTITY_REF, this method returns
* the entity replacement text (or null if not available). This is the only case where getText() and
* getTextCharacters() return different values.
*
* @see #getEventType
* @see #next
* @see #nextToken
*/
String getText();
/**
* Returns the buffer that contains the text of the current event, as well as the start offset and length relevant
* for the current event. See getText(), next() and nextToken() for description of possible returned values.
*
* <p><strong>Please note:</strong> this buffer must not
* be modified and its content MAY change after a call to next() or nextToken(). This method will always return the
* same value as getText(), except for ENTITY_REF. In the case of ENTITY ref, getText() returns the replacement text
* and this method returns the actual input buffer containing the entity name. If getText() returns null, this method
* returns null as well and the values returned in the holder array MUST be -1 (both start and length).
*
* @param holderForStartAndLength Must hold an 2-element int array into which the start offset and length values will
* be written.
* @return char buffer that contains the text of the current event (null if the current event has no text
* associated).
* @see #getText
* @see #next
* @see #nextToken
*/
char[] getTextCharacters(int[] holderForStartAndLength);
// --------------------------------------------------------------------------
// START_TAG / END_TAG shared methods
/**
* Returns the namespace URI of the current element. The default namespace is represented as empty string. If
* namespaces are not enabled, an empty String ("") is always returned. The current event must be START_TAG or
* END_TAG; otherwise, null is returned.
*/
String getNamespace();
/**
* For START_TAG or END_TAG events, the (local) name of the current element is returned when namespaces are enabled.
* When namespace processing is disabled, the raw name is returned. For ENTITY_REF events, the entity name is
* returned. If the current event is not START_TAG, END_TAG, or ENTITY_REF, null is returned.
* <p><b>Please note:</b> To reconstruct the raw element name
* when namespaces are enabled and the prefix is not null, you will need to add the prefix and a colon to
* localName..
*/
String getName();
/**
* Returns the prefix of the current element. If the element is in the default namespace (has no prefix), null is
* returned. If namespaces are not enabled, or the current event is not START_TAG or END_TAG, null is returned.
*/
String getPrefix();
/**
* Returns true if the current event is START_TAG and the tag is degenerated (e.g. <foobar/>).
* <p><b>NOTE:</b> if the parser is not on START_TAG, an exception
* will be thrown.
*/
boolean isEmptyElementTag() throws XmlPullParserException;
// --------------------------------------------------------------------------
// START_TAG Attributes retrieval methods
/**
* Returns the number of attributes of the current start tag, or -1 if the current event type is not START_TAG
*
* @see #getAttributeNamespace
* @see #getAttributeName
* @see #getAttributePrefix
* @see #getAttributeValue
*/
int getAttributeCount();
/**
* Returns the namespace URI of the attribute with the given index (starts from 0). Returns an empty string ("") if
* namespaces are not enabled or the attribute has no namespace. Throws an IndexOutOfBoundsException if the index is
* out of range or the current event type is not START_TAG.
*
* <p><strong>NOTE:</strong> if FEATURE_REPORT_NAMESPACE_ATTRIBUTES is set
* then namespace attributes (xmlns:ns='...') must be reported with namespace
* <a href="http://www.w3.org/2000/xmlns/">http://www.w3.org/2000/xmlns/</a>
* (visit this URL for description!). The default namespace attribute (xmlns="...") will be reported with empty
* namespace.
* <p><strong>NOTE:</strong>The xml prefix is bound as defined in
* <a href="http://www.w3.org/TR/REC-xml-names/#ns-using">Namespaces in XML</a>
* specification to "http://www.w3.org/XML/1998/namespace".
*
* @param index zero-based index of attribute
* @return attribute namespace, empty string ("") is returned if namesapces processing is not enabled or namespaces
* processing is enabled but attribute has no namespace (it has no prefix).
*/
String getAttributeNamespace(int index);
/**
* Returns the local name of the specified attribute if namespaces are enabled or just attribute name if namespaces
* are disabled. Throws an IndexOutOfBoundsException if the index is out of range or current event type is not
* START_TAG.
*
* @param index zero-based index of attribute
* @return attribute name (null is never returned)
*/
String getAttributeName(int index);
/**
* Returns the prefix of the specified attribute Returns null if the element has no prefix. If namespaces are
* disabled it will always return null. Throws an IndexOutOfBoundsException if the index is out of range or current
* event type is not START_TAG.
*
* @param index zero-based index of attribute
* @return attribute prefix or null if namespaces processing is not enabled.
*/
String getAttributePrefix(int index);
/**
* Returns the type of the specified attribute If parser is non-validating it MUST return CDATA.
*
* @param index zero-based index of attribute
* @return attribute type (null is never returned)
*/
String getAttributeType(int index);
/**
* Returns if the specified attribute was not in input was declared in XML. If parser is non-validating it MUST
* always return false. This information is part of XML infoset:
*
* @param index zero-based index of attribute
* @return false if attribute was in input
*/
boolean isAttributeDefault(int index);
/**
* Returns the given attributes value. Throws an IndexOutOfBoundsException if the index is out of range or current
* event type is not START_TAG.
*
* <p><strong>NOTE:</strong> attribute value must be normalized
* (including entity replacement text if PROCESS_DOCDECL is false) as described in
* <a href="http://www.w3.org/TR/REC-xml#AVNormalize">XML 1.0 section
* 3.3.3 Attribute-Value Normalization</a>
*
* @param index zero-based index of attribute
* @return value of attribute (null is never returned)
* @see #defineEntityReplacementText
*/
String getAttributeValue(int index);
/**
* Returns the attributes value identified by namespace URI and namespace localName. If namespaces are disabled
* namespace must be null. If current event type is not START_TAG then IndexOutOfBoundsException will be thrown.
*
* <p><strong>NOTE:</strong> attribute value must be normalized
* (including entity replacement text if PROCESS_DOCDECL is false) as described in
* <a href="http://www.w3.org/TR/REC-xml#AVNormalize">XML 1.0 section
* 3.3.3 Attribute-Value Normalization</a>
*
* @param namespace Namespace of the attribute if namespaces are enabled otherwise must be null
* @param name If namespaces enabled local name of attribute otherwise just attribute name
* @return value of attribute or null if attribute with given name does not exist
* @see #defineEntityReplacementText
*/
String getAttributeValue(String namespace,
String name);
// --------------------------------------------------------------------------
// actual parsing methods
/**
* Returns the type of the current event (START_TAG, END_TAG, TEXT, etc.)
*
* @see #next()
* @see #nextToken()
*/
int getEventType()
throws XmlPullParserException;
/**
* Get next parsing event - element content wil be coalesced and only one TEXT event must be returned for whole
* element content (comments and processing instructions will be ignored and emtity references must be expanded or
* exception mus be thrown if entity reerence can not be exapnded). If element content is empty (content is "") then
* no TEXT event will be reported.
*
* <p><b>NOTE:</b> empty element (such as <tag/>) will be reported
* with two separate events: START_TAG, END_TAG - it must be so to preserve parsing equivalency of empty element to
* <tag></tag>. (see isEmptyElementTag ())
*
* @see #isEmptyElementTag
* @see #START_TAG
* @see #TEXT
* @see #END_TAG
* @see #END_DOCUMENT
*/
int next()
throws XmlPullParserException, IOException;
/**
* This method works similarly to next() but will expose additional event types (COMMENT, CDSECT, DOCDECL,
* ENTITY_REF, PROCESSING_INSTRUCTION, or IGNORABLE_WHITESPACE) if they are available in input.
*
* <p>If special feature
* <a href="http://xmlpull.org/v1/doc/features.html#xml-roundtrip">FEATURE_XML_ROUNDTRIP</a>
* (identified by URI: http://xmlpull.org/v1/doc/features.html#xml-roundtrip) is enabled it is possible to do XML
* document round trip ie. reproduce exectly on output the XML input using getText(): returned content is always
* unnormalized (exactly as in input). Otherwise returned content is end-of-line normalized as described
* <a href="http://www.w3.org/TR/REC-xml#sec-line-ends">XML 1.0 End-of-Line Handling</a>
* and. Also when this feature is enabled exact content of START_TAG, END_TAG, DOCDECL and PROCESSING_INSTRUCTION is
* available.
*
* <p>Here is the list of tokens that can be returned from nextToken()
* and what getText() and getTextCharacters() returns:<dl>
* <dt>START_DOCUMENT<dd>null
* <dt>END_DOCUMENT<dd>null
* <dt>START_TAG<dd>null unless FEATURE_XML_ROUNDTRIP
* enabled and then returns XML tag, ex: <tag attr='val'>
* <dt>END_TAG<dd>null unless FEATURE_XML_ROUNDTRIP
* id enabled and then returns XML tag, ex: </tag>
* <dt>TEXT<dd>return element content.
* <br>Note: that element content may be delivered in multiple consecutive TEXT events.
* <dt>IGNORABLE_WHITESPACE<dd>return characters that are determined to be ignorable white
* space. If the FEATURE_XML_ROUNDTRIP is enabled all whitespace content outside root element will always reported as
* IGNORABLE_WHITESPACE otherise rteporting is optional.
* <br>Note: that element content may be delevered in multiple consecutive IGNORABLE_WHITESPACE events.
* <dt>CDSECT<dd>
* return text <em>inside</em> CDATA (ex. 'fo<o' from <!CDATA[fo<o]]>)
* <dt>PROCESSING_INSTRUCTION<dd>
* if FEATURE_XML_ROUNDTRIP is true return exact PI content ex: 'pi foo' from <?pi foo?> otherwise it may be exact
* PI content or concatenation of PI target, space and data so for example for <?target data?> string
* "target data" may be returned if FEATURE_XML_ROUNDTRIP is false.
* <dt>COMMENT<dd>return comment content ex. 'foo bar' from <!--foo bar-->
* <dt>ENTITY_REF<dd>getText() MUST return entity replacement text if PROCESS_DOCDECL is false
* otherwise getText() MAY return null, additionally getTextCharacters() MUST return entity name (for example
* 'entity_name' for &entity_name;).
* <br><b>NOTE:</b> this is the only place where value returned from getText() and
* getTextCharacters() <b>are different</b>
* <br><b>NOTE:</b> it is user responsibility to resolve entity reference
* if PROCESS_DOCDECL is false and there is no entity replacement text set in defineEntityReplacementText() method
* (getText() will be null)
* <br><b>NOTE:</b> character entities (ex. &#32;) and standard entities such as
* &amp; &lt; &gt; &quot; &apos; are reported as well and are <b>not</b> reported as TEXT tokens
* but as ENTITY_REF tokens! This requirement is added to allow to do roundtrip of XML documents!
* <dt>DOCDECL<dd>
* if FEATURE_XML_ROUNDTRIP is true or PROCESS_DOCDECL is false
* then return what is inside of DOCDECL for example it returns:<pre>
* " titlepage SYSTEM "http://www.foo.bar/dtds/typo.dtd"
* [<!ENTITY % active.links "INCLUDE">]"</pre>
* <p>for input document that contained:<pre>
* <!DOCTYPE titlepage SYSTEM "http://www.foo.bar/dtds/typo.dtd"
* [<!ENTITY % active.links "INCLUDE">]></pre>
* otherwise if FEATURE_XML_ROUNDTRIP is false and PROCESS_DOCDECL is true then what is returned is undefined (it may
* be even null)
* </dd>
* </dl>
*
* <p><strong>NOTE:</strong> there is no gurantee that there will only one TEXT or
* IGNORABLE_WHITESPACE event from nextToken() as parser may chose to deliver element content in multiple tokens
* (dividing element content into chunks)
*
* <p><strong>NOTE:</strong> whether returned text of token is end-of-line normalized
* is depending on FEATURE_XML_ROUNDTRIP.
*
* <p><strong>NOTE:</strong> XMLDecl (<?xml ...?>) is not reported but its content
* is available through optional properties (see class description above).
*
* @see #next
* @see #START_TAG
* @see #TEXT
* @see #END_TAG
* @see #END_DOCUMENT
* @see #COMMENT
* @see #DOCDECL
* @see #PROCESSING_INSTRUCTION
* @see #ENTITY_REF
* @see #IGNORABLE_WHITESPACE
*/
int nextToken()
throws XmlPullParserException, IOException;
//-----------------------------------------------------------------------------
// utility methods to mak XML parsing easier ...
/**
* Test if the current event is of the given type and if the namespace and name do match. null will match any
* namespace and any name. If the test is not passed, an exception is thrown. The exception text indicates the parser
* position, the expected event and the current event that is not meeting the requirement.
*
* <p>Essentially it does this
* <pre>
* if (type != getEventType()
* || (namespace != null && !namespace.equals( getNamespace () ) )
* || (name != null && !name.equals( getName() ) ) )
* throw new XmlPullParserException( "expected "+ TYPES[ type ]+getPositionDescription());
* </pre>
*/
void require(int type, String namespace, String name)
throws XmlPullParserException, IOException;
/**
* If current event is START_TAG then if next element is TEXT then element content is returned or if next event is
* END_TAG then empty string is returned, otherwise exception is thrown. After calling this function successfully
* parser will be positioned on END_TAG.
*
* <p>The motivation for this function is to allow to parse consistently both
* empty elements and elements that has non empty content, for example for input: <ol>
* <li><tag>foo</tag>
* <li><tag></tag> (which is equivalent to <tag/>
* both input can be parsed with the same code:
* <pre>
* p.nextTag()
* p.requireEvent(p.START_TAG, "", "tag");
* String content = p.nextText();
* p.requireEvent(p.END_TAG, "", "tag");
* </pre>
* This function together with nextTag make it very easy to parse XML that has no mixed content.
*
*
* <p>Essentially it does this
* <pre>
* if(getEventType() != START_TAG) {
* throw new XmlPullParserException(
* "parser must be on START_TAG to read next text", this, null);
* }
* int eventType = next();
* if(eventType == TEXT) {
* String result = getText();
* eventType = next();
* if(eventType != END_TAG) {
* throw new XmlPullParserException(
* "event TEXT it must be immediately followed by END_TAG", this, null);
* }
* return result;
* } else if(eventType == END_TAG) {
* return "";
* } else {
* throw new XmlPullParserException(
* "parser must be on START_TAG or TEXT to read text", this, null);
* }
* </pre>
*/
String nextText() throws XmlPullParserException, IOException;
/**
* Call next() and return event if it is START_TAG or END_TAG otherwise throw an exception. It will skip whitespace
* TEXT before actual tag if any.
*
* <p>essentially it does this
* <pre>
* int eventType = next();
* if(eventType == TEXT && isWhitespace()) { // skip whitespace
* eventType = next();
* }
* if (eventType != START_TAG && eventType != END_TAG) {
* throw new XmlPullParserException("expected start or end tag", this, null);
* }
* return eventType;
* </pre>
*/
int nextTag() throws XmlPullParserException, IOException;
}
| 42,997
| 43.327835
| 159
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/xml/XmlConfigurationReader.java
|
package org.infinispan.commons.configuration.io.xml;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.infinispan.commons.configuration.io.AbstractConfigurationReader;
import org.infinispan.commons.configuration.io.ConfigurationFormatFeature;
import org.infinispan.commons.configuration.io.ConfigurationReaderException;
import org.infinispan.commons.configuration.io.ConfigurationResourceResolver;
import org.infinispan.commons.configuration.io.Location;
import org.infinispan.commons.configuration.io.NamingStrategy;
import org.infinispan.commons.configuration.io.PropertyReplacer;
import org.infinispan.commons.configuration.io.URLConfigurationResourceResolver;
import org.infinispan.commons.util.SimpleImmutableEntry;
import org.infinispan.commons.util.Util;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public class XmlConfigurationReader extends AbstractConfigurationReader {
public static final String XINCLUDE = "include";
public static final String XINCLUDE_NS = "http://www.w3.org/2001/XInclude";
private final Deque<State> stack;
private State state;
int token;
public XmlConfigurationReader(Reader reader, ConfigurationResourceResolver resolver, Properties properties, PropertyReplacer replacer, NamingStrategy namingStrategy) {
this(reader, resolver, properties, replacer, namingStrategy, new ArrayDeque<>());
}
private XmlConfigurationReader(Reader reader, ConfigurationResourceResolver resolver, Properties properties, PropertyReplacer replacer, NamingStrategy namingStrategy, Deque<State> stack) {
super(resolver, properties, replacer, namingStrategy);
this.state = new State(reader, getParser(reader), resolver);
this.stack = stack;
this.stack.push(state);
token = -1;
}
private MXParser getParser(Reader reader) {
MXParser parser = new MXParser(reader);
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
return parser;
}
@Override
public ConfigurationResourceResolver getResourceResolver() {
return state.resolver;
}
@Override
public void require(ElementType elementType, String namespace, String name) {
int type;
switch (elementType) {
case START_DOCUMENT:
type = XmlPullParser.START_DOCUMENT;
break;
case END_DOCUMENT:
type = XmlPullParser.END_DOCUMENT;
break;
case START_ELEMENT:
type = XmlPullParser.START_TAG;
break;
case END_ELEMENT:
type = XmlPullParser.END_TAG;
break;
default:
throw new IllegalArgumentException(elementType.name());
}
try {
state.parser.require(type, namespace, name);
} catch (IOException e) {
throw new ConfigurationReaderException(e, getLocation());
}
}
@Override
public boolean hasNext() {
if (token < 0) {
try {
token = state.parser.next();
if (token == XmlPullParser.END_DOCUMENT) {
token = closeInclude();
}
} catch (IOException e) {
throw new ConfigurationReaderException(e, getLocation());
}
}
return token != XmlPullParser.END_DOCUMENT;
}
private int nextEvent() {
try {
int event = token < 0 ? state.parser.next() : token;
token = -1;
for (; ; ) {
if (event == XmlPullParser.START_TAG && XINCLUDE.equals(getLocalName()) && XINCLUDE_NS.equals(getNamespace())) {
event = include();
} else if (event == XmlPullParser.END_TAG && XINCLUDE.equals(getLocalName()) && XINCLUDE_NS.equals(getNamespace())) {
event = closeInclude();
} else if (event == XmlPullParser.END_DOCUMENT) {
event = closeInclude();
if (event == XmlPullParser.END_DOCUMENT) {
return event;
}
} else {
return event;
}
}
} catch (XmlPullParserException | IOException e) {
throw new ConfigurationReaderException(e, getLocation());
}
}
@Override
public ElementType nextElement() {
int event = nextEvent();
while (event == XmlPullParser.TEXT
|| event == XmlPullParser.IGNORABLE_WHITESPACE
|| event == XmlPullParser.PROCESSING_INSTRUCTION
|| event == XmlPullParser.COMMENT) {
event = nextEvent();
}
switch (event) {
case XmlPullParser.START_DOCUMENT:
return ElementType.START_DOCUMENT;
case XmlPullParser.END_DOCUMENT:
return ElementType.END_DOCUMENT;
case XmlPullParser.START_TAG:
return ElementType.START_ELEMENT;
case XmlPullParser.END_TAG:
return ElementType.END_ELEMENT;
default:
throw new ConfigurationReaderException("Expecting event type >=1 <=4, got " + event, getLocation());
}
}
@Override
public String getLocalName(NamingStrategy strategy) {
return strategy.convert(state.parser.getName());
}
@Override
public String getNamespace() {
return state.parser.getNamespace();
}
@Override
public int getAttributeCount() {
return state.parser.getAttributeCount();
}
@Override
public String getAttributeName(int index, NamingStrategy strategy) {
return strategy.convert(state.parser.getAttributeName(index));
}
@Override
public String getAttributeValue(int index) {
String value = state.parser.getAttributeValue(index);
return replaceProperties(value);
}
@Override
public String getAttributeValue(String localName, NamingStrategy strategy) {
String value = state.parser.getAttributeValue(null, strategy.convert(localName));
return replaceProperties(value);
}
@Override
public String getElementText() {
try {
return replaceProperties(state.parser.nextText().trim());
} catch (IOException e) {
throw new ConfigurationReaderException("Expected text", getLocation());
}
}
@Override
public Location getLocation() {
return new Location(getName(), state.parser.getLineNumber(), state.parser.getColumnNumber());
}
@Override
public String getAttributeNamespace(int index) {
return state.parser.getAttributeNamespace(index);
}
@Override
public Map.Entry<String, String> getMapItem(String nameAttribute) {
String type = getLocalName();
String name = getAttributeValue(nameAttribute);
return new SimpleImmutableEntry<>(name, type);
}
@Override
public void endMapItem() {
// Do nothing
}
@Override
public String[] readArray(String outer, String inner) {
List<String> list = new ArrayList<>();
while (inTag(outer)) {
if (inner.equals(getLocalName())) {
list.add(getElementText());
} else {
throw new ConfigurationReaderException(getLocalName(), getLocation());
}
}
return list.toArray(new String[0]);
}
private int include() {
try {
String href = getAttributeValue("href");
URL url = state.resolver.resolveResource(href);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
state = new State(reader, getParser(reader), new URLConfigurationResourceResolver(url));
stack.push(state);
require(ElementType.START_DOCUMENT);
int tag = state.parser.nextTag();
require(ElementType.START_ELEMENT);
return tag;
} catch (IOException e) {
throw new ConfigurationReaderException(e, getLocation());
}
}
private int closeInclude() {
try {
if (stack.size() > 1) {
State removed = stack.pop();
Util.close(removed.reader);
state = stack.peek();
state.parser.nextTag();
require(ElementType.END_ELEMENT);
return state.parser.nextTag();
} else {
return XmlPullParser.END_DOCUMENT;
}
} catch (IOException e) {
throw new ConfigurationReaderException(e, getLocation());
}
}
@Override
public boolean hasFeature(ConfigurationFormatFeature feature) {
switch (feature) {
case MIXED_ELEMENTS:
case BARE_COLLECTIONS:
return true;
default:
return false;
}
}
@Override
public void close() {
Util.close(state.reader);
}
@Override
public void setAttributeValue(String namespace, String name, String value) {}
// private members
private static final class State {
Reader reader;
XmlPullParser parser;
ConfigurationResourceResolver resolver;
State(Reader reader, MXParser parser, ConfigurationResourceResolver resolver) {
this.reader = reader;
this.parser = parser;
this.resolver = resolver;
}
}
}
| 9,316
| 31.127586
| 191
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/xml/XmlConfigurationWriter.java
|
package org.infinispan.commons.configuration.io.xml;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.Optional;
import org.infinispan.commons.configuration.io.AbstractConfigurationWriter;
import org.infinispan.commons.configuration.io.ConfigurationFormatFeature;
import org.infinispan.commons.configuration.io.ConfigurationWriterException;
import org.infinispan.commons.configuration.io.NamingStrategy;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public class XmlConfigurationWriter extends AbstractConfigurationWriter {
private String version = "1.0";
private String encoding;
private Optional<Boolean> standalone = Optional.empty();
private boolean openTag;
private boolean skipIndentClose;
public XmlConfigurationWriter(Writer writer, boolean prettyPrint, boolean clearTextSecrets) {
super(writer, 4, prettyPrint, clearTextSecrets, NamingStrategy.KEBAB_CASE);
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public Optional<Boolean> getStandalone() {
return standalone;
}
public void setStandalone(Optional<Boolean> standalone) {
this.standalone = standalone;
}
@Override
public void writeStartDocument() {
try {
writer.write("<?xml version=\"");
writer.write(version);
if (encoding != null && !encoding.isEmpty()) {
writer.write("\" encoding=\"");
writer.write(encoding);
}
if (standalone.isPresent()) {
writer.write("\" standalone=\"");
if (standalone.get().booleanValue()) {
writer.write("yes");
} else {
writer.write("no");
}
}
writer.write("\"?>");
nl();
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
private void closeCurrentTag(boolean newline) throws IOException {
if (openTag) {
writer.write(">");
if (newline) {
nl();
}
openTag = false;
}
}
@Override
public void writeStartElement(String name) {
writeStartElement0(new Tag(name, false, true, true));
}
private void writeStartElement0(Tag tag) {
try {
closeCurrentTag(true);
tagStack.push(tag);
tab();
writer.write("<");
writer.write(naming.convert(tag.getName()));
openTag = true;
indent();
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeStartElement(String prefix, String namespace, String name) {
writeStartElement((prefix == null ? "" : (prefix + ":")) + name);
}
@Override
public void writeStartArrayElement(String name) {
writeStartElement0(new Tag(name, true, true, true));
}
@Override
public void writeEndArrayElement() {
writeEndElement();
}
@Override
public void writeStartListElement(String name, boolean explicit) {
// XML allows repeated elements without a wrapper element
if (explicit) {
writeStartElement(name);
} else {
tagStack.push(new Tag(name));
}
}
@Override
public void writeStartListElement(String prefix, String namespace, String name, boolean explicit) {
// XML allows repeated elements without a wrapper element
writeStartListElement((prefix == null ? "" : (prefix + ":")) + name, explicit);
}
@Override
public void writeEndListElement() {
// XML allows repeated elements without a wrapper element
if (tagStack.peek().isExplicitOuter()) {
writeEndElement();
} else {
tagStack.pop();
}
}
@Override
public void writeNamespace(String prefix, String namespace) {
if (!openTag) {
throw new ConfigurationWriterException("Cannot set namespace without a started element");
}
if (prefix == null || prefix.isEmpty()) {
writeDefaultNamespace(namespace);
return;
}
if (namespaces.containsKey(prefix)) {
if (!namespaces.get(prefix).equals(namespace)) {
throw new ConfigurationWriterException("Duplicate declaration of prefix '" + prefix + "' with different namespace");
}
} else {
namespaces.put(prefix, namespace);
}
try {
writer.write(" xmlns:");
writer.write(prefix);
writer.write("=\"");
writer.write(namespace);
writer.write("\"");
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeDefaultNamespace(String namespace) {
if (!openTag) {
throw new ConfigurationWriterException("Cannot set namespace without a started element");
}
try {
writer.write(" xmlns=\"");
writer.write(namespace);
writer.write("\"");
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeEndElement() {
try {
outdent();
if (openTag) {
writer.write("/>");
nl();
openTag = false;
tagStack.pop();
} else {
if (skipIndentClose) {
skipIndentClose = false;
} else {
tab();
}
writer.write("</");
writer.write(tagStack.pop().getName());
writer.write(">");
nl();
}
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeEndDocument() {
try {
closeCurrentTag(true);
writer.flush();
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeAttribute(String name, String value) {
writeAttribute(name, value, true);
}
private void writeAttribute(String name, String value, boolean rename) {
try {
writer.write(' ');
writer.write(rename ? naming.convert(name) : name);
writer.write("=\"");
if (value != null) {
writer.write(value.replaceAll("&", "&"));
}
writer.write('"');
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeAttribute(String name, Iterable<String> values) {
if (values.iterator().hasNext()) {
writeAttribute(name, String.join(" ", values));
}
}
@Override
public void writeArrayElement(String outer, String inner, String attribute, Iterable<String> values) {
Iterator<String> it = values.iterator();
boolean wrapped = !inner.equals(outer);
if (it.hasNext()) {
if (wrapped) {
writeStartElement(outer);
}
while (it.hasNext()) {
writeStartElement(inner);
if (attribute == null) {
writeCharacters(it.next());
} else {
writeAttribute(attribute, it.next());
}
writeEndElement();
}
if (wrapped) {
writeEndElement();
}
}
}
@Override
public void writeCharacters(String chars) {
try {
closeCurrentTag(false);
writer.write(chars);
skipIndentClose = true;
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeEmptyElement(String name) {
try {
closeCurrentTag(true);
tab();
writer.write("<");
writer.write(naming.convert(name));
writer.write("/>");
nl();
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeStartMap(String name) {
writeStartElement(name);
}
@Override
public void writeMapItem(String element, String name, String key, String value) {
writeStartElement(element);
writeAttribute(name, key, false);
writeCharacters(value);
writeEndElement();
}
@Override
public void writeMapItem(String element, String name, String key) {
writeStartElement(element);
writeAttribute(name, key, false);
}
@Override
public void writeEndMapItem() {
writeEndElement();
}
@Override
public void writeEndMap() {
writeEndElement();
}
@Override
public void writeComment(String comment) {
try {
closeCurrentTag(true);
tab();
writer.write("<!--");
writer.write(comment);
writer.write("-->");
nl();
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public boolean hasFeature(ConfigurationFormatFeature feature) {
switch (feature) {
case MIXED_ELEMENTS:
case BARE_COLLECTIONS:
return true;
default:
return false;
}
}
}
| 9,373
| 25.480226
| 128
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/xml/XmlPullParserException.java
|
package org.infinispan.commons.configuration.io.xml;
/**
* This exception is thrown to signal XML Pull Parser related faults.
*
* @author <a href="http://www.extreme.indiana.edu/~aslom/">Aleksander Slominski</a>
*/
public class XmlPullParserException extends RuntimeException {
protected Throwable detail;
protected int row = -1;
protected int column = -1;
public XmlPullParserException(String s) {
super(s);
}
public XmlPullParserException(String msg, XmlPullParser parser, Throwable chain) {
super((msg == null ? "" : msg + " ")
+ (parser == null ? "" : "(position:" + parser.getPositionDescription() + ") ")
+ (chain == null ? "" : "caused by: " + chain));
if (parser != null) {
this.row = parser.getLineNumber();
this.column = parser.getColumnNumber();
}
this.detail = chain;
}
public Throwable getDetail() {
return detail;
}
public int getLineNumber() {
return row;
}
public int getColumnNumber() {
return column;
}
public void printStackTrace() {
if (detail == null) {
super.printStackTrace();
} else {
synchronized (System.err) {
System.err.println(super.getMessage() + "; nested exception is:");
detail.printStackTrace();
}
}
}
}
| 1,355
| 24.584906
| 91
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/yaml/YamlConfigurationReader.java
|
package org.infinispan.commons.configuration.io.yaml;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.infinispan.commons.configuration.io.AbstractConfigurationReader;
import org.infinispan.commons.configuration.io.ConfigurationFormatFeature;
import org.infinispan.commons.configuration.io.ConfigurationReaderException;
import org.infinispan.commons.configuration.io.ConfigurationResourceResolver;
import org.infinispan.commons.configuration.io.Location;
import org.infinispan.commons.configuration.io.NamingStrategy;
import org.infinispan.commons.configuration.io.PropertyReplacer;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.util.SimpleImmutableEntry;
import org.infinispan.commons.util.Util;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public class YamlConfigurationReader extends AbstractConfigurationReader {
private static final int INDENT = 2;
final private Deque<Parsed> state = new ArrayDeque<>();
final private List<String> attributeNames = new ArrayList<>();
final private List<String> attributeValues = new ArrayList<>();
final private List<String> attributeNamespaces = new ArrayList<>();
final private Map<String, String> namespaces = new HashMap<>();
private final BufferedReader reader;
private Parsed next;
private ElementType type = ElementType.START_DOCUMENT;
private int row = 0;
private int column = 0;
private Node lines;
public YamlConfigurationReader(Reader reader, ConfigurationResourceResolver resolver, Properties properties, PropertyReplacer replacer, NamingStrategy namingStrategy) {
super(resolver, properties, replacer, namingStrategy);
this.reader = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
namespaces.put("", ""); // Default namespace
loadTree();
if (Log.CONFIG.isTraceEnabled()) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
printTree(pw, lines);
Log.CONFIG.trace(sw);
}
}
private void printTree(PrintWriter pw, Node node) {
if (node != null) {
for (int i = 0; i < node.parsed.indent; i++) {
pw.print(' ');
}
pw.println(node.parsed);
if (node.children != null) {
for (Node c : node.children) {
printTree(pw, c);
}
}
}
}
private static class Node {
final Parsed parsed;
ArrayList<Node> children;
Node parent;
Node(Parsed parsed) {
this.parsed = parsed;
}
Node addChild(Node child) {
if (children == null) {
children = new ArrayList<>();
}
if (isAttribute(child.parsed)) {
// Add before the first non attribute
for (int i = 0; i < children.size(); i++) {
if (!isAttribute(children.get(i).parsed)) {
children.add(i, child);
child.parent = this;
return child;
}
}
}
children.add(child);
child.parent = this;
return child;
}
Node addSibling(Node sibling) {
parent.addChild(sibling);
return sibling;
}
Node next() {
if (hasChildren()) {
return children.remove(0);
} else {
if (parent == null) {
return null;
} else {
return parent.next();
}
}
}
public String toString() {
return parsed.toString();
}
boolean hasChildren() {
return children != null && !children.isEmpty();
}
}
private void loadTree() {
Parsed parsed;
Node current = null;
do {
try {
do {
parsed = parseLine(reader.readLine());
} while (parsed != null && parsed.name == null && parsed.value == null && !parsed.list);
} catch (IOException e) {
throw new ConfigurationReaderException(e, new Location(getName(), row, column));
}
if (parsed == null) {
// EOF
return;
}
if (lines == null) {
if (parsed.name == null) {
throw new ConfigurationReaderException("Incomplete line", new Location(getName(), row, column));
}
lines = new Node(parsed);
current = lines;
} else {
if (parsed.list) {
if (parsed.name == null) {
// It's an array
if (current.parsed.indent == parsed.indent) {
current = current.addSibling(new Node(parsed));
} else {
current = current.addChild(new Node(parsed));
}
} else {
// Find the parent of the previous element
current = findParent(current, parsed);
if (current.parsed.list) {
current = current.parent;
}
// Clone the parent
current = addListItem(parsed, current);
current = current.addChild(new Node(parsed));
}
} else if (parsed.indent == current.parsed.indent) {
// Sibling of the current node
current = current.addSibling(new Node(parsed));
} else if (parsed.indent > current.parsed.indent) {
// Child of the current node
if (parsed.name == null) {
// It's a value continuation, append it to the current
current.parsed.value = current.parsed.value + " " + parsed.value;
} else {
current = current.addChild(new Node(parsed));
}
} else {
// Lower indent than, the current owner, climb up the tree to find the parent
current = findParent(current, parsed);
current = current.addChild(new Node(parsed));
}
}
} while (true);
}
private Node addListItem(Parsed parsed, Node current) {
// It's a list item, we create a synthetic node with the same name as the parent
Parsed holder = new Parsed(parsed.row);
holder.nsPrefix = current.parsed.nsPrefix;
holder.name = current.parsed.name;
holder.indent = current.parsed.indent + 1;//parsed.indent;
holder.list = true;
current = current.addChild(new Node(holder));
// And the parsed line is added as a child of the holder
parsed.list = false;
return current;
}
private Node findParent(Node current, Parsed line) {
while (line.indent <= current.parsed.indent) {
current = current.parent;
}
return current;
}
private static boolean isAttribute(Parsed p) {
return p.name != null && p.value != null;
}
Parsed parseLine(final String s) {
if (s == null) {
return null;
} else {
Parsed parsed = new Parsed(++row);
int length = s.length();
// Trim any space at the end of the line
while (length > 0 && s.charAt(length - 1) == ' ') length--;
int state = 0; // 0=INDENT, 1=KEY, 2=COLON, 3=VALUE, 4=TRAILING
int start = -1;
for (int i = 0; i < length; i++) {
column = i + 1;
int c = s.charAt(i);
switch (c) {
case ' ':
if (state == 0) {
parsed.indent++;
} // else ignore: it may be ignorable or part of a key/value
break;
case '\t':
if (state == 0) {
parsed.indent += INDENT;
} // else ignore: it may be ignorable or part of a key/value
break;
case '#':
if (state == 3) {
parsed.value = s.substring(start, i - 1).trim();
return parsed;
} else if (state == 1) {
throw new ConfigurationReaderException("Invalid comment", new Location(getName(), row, i));
} else {
return parsed; // the rest of the line is a comment
}
case ':':
if (i + 1 == length || s.charAt(i + 1) == ' ') {
if (state == 1) {
if (start >= 0) {
parseKey(parsed, s.substring(start, i));
}
state = 2;
}
}
break;
case '~':
if (state == 2 || i + 1 == length) {
// the null element
parsed.value = null;
return parsed;
}
case '\\':
if (i + 1 == length) {
throw new ConfigurationReaderException("Incomplete escape sequence", new Location(getName(), row, i));
} else {
i++;
}
break;
case '%':
if (i == 0) {
String[] parts = s.split(" ");
if (parts.length == 3 && parts[0].equals("%TAG") && parts[1].startsWith("!") && parts[1].endsWith("!")) {
if ("!".equals(parts[1])) {
namespaces.put("", parts[2]); // The primary namespace
} else {
namespaces.put(parts[1].substring(1, parts[1].length() - 1), parts[2]);
}
return parsed;
} else if (parts.length == 2 && parts[0].equals("%YAML")) {
return parsed;
} else {
Log.CONFIG.warn("Unknown directive " + s + " at " + new Location(getName(), row, i));
}
}
break;
case '-':
if (i == 0 && "---".equals(s)) {
// It's a separator
return parsed;
} else if (state == 0) {
// It's a list delimiter
parsed.list = true;
parsed.indent++;
}
break;
case '"':
case '\'':
if (state == 0 || state == 2) {
int endQuote = s.indexOf(c, i + 1);
if (endQuote < 0) {
throw new ConfigurationReaderException("Missing closing quote", new Location(getName(), row, i));
}
String v = s.substring(i + 1, endQuote).trim();
if (state == 0) {
parseKey(parsed, v);
state = 1;
} else {
parsed.value = v;
state = 4;
}
i = endQuote; // Skip
break;
}
// Fallthrough
default:
if (state == 0) {
state = 1;
start = i;
} else if (state == 2) {
state = 3;
start = i;
}
}
}
if (state == 1) { // Bare string
if (parsed.list) {
if (start > 0) {
parsed.value = s.substring(start).trim();
} else {
// The value was stored in the name, swap them
parsed.value = parsed.name;
parsed.name = null;
}
} else {
// It's probably a continuation of the previous line
parsed.value = s.substring(start).trim();
}
} else if (state == 3) { // we reached the end of the line
String val = s.substring(start).trim();
switch (val) {
// Handle various null values: null | Null | NULL | {}
case "{}":
case "null":
case "Null":
case "NULL":
parsed.value = null;
return parsed;
default:
parsed.value = val;
}
}
return parsed;
}
}
private void parseKey(Parsed p, String s) {
int colon = s.lastIndexOf(':');
p.name = colon < 0 ? s : s.substring(colon + 1);
p.nsPrefix = colon < 0 ? "" : s.substring(0, colon);
if (!p.nsPrefix.isEmpty()) {
namespaces.putIfAbsent(p.nsPrefix, namingStrategy.convert(p.nsPrefix));
}
}
private void readNext() {
do {
if (lines != null) {
next = lines.parsed;
lines = lines.next();
} else {
next = null;
}
} while (next != null && next.name == null && next.value == null);
}
@Override
public ElementType nextElement() {
if (next == null) {
readNext();
}
resetAttributes();
if (next == null) { // If still null, we've reached the end of the document, we need to unwind the stack
if (state.isEmpty()) {
type = ElementType.END_DOCUMENT;
} else {
if (type == ElementType.END_ELEMENT) {
state.pop();
}
type = state.isEmpty() ? ElementType.END_DOCUMENT : ElementType.END_ELEMENT;
}
} else {
if (!state.isEmpty()) {
if (next.indent < state.peek().indent) {
if (type == ElementType.END_ELEMENT) {
state.pop();
}
type = ElementType.END_ELEMENT;
return type;
} else if (next.indent == state.peek().indent) {
if (type != ElementType.END_ELEMENT) {
// Emit the end element for the current item
type = ElementType.END_ELEMENT;
return type;
} else {
state.pop();
}
} else if (next.list && state.peek().list) {
if (type != ElementType.END_ELEMENT) {
// Emit the end element for the current item
type = ElementType.END_ELEMENT;
} else {
// Next element in the list
state.peek().value = next.value;
readNext();
type = ElementType.START_ELEMENT;
}
return type;
}
}
state.push(next);
int currentIndent = next.indent;
readNext();
if (next != null && next.list) {
if (next.name == null) {
// Bare value list
Parsed current = state.peek();
current.list = true;
current.value = next.value;
readNext();
}
} else {
// Read the attributes: they are indented relative to the element and have a value
while (next != null && next.indent > currentIndent && next.name != null) {
if (next.value != null) {
setAttributeValue(next.nsPrefix, next.name, next.value);
readNext();
} else {
if (lines != null && lines.parsed.list && lines.parsed.name == null && lines.parsed.value != null) {
String name = next.name;
String namespace = next.nsPrefix;
StringBuilder sb = new StringBuilder();
readNext();
while (next != null && next.list) {
sb.append(replaceProperties(next.value)).append(' ');
readNext();
}
this.setAttributeValue(namespace, name, sb.toString());
} else {
break;
}
}
}
}
type = ElementType.START_ELEMENT;
}
return type;
}
private void resetAttributes() {
this.attributeNames.clear();
this.attributeValues.clear();
this.attributeNamespaces.clear();
}
@Override
public Location getLocation() {
return new Location(getName(), row, column);
}
@Override
public String getAttributeName(int index, NamingStrategy strategy) {
return strategy.convert(attributeNames.get(index));
}
@Override
public String getAttributeNamespace(int index) {
return namespaces.get(attributeNamespaces.get(index));
}
@Override
public String getAttributeValue(String localName, NamingStrategy strategy) {
for (int i = 0; i < attributeNames.size(); i++) {
if (localName.equals(strategy.convert(attributeNames.get(i)))) {
return attributeValues.get(i);
}
}
return null;
}
@Override
public String getAttributeValue(int index) {
return attributeValues.get(index);
}
@Override
public String getElementText() {
return replaceProperties(state.peek().value);
}
@Override
public String getLocalName(NamingStrategy strategy) {
return strategy.convert(state.peek().name);
}
@Override
public String getNamespace() {
return namespaces.get(state.peek().nsPrefix);
}
@Override
public boolean hasNext() {
if (!state.isEmpty()) {
return true;
}
if (next == null) {
readNext();
}
return next != null;
}
@Override
public int getAttributeCount() {
return attributeNames.size();
}
@Override
public Map.Entry<String, String> getMapItem(String nameAttribute) {
String name = getLocalName(NamingStrategy.IDENTITY);
nextElement();
String type = getLocalName();
return new SimpleImmutableEntry<>(name, type);
}
@Override
public void endMapItem() {
nextElement();
}
@Override
public String[] readArray(String outer, String inner) {
require(ElementType.START_ELEMENT, null, outer);
List<String> elements = new ArrayList<>();
boolean loop;
do {
elements.add(getElementText());
nextElement();
require(ElementType.END_ELEMENT, null, outer);
loop = next.list;
if (loop) {
nextElement();
}
} while (loop);
return elements.toArray(new String[0]);
}
@Override
public void require(ElementType type, String namespace, String name) {
if (type != this.type
|| (namespace != null && !namespace.equals(getNamespace()))
|| (name != null && !name.equals(getLocalName()))) {
throw new ConfigurationReaderException("Expected event " + type
+ (name != null ? " with name '" + name + "'" : "")
+ (namespace != null && name != null ? " and" : "")
+ (namespace != null ? " with namespace '" + namespace + "'" : "")
+ " but got"
+ (type != this.type ? " " + this.type : "")
+ (name != null && getLocalName() != null && !name.equals(getLocalName())
? " name '" + getLocalName() + "'" : "")
+ (namespace != null && name != null
&& getLocalName() != null && !name.equals(getLocalName())
&& getNamespace() != null && !namespace.equals(getNamespace())
? " and" : "")
+ (namespace != null && getNamespace() != null && !namespace.equals(getNamespace())
? " namespace '" + getNamespace() + "'" : ""), new Location(getName(), row, 1));
}
}
@Override
public boolean hasFeature(ConfigurationFormatFeature feature) {
return false;
}
@Override
public void close() {
Util.close(reader);
}
@Override
public void setAttributeValue(String namespace, String name, String value) {
this.attributeNames.add(name);
this.attributeNamespaces.add(namespace);
this.attributeValues.add(replaceProperties(value));
}
public Map<String, Object> asMap() {
return Collections.singletonMap(lines.parsed.name, asMap(lines));
}
private Object asMap(Node node) {
if (node.hasChildren()) {
if (node.children.get(0).parsed.list) {
List<Object> children = new ArrayList<>(node.children.size());
for (Node child : node.children) {
children.add(asMap(child));
}
return children;
} else {
Map<String, Object> children = new LinkedHashMap<>(node.children.size());
for (Node child : node.children) {
children.put(child.parsed.name, asMap(child));
}
return children;
}
} else {
return node.parsed.value;
}
}
public static class Parsed {
final int row;
int indent;
boolean list;
String name;
String nsPrefix;
String value;
public Parsed(int row) {
this.row = row;
}
@Override
public String toString() {
return "{[" + row + "," + indent + "] " + nsPrefix + ":" + name + (list ? "[]" : "") + (value == null ? ":" : (": " + value)) + "}";
}
}
}
| 21,935
| 33.436421
| 171
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/yaml/YamlConfigurationWriter.java
|
package org.infinispan.commons.configuration.io.yaml;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import org.infinispan.commons.configuration.io.AbstractConfigurationWriter;
import org.infinispan.commons.configuration.io.ConfigurationFormatFeature;
import org.infinispan.commons.configuration.io.ConfigurationWriterException;
import org.infinispan.commons.configuration.io.NamingStrategy;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public class YamlConfigurationWriter extends AbstractConfigurationWriter {
public static final int INDENT = 2;
private boolean openTag;
private boolean attributes;
private boolean array;
public YamlConfigurationWriter(Writer writer, boolean clearTextSecrets) {
super(writer, INDENT, true, clearTextSecrets, NamingStrategy.CAMEL_CASE);
}
@Override
public void writeStartDocument() {
}
@Override
public void writeStartElement(String name) {
writeStartElement0(new Tag(name, false, true, true), naming);
}
private void writeStartElement0(Tag tag, NamingStrategy naming) {
try {
if (openTag) {
nl();
}
Tag parent = tagStack.peek();
tagStack.push(tag);
tab();
if (parent != null && parent.isRepeating()) {
writer.write("- ");
array = true;
} else {
array = false;
writeName(tag.getName(), naming);
}
attributes = false;
openTag = true;
indent();
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
private void writeName(String name, NamingStrategy naming) throws IOException {
writer.write(naming.convert(name));
writer.write(": ");
}
@Override
public void writeStartElement(String prefix, String namespace, String name) {
writeStartElement(prefixName(prefix, namespace, name));
}
private String prefixName(String prefix, String namespace, String name) {
if (prefix == null) {
return name;
} else if (namespaces.containsKey(prefix)) {
return prefix + ":" + name;
} else {
return namespace + ":" + name;
}
}
@Override
public void writeStartArrayElement(String name) {
writeStartElement0(new Tag(name, true, true, false), naming);
}
@Override
public void writeEndArrayElement() {
writeEndElement();
}
@Override
public void writeStartListElement(String name, boolean explicit) {
writeStartElement0(new Tag(name, true, explicit, true), naming);
}
@Override
public void writeStartListElement(String prefix, String namespace, String name, boolean explicit) {
writeStartListElement(prefixName(prefix, namespace, name), explicit);
}
public void writeNamespace(String prefix, String namespace) {
if (!openTag) {
throw new ConfigurationWriterException("Cannot set namespace without a started element");
}
}
@Override
public void writeDefaultNamespace(String namespace) {
if (!openTag) {
throw new ConfigurationWriterException("Cannot set namespace without a started element");
}
}
@Override
public void writeEndElement() {
try {
if (openTag && !attributes) {
writer.write('~');
nl();
}
openTag = false;
attributes = false;
tagStack.pop();
outdent();
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeEndDocument() {
if (!tagStack.isEmpty()) {
throw new ConfigurationWriterException("Tag stack not empty: " + tagStack);
}
try {
writer.flush();
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeAttribute(String name, String value) {
writeAttribute(name, value, true);
}
private void writeAttribute(String name, String value, boolean rename) {
try {
openTag = false;
if (!attributes) {
if (!array) {
nl();
}
attributes = true;
}
if (!array) {
tab();
}
array = false;
writer.write(rename ? naming.convert(name) : name);
if (value != null) {
writer.write(": \"");
writer.write(value);
writer.write('"');
} else {
writer.write(": ~");
}
nl();
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeAttribute(String name, Iterable<String> values) {
try {
openTag = false;
if (!attributes) {
nl();
attributes = true;
}
tab();
writer.write(naming.convert(name));
writer.write(":");
if (!values.iterator().hasNext()) {
writer.write(" ~");
nl();
} else {
nl();
indent();
for (String value : values) {
tab();
writer.write("- \"");
writer.write(value);
writer.write('"');
nl();
}
outdent();
}
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeArrayElement(String outer, String inner, String attribute, Iterable<String> values) {
try {
Iterator<String> it = values.iterator();
if (it.hasNext()) {
writeStartElement(outer);
nl();
while (it.hasNext()) {
tab();
writer.write("- \"");
writer.write(it.next());
writer.write('"');
nl();
}
openTag = false;
writeEndElement();
}
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeCharacters(String chars) {
try {
if (attributes) {
writeAttribute("value", chars);
} else {
writer.write("\"");
writer.write(chars);
writer.write('"');
nl();
}
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeEmptyElement(String name) {
writeStartElement(name);
writeEndElement();
}
@Override
public void writeComment(String comment) {
try {
writer.write("# ");
writer.write(comment);
nl();
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeStartMap(String name) {
writeStartElement(name);
}
@Override
public void writeMapItem(String element, String name, String key, String value) {
writeAttribute(key, value, false);
}
@Override
public void writeMapItem(String element, String name, String key) {
writeStartElement0(new Tag(key, false, true, true), NamingStrategy.IDENTITY);
writeStartElement(element);
}
@Override
public void writeEndMapItem() {
writeEndElement();
writeEndElement();
}
@Override
public void writeEndMap() {
writeEndElement();
}
@Override
public boolean hasFeature(ConfigurationFormatFeature feature) {
return false;
}
}
| 7,641
| 25.442907
| 105
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/json/JsonConfigurationWriter.java
|
package org.infinispan.commons.configuration.io.json;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayDeque;
import java.util.Deque;
import org.infinispan.commons.configuration.io.AbstractConfigurationWriter;
import org.infinispan.commons.configuration.io.ConfigurationFormatFeature;
import org.infinispan.commons.configuration.io.ConfigurationWriterException;
import org.infinispan.commons.configuration.io.NamingStrategy;
import org.infinispan.commons.dataconversion.internal.Json;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public class JsonConfigurationWriter extends AbstractConfigurationWriter {
private boolean attributes;
private boolean openTag;
private final Deque<Json> json;
public JsonConfigurationWriter(Writer writer, boolean prettyPrint, boolean clearTextSecrets) {
super(writer, 2, prettyPrint, clearTextSecrets, NamingStrategy.KEBAB_CASE);
json = new ArrayDeque<>();
}
@Override
public void writeStartDocument() {
json.push(Json.object());
}
@Override
public void writeStartElement(String name) {
writeStartElement(name, true);
}
private void writeStartElement(String name, boolean convert) {
if (convert) {
name = naming.convert(name);
}
Tag parentTag = tagStack.peek();
tagStack.push(new Tag(name, false, true, true));
Json object = Json.object();
Json parent = json.peek();
if (parent.isArray()) {
parent.add(object);
} else if (parentTag != null && parentTag.isRepeating()) {
if (parent.has(name)) {
parent.at(name).add(object);
} else {
parent.set(name, Json.array(object));
}
} else {
parent.set(name, object);
}
json.push(object);
openTag = true;
attributes = false;
}
@Override
public void writeStartElement(String prefix, String namespace, String name) {
writeStartElement(prefixName(prefix, namespace, name));
}
private String prefixName(String prefix, String namespace, String name) {
if (prefix == null) {
return name;
} else if (namespaces.containsKey(prefix)) {
return prefix + ":" + name;
} else {
return namespace + ":" + name;
}
}
@Override
public void writeStartArrayElement(String name) {
tagStack.push(new Tag(name, true, true, false));
Json array = Json.array();
json.peek().set(name, array);
json.push(array);
attributes = false;
}
@Override
public void writeEndArrayElement() {
tagStack.pop();
json.pop();
}
@Override
public void writeStartListElement(String name, boolean explicit) {
tagStack.push(new Tag(name, true, explicit, true));
Json array = Json.array();
json.peek().set(name, array);
json.push(array);
openTag = true;
attributes = false;
}
@Override
public void writeStartListElement(String prefix, String namespace, String name, boolean explicit) {
writeStartListElement(prefixName(prefix, namespace, name), explicit);
}
@Override
public void writeEndListElement() {
tagStack.pop();
json.pop();
openTag = false;
}
public void writeNamespace(String prefix, String namespace) {
if (!openTag) {
throw new ConfigurationWriterException("Cannot set namespace without a started element");
}
}
@Override
public void writeDefaultNamespace(String namespace) {
if (!openTag) {
throw new ConfigurationWriterException("Cannot set namespace without a started element");
}
}
@Override
public void writeEndElement() {
tagStack.pop();
json.pop();
openTag = false;
}
@Override
public void writeEndDocument() {
try {
Json json = this.json.pop();
writer.write(prettyPrint ? json.toPrettyString() : json.toString());
} catch (IOException e) {
throw new ConfigurationWriterException(e);
}
}
@Override
public void writeAttribute(String name, Iterable<String> values) {
Json parent = attributeParent();
Json array = Json.array();
for (String value : values) {
array.add(value);
}
parent.set(name, array);
}
private Json attributeParent() {
attributes = true;
Json parent = json.peek();
if (parent.isArray()) { // Replace the array with an object
json.pop();
parent = json.peek().replace(parent, Json.object());
json.push(parent);
}
return parent;
}
@Override
public void writeAttribute(String name, String value) {
Json parent = attributeParent();
parent.set(name, value);
}
@Override
public void writeAttribute(String name, boolean value) {
Json parent = attributeParent();
parent.set(name, value);
}
@Override
public void writeArrayElement(String outer, String inner, String attribute, Iterable<String> values) {
Json array = Json.array();
values.forEach(array::add);
json.peek().set(outer, array);
}
@Override
public void writeCharacters(String chars) {
//json.peek().add(chars);
}
@Override
public void writeEmptyElement(String name) {
json.peek().set(name, null);
}
@Override
public void writeComment(String comment) {
// Comments are unsupported in JSON
}
@Override
public void writeStartMap(String name) {
writeStartElement(name);
}
@Override
public void writeMapItem(String element, String name, String key, String value) {
json.peek().set(key, value);
}
@Override
public void writeMapItem(String element, String name, String key) {
writeStartElement(key, false);
writeStartElement(element);
}
@Override
public void writeEndMapItem() {
writeEndElement();
writeEndElement();
}
@Override
public void writeEndMap() {
writeEndElement();
}
@Override
public boolean hasFeature(ConfigurationFormatFeature feature) {
return false;
}
}
| 6,162
| 25.679654
| 105
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/io/json/JsonConfigurationReader.java
|
package org.infinispan.commons.configuration.io.json;
import java.io.BufferedReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.infinispan.commons.configuration.io.AbstractConfigurationReader;
import org.infinispan.commons.configuration.io.ConfigurationFormatFeature;
import org.infinispan.commons.configuration.io.ConfigurationReaderException;
import org.infinispan.commons.configuration.io.ConfigurationResourceResolver;
import org.infinispan.commons.configuration.io.Location;
import org.infinispan.commons.configuration.io.NamingStrategy;
import org.infinispan.commons.configuration.io.PropertyReplacer;
import org.infinispan.commons.dataconversion.internal.Json;
import org.infinispan.commons.util.SimpleImmutableEntry;
import org.infinispan.commons.util.Util;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public class JsonConfigurationReader extends AbstractConfigurationReader {
private static final String NAMESPACE = "_namespace";
private final Deque<Iterator<?>> iteratorStack;
private final Deque<String> nameStack;
private final BufferedReader reader;
private final List<Map.Entry<String, Json>> attributes = new ArrayList<>();
private final String namespace;
private String name;
private Json element, current;
private ElementType type;
public JsonConfigurationReader(BufferedReader reader, ConfigurationResourceResolver resourceResolver, Properties properties, PropertyReplacer replacer, NamingStrategy namingStrategy) {
super(resourceResolver, properties, replacer, namingStrategy);
this.reader = reader;
try (Stream<String> lines = this.reader.lines()) {
Map<String, Json> json = Json.read(lines.collect(Collectors.joining("\n"))).asJsonMap();
Json namespace = json.remove(NAMESPACE);
this.namespace = namespace == null ? "" : namespace.asString();
iteratorStack = new ArrayDeque<>();
iteratorStack.push(json.entrySet().iterator());
nameStack = new ArrayDeque<>();
type = ElementType.START_DOCUMENT;
}
}
@Override
public ElementType nextElement() {
Iterator<?> iterator = iteratorStack.peek();
if (iterator == null) {
return null;
} else if (iterator.hasNext()) {
Object item = iterator.next();
if (item instanceof Map.Entry) {
// this is a map
Map.Entry<String, ?> e = (Map.Entry<String, ?>) item;
Json value = (Json) e.getValue();
current = value;
if (value.isPrimitive()) {
throw new IllegalStateException("Primitive attribute should have been detected as attribute: " + e.getKey());
} else if (value.isObject()) {
processObject(value);
} else if (value.isArray()) {
processArray(e.getKey(), value);
} else if (value.isNull()) {
attributes.clear();
iteratorStack.push(Collections.emptyIterator());
}
name = e.getKey();
nameStack.push(name);
return (type = ElementType.START_ELEMENT);
} else if (item instanceof ElementEntry) {
ElementEntry entry = (ElementEntry) item;
name = entry.k;
type = entry.type;
if (type == ElementType.START_ELEMENT) {
nameStack.push(name);
current = element = entry.v;
if (element.isObject()) {
processObject(element);
} else if (element.isArray()) {
processArray(name, element);
} else {
throw new IllegalStateException("Element is neither an object nor an array: " + entry.k);
}
} else {
nameStack.pop();
iteratorStack.pop();
element = null;
}
return type;
} else {
throw new IllegalStateException(item.toString());
}
} else {
// We've reached the end of the current iterator
iteratorStack.pop();
element = null;
attributes.clear();
if (nameStack.isEmpty()) {
return (type = ElementType.END_DOCUMENT);
} else {
name = nameStack.pop();
return (type = ElementType.END_ELEMENT);
}
}
}
private void processArray(String name, Json value) {
attributes.clear();
List<Json> list = value.asJsonList();
List<ElementEntry> array = new ArrayList<>(list.size() * 2 + 2);
boolean primitive = (list.size() > 0 && list.get(0).isPrimitive());
if (!primitive) {
array.add(new ElementEntry(name, null, ElementType.START_ELEMENT));
}
for (Json json : list) {
array.add(new ElementEntry(name, json, ElementType.START_ELEMENT));
}
if (!primitive) {
array.add(new ElementEntry(name, null, ElementType.END_ELEMENT));
}
Iterator<ElementEntry> it = array.iterator();
iteratorStack.push(it);
current = element = it.next().v; // Already remove the first one
}
private void processObject(Json value) {
// Find all the attributes
attributes.clear();
Map<String, Json> map = value.asJsonMap();
for (Iterator<Map.Entry<String, Json>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, Json> entry = it.next();
if (entry.getValue().isPrimitive()) {
this.attributes.add(entry);
it.remove();
} else if (isArrayOfPrimitives(entry.getValue())) {
this.attributes.add(entry);
it.remove();
}
}
iteratorStack.push(map.entrySet().iterator());
}
private boolean isArrayOfPrimitives(Json json) {
if (json.isArray()) {
List<Json> list = json.asJsonList();
if (list.isEmpty()) {
return false;
}
for(Json item : list) {
if (!item.isPrimitive()) {
return false;
}
}
return true;
} else {
return false;
}
}
@Override
public Location getLocation() {
if (current != null) {
return new Location(getName(), current.getLine(), current.getColumn());
} else {
return new Location(getName(), 1, 0);
}
}
@Override
public String getAttributeName(int index, NamingStrategy strategy) {
String name = attributes.get(index).getKey();
return basename(strategy, name);
}
private String basename(NamingStrategy strategy, String name) {
int colon = name.lastIndexOf(':');
return strategy.convert(colon < 0 ? name : name.substring(colon + 1));
}
@Override
public String getLocalName(NamingStrategy strategy) {
return basename(strategy, name);
}
@Override
public String getAttributeNamespace(int index) {
String name = attributes.get(index).getKey();
int colon = name.lastIndexOf(':');
return colon < 0 ? "" : name.substring(0, colon);
}
@Override
public String getAttributeValue(String name, NamingStrategy strategy) {
for (Map.Entry<String, Json> attribute : attributes) {
if (name.equals(basename(strategy, attribute.getKey()))) {
return replaceProperties(attribute.getValue().asString());
}
}
return null;
}
@Override
public String[] getListAttributeValue(int index) {
Json value = attributes.get(index).getValue();
if (value.isArray()) {
List<Json> list = value.asJsonList();
String[] array = new String[list.size()];
for(int i = 0; i < list.size(); i++) {
array[i] = replaceProperties(list.get(i).asString());
}
return array;
} else {
return replaceProperties(value.isString() ? value.asString() : value.toString()).split("\\s+");
}
}
@Override
public String getAttributeValue(int index) {
Json value = attributes.get(index).getValue();
return replaceProperties(value.isString() ? value.asString() : value.toString());
}
@Override
public String getElementText() {
String text = (element != null && element.isPrimitive()) ? element.asString() : null;
nextElement();// Consume the end element
return text;
}
@Override
public String getNamespace() {
int colon = name.lastIndexOf(':');
return colon < 0 ? namespace : name.substring(0, colon);
}
@Override
public boolean hasNext() {
return !iteratorStack.isEmpty();
}
@Override
public int getAttributeCount() {
return attributes.size();
}
@Override
public void require(ElementType type, String namespace, String name) {
if (type != this.type
|| (namespace != null && !namespace.equals(getNamespace()))
|| (name != null && !name.equals(getLocalName()))) {
throw new ConfigurationReaderException("Expected event " + type
+ (name != null ? " with name '" + name + "'" : "")
+ (namespace != null && name != null ? " and" : "")
+ (namespace != null ? " with namespace '" + namespace + "'" : "")
+ " but got"
+ (type != this.type ? " " + this.type : "")
+ (name != null && getLocalName() != null && !name.equals(getLocalName())
? " name '" + getLocalName() + "'" : "")
+ (namespace != null && name != null
&& getLocalName() != null && !name.equals(getLocalName())
&& getNamespace() != null && !namespace.equals(getNamespace())
? " and" : "")
+ (namespace != null && getNamespace() != null && !namespace.equals(getNamespace())
? " namespace '" + getNamespace() + "'" : ""), new Location(getName(), 1, 1));
}
}
@Override
public Map.Entry<String, String> getMapItem(String nameAttribute) {
String name = getLocalName(NamingStrategy.IDENTITY);
nextElement();
String type = getLocalName();
return new SimpleImmutableEntry<>(name, type);
}
@Override
public void endMapItem() {
nextElement();
}
@Override
public String[] readArray(String outer, String inner) {
Iterator<ElementEntry> iterator = (Iterator<ElementEntry>) iteratorStack.peek();
List<String> array = new ArrayList<>();
while (iterator.hasNext()) {
ElementEntry next = iterator.next();
if (next.type == ElementType.END_ELEMENT) {
array.add(next.v.asString());
}
}
nextElement();
require(ElementType.END_ELEMENT, null, outer);
return array.stream().toArray(String[]::new);
}
@Override
public boolean hasFeature(ConfigurationFormatFeature feature) {
return false;
}
@Override
public void close() {
Util.close(reader);
}
@Override
public void setAttributeValue(String namespace, String name, String value) {
attributes.add(new SimpleImmutableEntry<>(name, Json.make(value)));
}
private static class ElementEntry {
final String k;
final Json v;
final ElementType type;
ElementEntry(String k, Json v, ElementType type) {
this.k = k;
this.v = v;
this.type = type;
}
}
}
| 11,642
| 33.859281
| 187
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/AttributeValidator.java
|
package org.infinispan.commons.configuration.attributes;
import org.infinispan.commons.logging.Log;
/**
* AttributeValidator.
*
* @author Tristan Tarrant
* @since 7.2
*/
@FunctionalInterface
public interface AttributeValidator<T> {
void validate(T value);
static <E extends Number> AttributeValidator<E> greaterThanZero(Enum<?> attribute) {
return value -> {
if (value.intValue() < 1) {
throw Log.CONFIG.attributeMustBeGreaterThanZero(value.intValue(), attribute);
}
};
}
}
| 533
| 22.217391
| 89
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/AttributeCopier.java
|
package org.infinispan.commons.configuration.attributes;
/**
* AttributeCopier. Usually an attribute is copied by using the {@link Object#clone()} method. When
* this method is not enough, you can provide a custom attribute copier by implementing this
* interface
*
* @author Tristan Tarrant
* @since 7.2
*/
public interface AttributeCopier<T> {
T copyAttribute(T attribute);
}
| 389
| 26.857143
| 99
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/Updatable.java
|
package org.infinispan.commons.configuration.attributes;
/**
* An interface for defining updatable attributes/attributeset. The default implementation is a no-op.
*
* @author Tristan Tarrant
* @since 13.0
*/
public interface Updatable<T> {
/**
* Updates the mutable part of this instance with the values of the other instance
* @param other
*/
default void update(String parentName, T other) {
// Do nothing
}
/**
* Verifies that updating the mutable part of this instance with the values of the other instance is possible
* @param other
*/
default void validateUpdate(String parentName, T other) {
// Do nothing
}
}
| 680
| 23.321429
| 112
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/ConfigurationElement.java
|
package org.infinispan.commons.configuration.attributes;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import org.infinispan.commons.configuration.io.ConfigurationWriter;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.util.Util;
/**
* An abstract class which represents a configuration element, with attributes and child elements.
*
* @author Gustavo Fernandes
* @author Tristan Tarrant
* @since 13.0
**/
public abstract class ConfigurationElement<T extends ConfigurationElement> implements Matchable<T>, Updatable<T> {
public static final ConfigurationElement<?>[] CHILDLESS = new ConfigurationElement[0];
protected final String element;
protected final AttributeSet attributes;
protected final ConfigurationElement<?>[] children;
protected final boolean repeated;
protected ConfigurationElement(Enum<?> element, AttributeSet attributes, ConfigurationElement<?>... children) {
this(element.toString(), false, attributes, children);
}
protected ConfigurationElement(String element, AttributeSet attributes, ConfigurationElement<?>... children) {
this(element, false, attributes, children);
}
protected ConfigurationElement(String element, boolean repeated, AttributeSet attributes, ConfigurationElement<?>... children) {
this.element = element;
this.repeated = repeated;
this.attributes = attributes.checkProtection();
this.children = (children != null && children.length > 0) ? children : CHILDLESS;
}
public final String elementName() {
return element;
}
public final AttributeSet attributes() {
return attributes;
}
public ConfigurationElement<?>[] children() {
return children;
}
public Attribute<?> findAttribute(String name) {
int sep = name.indexOf('.');
if (sep < 0) {
if (!attributes.contains(name)) {
throw Log.CONFIG.noAttribute(name, element);
} else {
return attributes.attribute(name);
}
} else {
String part = name.substring(0, sep);
for (ConfigurationElement<?> child : children) {
if (part.equals(child.elementName())) {
return child.findAttribute(name.substring(sep + 1));
}
}
throw Log.CONFIG.noAttribute(name, element);
}
}
protected static <T extends ConfigurationElement> ConfigurationElement<T> list(Enum<?> element, List<T> list) {
ConfigurationElement[] configurationElements = list.toArray(new ConfigurationElement[0]);
return new ConfigurationElement<T>(element, AttributeSet.EMPTY, configurationElements) {
};
}
@Override
public boolean matches(T other) {
if (!attributes.matches(other.attributes)) return false;
if (children.length != other.children.length) return false;
for (int i = 0; i < children.length; i++) {
ConfigurationElement ours = children[i];
ConfigurationElement theirs = other.children[i];
if (!ours.matches(theirs)) return false;
}
return true;
}
@Override
public void update(String parentName, T other) {
String qualifiedName = qualifiedName(parentName);
this.attributes.update(qualifiedName, other.attributes);
for (int i = 0; i < children.length; i++) {
ConfigurationElement ours = children[i];
ConfigurationElement theirs = other.children[i];
ours.update(qualifiedName, theirs);
}
}
@Override
public void validateUpdate(String parentName, T other) {
String qualifiedName = qualifiedName(parentName);
IllegalArgumentException iae = Log.CONFIG.invalidConfiguration(qualifiedName);
try {
this.attributes.validateUpdate(qualifiedName, other.attributes);
} catch (Throwable t) {
Util.unwrapSuppressed(iae, t);
}
for (int i = 0; i < children.length; i++) {
ConfigurationElement ours = children[i];
ConfigurationElement theirs = other.children[i];
try {
ours.validateUpdate(qualifiedName, theirs);
} catch (Throwable t) {
Util.unwrapSuppressed(iae, t);
}
}
if (iae.getSuppressed().length > 0) {
throw iae;
}
}
private String qualifiedName(String parentName) {
return parentName == null ? element : parentName + "." + element;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConfigurationElement<?> that = (ConfigurationElement<?>) o;
return attributes.equals(that.attributes) && Arrays.equals(children, that.children);
}
@Override
public int hashCode() {
int result = Objects.hash(attributes);
result = 31 * result + Arrays.hashCode(children);
return result;
}
@Override
public String toString() {
if (children == CHILDLESS) {
return attributes.toString(null);
} else {
StringBuilder sb = new StringBuilder();
sb.append('[');
sb.append(attributes.toString(null));
for(ConfigurationElement<?> child : children){
sb.append(", ");
sb.append(child.elementName());
sb.append('=');
sb.append(child);
}
sb.append(']');
return sb.toString();
}
}
public boolean isModified() {
if (attributes.isModified()) return true;
for (ConfigurationElement<?> child : children) {
if (child.isModified()) return true;
}
return false;
}
/**
* Writes this {@link ConfigurationElement} to the writer
*
* @param writer
*/
public void write(ConfigurationWriter writer) {
if (isModified()) {
if (attributes.attributes().isEmpty() && children.length > 0 && Arrays.stream(children).allMatch(c -> children[0].element.equals(c.element))) {
// Simple array: all children are homogeneous
writer.writeStartListElement(element, true);
for (ConfigurationElement<?> child : children) {
child.write(writer);
}
writer.writeEndListElement();
} else {
writer.writeStartElement(element);
attributes.write(writer);
String repeatElement = null;
for (ConfigurationElement<?> child : children) {
if (child.repeated) {
if (!child.element.equals(repeatElement)) {
if (repeatElement != null) {
writer.writeEndListElement();
}
repeatElement = child.element;
writer.writeStartListElement(repeatElement, false);
}
} else {
repeatElement = null;
}
child.write(writer);
}
if (repeatElement != null) {
writer.writeEndListElement();
}
writer.writeEndElement();
}
}
}
protected static <T> ConfigurationElement<?>[] children(Collection<T> children) {
return children.toArray(CHILDLESS);
}
protected static ConfigurationElement<?> child(Attribute<?> attribute) {
return new AttributeAsElement(attribute);
}
private static class AttributeAsElement extends ConfigurationElement<AttributeAsElement> {
private final Attribute<?> attribute;
protected AttributeAsElement(Attribute<?> attribute) {
super(attribute.name(), false, AttributeSet.EMPTY, CHILDLESS);
this.attribute = attribute;
}
@Override
public void write(ConfigurationWriter writer) {
attribute.write(writer, attribute.name());
}
}
}
| 7,866
| 32.909483
| 152
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/CollectionAttributeCopier.java
|
package org.infinispan.commons.configuration.attributes;
import static org.infinispan.commons.logging.Log.CONFIG;
import java.util.HashMap;
import java.util.HashSet;
/**
* CollectionAttributeCopier. This {@link AttributeCopier} can handle a handful of "known"
* collection types ( {@link HashSet}, {@link HashMap} )
*
* @author Tristan Tarrant
* @since 7.2
*/
public class CollectionAttributeCopier<T> implements AttributeCopier<T> {
private static final AttributeCopier<Object> INSTANCE = new CollectionAttributeCopier<>();
public static <T> CollectionAttributeCopier<T> collectionCopier() {
return (CollectionAttributeCopier<T>) INSTANCE;
}
@SuppressWarnings("unchecked")
@Override
public T copyAttribute(T attribute) {
if (attribute == null) {
return null;
}
Class<?> klass = attribute.getClass();
if (HashSet.class.equals(klass)) {
return (T) new HashSet<>((HashSet<?>)attribute);
} else if (HashMap.class.equals(klass)) {
return (T) new HashMap<>((HashMap<?, ?>)attribute);
} else {
throw CONFIG.noAttributeCopierForType(klass);
}
}
}
| 1,157
| 28.692308
| 93
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/AttributeDefinition.java
|
package org.infinispan.commons.configuration.attributes;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Supplier;
import org.infinispan.commons.CacheConfigurationException;
/**
*
* AttributeDefinition. Defines the characteristics of a configuration attribute. It is used to
* construct an actual {@link Attribute} holder.
*
* An attribute definition has the following characteristics:
* <ul>
* <li>A name</li>
* <li>A default value or a value initializer</li>
* <li>A type, which needs to be specified if it cannot be inferred from the default value, i.e.
* when it is null</li>
* <li>Whether an attribute is immutable or not, i.e. whether its value is constant after
* initialization or it can be changed</li>
* <li>A validator which intercepts invalid values</li>
* </ul>
*
* @author Tristan Tarrant
* @since 7.2
*/
public final class AttributeDefinition<T> {
private final String name;
private final T defaultValue;
private final boolean immutable;
private final boolean autoPersist;
private final boolean global;
private final AttributeCopier<T> copier;
private final AttributeInitializer<? extends T> initializer;
private final AttributeValidator<? super T> validator;
private final AttributeSerializer<? super T> serializer;
private final AttributeParser<? super T> parser;
private final Class<T> type;
private final int deprecatedMajor;
private final int deprecatedMinor;
AttributeDefinition(String name, T initialValue, Class<T> type,
boolean immutable, boolean autoPersist, boolean global,
AttributeCopier<T> copier,
AttributeValidator<? super T> validator,
AttributeInitializer<? extends T> initializer,
AttributeSerializer<? super T> serializer,
AttributeParser<? super T> parser,
int deprecatedMajor, int deprecatedMinor) {
this.name = name;
this.defaultValue = initialValue;
this.immutable = immutable;
this.autoPersist = autoPersist;
this.global = global;
this.copier = copier;
this.initializer = initializer;
this.validator = validator;
this.serializer = serializer;
this.parser = parser;
this.type = type;
this.deprecatedMajor = deprecatedMajor;
this.deprecatedMinor = deprecatedMinor;
}
public String name() {
return name;
}
public Class<T> getType() {
return type;
}
public T getDefaultValue() {
return initializer != null ? initializer().initialize() : defaultValue;
}
public boolean isImmutable() {
return immutable;
}
public boolean isAutoPersist() {
return autoPersist;
}
public boolean isRepeated() {
return type.isArray() || Collection.class.isAssignableFrom(type);
}
public boolean isGlobal() {
return global;
}
public boolean isDeprecated(int major, int minor) {
return (major > deprecatedMajor || (major == deprecatedMajor && minor > deprecatedMinor));
}
public AttributeCopier<T> copier() {
return copier;
}
public AttributeInitializer<? extends T> initializer() {
return initializer;
}
AttributeValidator<? super T> validator() {
return validator;
}
public AttributeSerializer<? super T> serializer() {
return serializer;
}
public T parse(String value) {
return (T) parser.parse(type, value);
}
public Attribute<T> toAttribute() {
return new Attribute<T>(this);
}
public void validate(T value) {
if (validator != null) {
validator.validate(value);
}
}
public static <T> Builder<T> builder(Enum<?> name, T defaultValue) {
return builder(name.toString(), defaultValue);
}
public static <T> Builder<T> builder(String name, T defaultValue) {
if (defaultValue != null) {
return new Builder<T>(name, defaultValue, (Class<T>) defaultValue.getClass());
} else {
throw new CacheConfigurationException("Must specify type when passing null for AttributeDefinition " + name);
}
}
public static <T> Builder<T> builder(Enum<?> name, T defaultValue, Class<T> klass) {
return new Builder<>(name.toString(), defaultValue, klass);
}
public static <T> Builder<T> builder(String name, T defaultValue, Class<T> klass) {
return new Builder<>(name, defaultValue, klass);
}
public static <T> Builder<Class<? extends T>> classBuilder(String name, Class<T> klass) {
return new Builder(name, null, Class.class);
}
public static <T> Builder<Supplier<? extends T>> supplierBuilder(String name, Class<T> klass) {
return new Builder(name, null, Supplier.class);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AttributeDefinition<?> that = (AttributeDefinition<?>) o;
if (immutable != that.immutable) return false;
if (autoPersist != that.autoPersist) return false;
if (global != that.global) return false;
if (!Objects.equals(name, that.name)) return false;
if (!Objects.equals(defaultValue, that.defaultValue)) return false;
if (!Objects.equals(copier, that.copier)) return false;
if (!Objects.equals(initializer, that.initializer)) return false;
if (!Objects.equals(validator, that.validator)) return false;
if (!Objects.equals(serializer, that.serializer)) return false;
return Objects.equals(type, that.type);
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0);
result = 31 * result + (immutable ? 1 : 0);
result = 31 * result + (autoPersist ? 1 : 0);
result = 31 * result + (global ? 1 : 0);
result = 31 * result + (copier != null ? copier.hashCode() : 0);
result = 31 * result + (initializer != null ? initializer.hashCode() : 0);
result = 31 * result + (validator != null ? validator.hashCode() : 0);
result = 31 * result + (serializer != null ? serializer.hashCode() : 0);
result = 31 * result + (type != null ? type.hashCode() : 0);
return result;
}
public static final class Builder<T> {
private final String name;
private final T defaultValue;
private final Class<T> type;
private boolean immutable = false;
private boolean autoPersist = true;
private boolean global = true;
private AttributeCopier<T> copier = null;
private AttributeInitializer<? extends T> initializer;
private AttributeValidator<? super T> validator;
private AttributeSerializer<? super T> serializer = AttributeSerializer.DEFAULT;
private AttributeParser<? super T> parser = AttributeParser.DEFAULT;
private int deprecatedMajor = Integer.MAX_VALUE;
private int deprecatedMinor = Integer.MAX_VALUE;
private Builder(String name, T defaultValue, Class<T> type) {
this.name = name;
this.defaultValue = defaultValue;
this.type = type;
}
public Builder<T> immutable() {
this.immutable = true;
return this;
}
public Builder<T> copier(AttributeCopier<T> copier) {
this.copier = copier;
return this;
}
public Builder<T> initializer(AttributeInitializer<? extends T> initializer) {
this.initializer = initializer;
return this;
}
public Builder<T> autoPersist(boolean autoPersist) {
this.autoPersist = autoPersist;
return this;
}
public Builder<T> global(boolean global) {
this.global = global;
return this;
}
public Builder<T> validator(AttributeValidator<? super T> validator) {
this.validator = validator;
return this;
}
public Builder<T> serializer(AttributeSerializer<? super T> serializer) {
this.serializer = serializer;
return this;
}
public Builder<T> parser(AttributeParser<? super T> parser) {
this.parser = parser;
return this;
}
public Builder<T> deprecatedSince(int major, int minor) {
this.deprecatedMajor = major;
this.deprecatedMinor = minor;
return this;
}
public AttributeDefinition<T> build() {
return new AttributeDefinition<>(name, defaultValue, type, immutable, autoPersist, global, copier, validator, initializer, serializer, parser, deprecatedMajor, deprecatedMinor);
}
}
}
| 8,724
| 32.174905
| 186
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/AttributeInitializer.java
|
package org.infinispan.commons.configuration.attributes;
/**
* AttributeInitializer. Provides a way to initialize an attribute's value, whenever this needs to be done at Attribute construction time.
* This is usually needed when the value is a mutable object.
*
* @author Tristan Tarrant
* @since 7.2
*/
public interface AttributeInitializer<T> {
T initialize();
}
| 375
| 27.923077
| 138
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/AttributeParser.java
|
package org.infinispan.commons.configuration.attributes;
import org.infinispan.commons.util.Util;
/**
* AttributeParser.
*
* @since 15.0
*/
public interface AttributeParser<T> {
AttributeParser<Object> DEFAULT = (klass, value) -> Util.fromString(klass, value);
T parse(Class klass, String value);
}
| 312
| 19.866667
| 85
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/AttributeSet.java
|
package org.infinispan.commons.configuration.attributes;
import static org.infinispan.commons.logging.Log.CONFIG;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.io.ConfigurationWriter;
import org.infinispan.commons.util.TypedProperties;
/**
* AttributeSet is a container for {@link Attribute}s. It is constructed by passing in a list of
* {@link AttributeDefinition}s. AttributeSets are initially unprotected, which means that the contained attributes can
* be modified. If the {@link #protect()} method is invoked then only attributes which are not
* {@link AttributeDefinition#isImmutable()} can be modified from then on.
*
* @author Tristan Tarrant
* @since 7.2
*/
public class AttributeSet implements AttributeListener<Object>, Matchable<AttributeSet>, Updatable<AttributeSet> {
public static final AttributeSet EMPTY = new AttributeSet(null, "", null, new AttributeDefinition[0]).protect();
private final Class<?> klass;
private final String name;
private final Map<String, Attribute<?>> attributes;
private boolean protect;
private final Map<String, RemovedAttribute> removed;
private boolean touched;
public AttributeSet(Class<?> klass, AttributeDefinition<?>... attributeDefinitions) {
this(klass, klass.getSimpleName(), null, attributeDefinitions);
}
public AttributeSet(String name, AttributeDefinition<?>... attributeDefinitions) {
this(name, null, attributeDefinitions);
}
public AttributeSet(Class<?> klass, AttributeSet attributeSet, AttributeDefinition<?>... attributeDefinitions) {
this(klass, klass.getSimpleName(), attributeSet, attributeDefinitions);
}
public AttributeSet(String name, AttributeSet attributeSet, AttributeDefinition<?>[] attributeDefinitions) {
this(null, name, attributeSet, attributeDefinitions);
}
public AttributeSet(Class<?> klass, Enum<?> name, AttributeDefinition<?>... attributeDefinitions) {
this(klass, name.name(), null, attributeDefinitions);
}
public AttributeSet(Class<?> klass, String name, AttributeSet attributeSet, AttributeDefinition<?>[] attributeDefinitions) {
this(klass, name, attributeSet, attributeDefinitions, null);
}
public AttributeSet(Class<?> klass, String name, AttributeSet attributeSet, AttributeDefinition<?>[] attributeDefinitions, RemovedAttribute[] removedAttributes) {
this.klass = klass;
this.name = name;
if (attributeSet != null) {
this.attributes = new LinkedHashMap<>(attributeDefinitions.length + attributeSet.attributes.size());
for (Attribute<?> attribute : attributeSet.attributes.values()) {
this.attributes.put(attribute.name(), attribute.getAttributeDefinition().toAttribute());
}
} else {
this.attributes = new LinkedHashMap<>(attributeDefinitions.length);
}
for (AttributeDefinition<?> def : attributeDefinitions) {
if (attributes.containsKey(def.name())) {
throw CONFIG.attributeSetDuplicateAttribute(def.name(), name);
}
Attribute<Object> attribute = (Attribute<Object>) def.toAttribute();
if (!attribute.isImmutable())
attribute.addListener(this);
this.attributes.put(def.name(), attribute);
}
if (removedAttributes == null) {
this.removed = Collections.emptyMap();
} else {
this.removed = new HashMap<>(removedAttributes.length);
for (RemovedAttribute i : removedAttributes) {
removed.put(i.name, i);
}
}
}
public Class<?> getKlass() {
return klass;
}
public String getName() {
return name;
}
/**
* Returns whether this attribute set contains the specified named attribute
*
* @param name the name of the attribute
*/
public boolean contains(String name) {
return attributes.containsKey(name);
}
/**
* Returns whether this set contains the specified attribute definition
*
* @param def the {@link AttributeDefinition}
*/
public <T> boolean contains(AttributeDefinition<T> def) {
return contains(def.name());
}
/**
* Returns the named attribute
*
* @param name the name of the attribute to return
* @return the attribute
*/
@SuppressWarnings("unchecked")
public <T> Attribute<T> attribute(String name) {
return (Attribute<T>) this.attributes.get(name);
}
/**
* Returns the named attribute
*
* @param name the name of the attribute to return
* @return the attribute
*/
public <T> Attribute<T> attribute(Enum<?> name) {
return attribute(name.toString());
}
/**
* Returns the attribute identified by the supplied {@link AttributeDefinition}
*
* @param def the attribute definition
* @return the attribute
*/
public <T> Attribute<T> attribute(AttributeDefinition<T> def) {
Attribute<T> attribute = attribute(def.name());
if (attribute != null)
return attribute;
else
throw CONFIG.noSuchAttribute(def.name(), name);
}
/**
* Copies all attribute from another AttributeSet using the supplied {@link Combine.Attributes} strategy.
*
* @param other the source AttributeSet
* @param combine the attribute combine strategy
*/
public void read(AttributeSet other, Combine combine) {
for (Attribute<?> attribute : attributes.values()) {
if (attribute.getAttributeDefinition().isRepeated()) {
Attribute<Object> a = other.attribute(attribute.name());
if (a.isModified()) {
if (combine.repeatedAttributes() == Combine.RepeatedAttributes.MERGE) {
((Attribute<Object>) attribute).merge(a);
} else {
((Attribute<Object>) attribute).read(a);
}
}
} else {
if (combine.attributes() == Combine.Attributes.OVERRIDE) {
attribute.reset();
}
Attribute<Object> a = other.attribute(attribute.name());
if (a.isModified()) {
((Attribute<Object>) attribute).read(a);
}
}
}
}
/**
* Returns a new ValueSet where immutable {@link Attribute}s are write-protected
*
* @return
*/
public AttributeSet protect() {
AttributeDefinition<?>[] attrDefs = new AttributeDefinition[attributes.size()];
int i = 0;
for (Attribute<?> attribute : attributes.values()) {
attrDefs[i++] = attribute.getAttributeDefinition();
}
AttributeSet protectedSet = new AttributeSet(klass, name, null, attrDefs);
for (Attribute<?> attribute : protectedSet.attributes.values()) {
Attribute<?> localAttr = this.attributes.get(attribute.name());
attribute.read((Attribute) localAttr);
attribute.protect();
}
protectedSet.protect = true;
protectedSet.touched = this.touched;
return protectedSet;
}
/**
* Returns whether any attributes in this set have been modified
*/
public boolean isModified() {
for (Attribute<?> attribute : attributes.values()) {
if (attribute.isModified())
return true;
}
return false;
}
/**
* Returns whether this attribute set is protected
*/
public boolean isProtected() {
return protect;
}
/**
* Writer a single attribute to the specified {@link ConfigurationWriter} using the attribute's xmlName
*
* @param writer the writer
* @param def the Attribute definition
*/
public void write(ConfigurationWriter writer, AttributeDefinition<?> def) {
write(writer, def, def.name());
}
/**
* Writer a single attribute to the specified {@link ConfigurationWriter} using the supplied name
*
* @param writer the writer
* @param def the Attribute definition
* @param name the XML tag name for the attribute
*/
public void write(ConfigurationWriter writer, AttributeDefinition<?> def, Enum<?> name) {
write(writer, def, name.toString());
}
/**
* Writer a single attribute to the specified {@link ConfigurationWriter} using the supplied name
*
* @param writer the writer
* @param def the Attribute definition
* @param name the XML tag name for the attribute
*/
public void write(ConfigurationWriter writer, AttributeDefinition<?> def, String name) {
Attribute<?> attribute = attribute(def);
attribute.write(writer, name);
}
/**
* Writes this attributeset to the specified ConfigurationWriter as an element
*
* @param writer
*/
public void write(ConfigurationWriter writer, String name) {
if (isModified()) {
writer.writeStartElement(name);
write(writer);
writer.writeEndElement();
}
}
/**
* Writes this attributeset to the specified ConfigurationWriter as an element
*
* @param writer
*/
public void write(ConfigurationWriter writer, Enum<?> name) {
write(writer, name.toString());
}
/**
* Writes the specified attributes in this attributeset to the specified ConfigurationWriter as an element
*
* @param writer
*/
public void write(ConfigurationWriter writer, String persistentName, AttributeDefinition<?>... defs) {
if (Arrays.stream(defs).anyMatch(def -> attribute(def).isModified())) {
writer.writeStartElement(persistentName);
for (AttributeDefinition def : defs) {
Attribute attr = attribute(def);
attr.write(writer, attr.getAttributeDefinition().name());
}
writer.writeEndElement();
}
}
/**
* Writes the attributes of this attributeset as part of the current element
*
* @param writer
*/
public void write(ConfigurationWriter writer) {
for (Attribute<?> attr : attributes.values()) {
if (attr.isPersistent())
attr.write(writer, attr.getAttributeDefinition().name());
}
}
/**
* Validates the {@link Attribute} values.
*/
public void validate() {
attributes.values().forEach(Attribute::validate);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((attributes == null) ? 0 : attributes.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AttributeSet other = (AttributeSet) obj;
if (attributes == null) {
if (other.attributes != null)
return false;
} else if (!attributes.equals(other.attributes))
return false;
return true;
}
@Override
public boolean matches(AttributeSet other) {
if (other.attributes.size() != attributes.size())
return false;
for (Map.Entry<String, Attribute<?>> e : attributes.entrySet()) {
String key = e.getKey();
Attribute<?> value = e.getValue();
if (value == null) {
if (!(other.attributes.containsKey(key) && other.attributes.get(key) == null))
return false;
} else {
if (!value.matches(other.attributes.get(key)))
return false;
}
}
return true;
}
@Override
public void update(String parentName, AttributeSet other) {
for (Map.Entry<String, Attribute<?>> e : attributes.entrySet()) {
e.getValue().update(parentName, other.attribute(e.getKey()));
}
}
@Override
public void validateUpdate(String parentName, AttributeSet other) {
IllegalArgumentException iae = new IllegalArgumentException();
for (Map.Entry<String, Attribute<?>> e : attributes.entrySet()) {
try {
e.getValue().validateUpdate(parentName, other.attribute(e.getKey()));
} catch (Throwable t) {
iae.addSuppressed(t);
}
}
if (iae.getSuppressed().length > 0) {
throw iae;
}
}
@Override
public String toString() {
return toString(name);
}
public String toString(String name) {
StringBuilder sb = new StringBuilder();
if (name != null) {
sb.append(name);
sb.append(" = ");
}
sb.append("[");
boolean comma = false;
for (Attribute<?> value : attributes.values()) {
if (comma) {
sb.append(", ");
} else {
comma = true;
}
sb.append(value.toString());
}
sb.append("]");
return sb.toString();
}
public AttributeSet checkProtection() {
if (!protect) {
throw CONFIG.unprotectedAttributeSet(name);
}
return this;
}
public void reset() {
if (protect) {
throw CONFIG.protectedAttributeSet(name);
}
for (Attribute<?> attribute : attributes.values()) {
attribute.reset();
}
}
@Override
public void attributeChanged(Attribute<Object> attribute, Object oldValue) {
}
public Collection<Attribute<?>> attributes() {
return attributes.values();
}
public boolean isEmpty() {
return attributes.entrySet().stream().allMatch(attrs -> {
Attribute<?> attr = attrs.getValue();
return attr.isNull() || !attr.isModified();
});
}
public TypedProperties fromProperties(TypedProperties properties, String prefix) {
for (Attribute<?> attr : attributes.values()) {
String name = prefix + attr.name();
if (properties.containsKey(name)) {
attr.fromString(properties.getProperty(name, true));
}
}
return properties;
}
public boolean isRemoved(String name, int major, int minor) {
RemovedAttribute r = removed.get(name);
return r != null && (major < r.major || (major == r.major && minor < r.minor));
}
public void touch() {
this.touched = true;
}
public boolean isTouched() {
return touched;
}
public static final class RemovedAttribute {
final String name;
final int major;
final int minor;
public RemovedAttribute(Enum<?> name, int major, int minor) {
this(name.toString(), major, minor);
}
public RemovedAttribute(String name, int major, int minor) {
this.name = name;
this.major = major;
this.minor = minor;
}
}
}
| 14,783
| 30.455319
| 165
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/PropertiesAttributeSerializer.java
|
package org.infinispan.commons.configuration.attributes;
import java.util.Map;
import org.infinispan.commons.configuration.io.ConfigurationFormatFeature;
import org.infinispan.commons.configuration.io.ConfigurationWriter;
public class PropertiesAttributeSerializer implements AttributeSerializer<Map<?, ?>> {
public static final PropertiesAttributeSerializer PROPERTIES = new PropertiesAttributeSerializer("properties", "property", "name");
private final String collectionElement;
private final String itemElement;
private final String nameAttribute;
public PropertiesAttributeSerializer(Enum<?> collectionElement, Enum<?> itemElement, Enum<?> nameAttribute) {
this(collectionElement.toString(), itemElement.toString(), nameAttribute.toString());
}
public PropertiesAttributeSerializer(String collectionElement, String itemElement, String nameAttribute) {
this.collectionElement = collectionElement;
this.itemElement = itemElement;
this.nameAttribute = nameAttribute;
}
@Override
public void serialize(ConfigurationWriter writer, String name, Map<?, ?> properties) {
if (!properties.isEmpty()) {
if (writer.hasFeature(ConfigurationFormatFeature.BARE_COLLECTIONS)) {
for (Map.Entry<?, ?> entry : properties.entrySet()) {
writer.writeStartElement(itemElement);
writer.writeAttribute(nameAttribute, entry.getKey().toString());
writer.writeCharacters(entry.getValue().toString());
writer.writeEndElement();
}
} else {
writer.writeStartMap(collectionElement);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
writer.writeMapItem(itemElement, nameAttribute, entry.getKey().toString(), entry.getValue().toString());
}
writer.writeEndMap();
}
}
}
}
| 1,895
| 42.090909
| 134
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/TypedPropertiesAttributeCopier.java
|
package org.infinispan.commons.configuration.attributes;
import org.infinispan.commons.util.TypedProperties;
/**
* TypedPropertiesAttributeCopier. This {@link AttributeCopier} can handle {@link TypedProperties}
*
* @author Tristan Tarrant
* @since 7.2
*/
public class TypedPropertiesAttributeCopier implements AttributeCopier<TypedProperties> {
public static final AttributeCopier<TypedProperties> INSTANCE = new TypedPropertiesAttributeCopier();
@Override
public TypedProperties copyAttribute(TypedProperties attribute) {
return new TypedProperties(attribute);
}
}
| 591
| 31.888889
| 104
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/AttributeListener.java
|
package org.infinispan.commons.configuration.attributes;
/**
* An AttributeListener will be invoked whenever an attribute has been modified.
*
* @author Tristan Tarrant
* @since 7.2
*/
public interface AttributeListener<T> {
void attributeChanged(Attribute<T> attribute, T oldValue);
}
| 295
| 23.666667
| 80
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/Matchable.java
|
package org.infinispan.commons.configuration.attributes;
/**
* An interface for defining non-strict equality, e.g. such as attributes being of the same type but not necessarily
* having the same value. The default behaviour delegates to {@link Object#equals(Object)}.
*
* @author Tristan Tarrant
* @since 9.2
*/
public interface Matchable<T> {
default boolean matches(T other) {
return equals(other);
}
}
| 426
| 24.117647
| 116
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/Attribute.java
|
package org.infinispan.commons.configuration.attributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.configuration.io.ConfigurationWriter;
import org.infinispan.commons.logging.Log;
/**
* Attribute. This class implements a configuration attribute value holder. A configuration attribute is defined by an
* {@link AttributeDefinition}. An attribute contains an optional value (or defers to its AttributeDefinition for the
* default value). It is possible to determine whether a value has been changed with respect to its initial value. An
* Attribute remains modifiable until it is protected. At which point it can only be modified if its AttributeDefinition
* allows it to be mutable. Additionally it is possible to register listeners when values change so that code can react
* to these changes.
*
* @author Tristan Tarrant
* @since 7.2
*/
public final class Attribute<T> implements Cloneable, Matchable<Attribute<?>>, Updatable<Attribute<T>> {
private final AttributeDefinition<T> definition;
private T value;
private boolean protect;
private boolean modified;
private List<AttributeListener<T>> listeners;
Attribute(AttributeDefinition<T> definition) {
this.definition = definition;
this.value = definition.getDefaultValue();
}
public String name() {
return definition.name();
}
public T get() {
return value;
}
public T orElse(T other) {
return modified ? value : other;
}
public T getInitialValue() {
return definition.getDefaultValue();
}
public void validate() {
definition.validate(value);
}
public Attribute<T> protect() {
if (!protect && definition.isImmutable()) {
this.protect = true;
}
return this;
}
public void set(T value) {
if (protect) {
throw Log.CONFIG.protectedAttribute(definition.name());
}
T oldValue = this.value;
this.value = value;
this.modified = true;
this.fireValueChanged(oldValue);
}
public void setImplied(T value) {
if (protect) {
throw Log.CONFIG.protectedAttribute(definition.name());
}
T oldValue = this.value;
this.value = value;
this.modified = false;
this.fireValueChanged(oldValue);
}
public void fromString(String value) {
set(definition.parse(value));
}
public T computeIfAbsent(Supplier<T> supplier) {
if (value == null)
set(supplier.get());
return value;
}
public boolean isImmutable() {
return definition.isImmutable();
}
public boolean isPersistent() {
return definition.isAutoPersist();
}
public boolean isModified() {
return modified;
}
public boolean isRepeated() {
return definition.isRepeated();
}
public void addListener(AttributeListener<T> listener) {
if (isImmutable() && isProtect()) {
throw new UnsupportedOperationException();
}
if (listeners == null) {
listeners = new ArrayList<>();
}
listeners.add(listener);
}
public void removeListener(AttributeListener<T> listener) {
if (listeners != null) {
listeners.remove(listener);
}
}
public boolean isNull() {
return value == null;
}
boolean isProtect() {
return protect;
}
public AttributeDefinition<T> getAttributeDefinition() {
return definition;
}
private void fireValueChanged(T oldValue) {
if (listeners != null) {
for (AttributeListener<T> listener : listeners) {
listener.attributeChanged(this, oldValue);
}
}
}
@SuppressWarnings("unchecked")
@Override
protected Attribute<T> clone() {
Attribute<T> clone;
try {
clone = (Attribute<T>) super.clone();
clone.modified = this.modified;
clone.listeners = null;
clone.protect = false;
return clone;
} catch (CloneNotSupportedException e) {
throw new CacheException(e);
}
}
public void read(Attribute<T> other) {
AttributeCopier<T> copier = definition.copier();
if (copier == null) {
Attribute<T> clone = other.clone();
this.value = clone.value;
} else {
this.value = copier.copyAttribute(other.value);
}
this.modified = other.modified;
}
public void merge(Attribute<T> other) {
Collection<Object> collection = (Collection<Object>) other.value;
((Collection<Object>) this.value).addAll(collection);
this.modified = !collection.isEmpty();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((definition == null) ? 0 : definition.hashCode());
result = prime * result + (modified ? 1231 : 1237);
result = prime * result + ((value == null) ? 0 : value.getClass().isArray() ? Arrays.deepHashCode((Object[]) value) : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Attribute<?> other = (Attribute<?>) obj;
if (definition == null) {
if (other.definition != null)
return false;
} else if (!definition.equals(other.definition))
return false;
if (value == null) {
return other.value == null;
} else return Objects.deepEquals(value, other.value);
}
/**
* Compares this attribute to another attribute taking into account the {@link AttributeDefinition#isGlobal()} flag.
* If the attribute is global, then this method will return true only if the values are identical. If the attribute
* is local, then this method will return true even if the values don't match. Essentially, this method only ensures
* that the attribute definitions are equals.
*
* @param other
* @return
*/
public boolean matches(Attribute<?> other) {
if (other == null)
return false;
if (!this.definition.equals(other.definition))
return false;
if (this.definition.isGlobal()) {
if (Matchable.class.isAssignableFrom(this.definition.getType())) {
return ((Matchable) value).matches(other.value);
} else {
return Objects.equals(value, other.value);
}
}
return true;
}
/**
* Updates this attribute with the value of the other attribute only if the attribute is mutable and the other has
* been modified from its default value
*
* @param other
*/
@Override
public void update(String elementName, Attribute<T> other) {
if (this.definition.equals(other.definition)) {
if (isImmutable()) {
// Ensure that there are no incompatible changes
if (definition.isGlobal() && !equals(other)) {
throw Log.CONFIG.incompatibleAttribute(definition.name(), elementName, String.valueOf(value), String.valueOf(other.value));
}
} else if (!equals(other)) {
if (other.isModified()) {
set(other.get());
} else {
setImplied(other.get());
}
Log.CONFIG.debugf("Updated attribute '%s' to value '%s'", name(), value);
}
} else {
throw new IllegalArgumentException(this + "!=" + other);
}
}
@Override
public void validateUpdate(String parentName, Attribute<T> other) {
if (this.definition.equals(other.definition)) {
if (isImmutable()) {
// Ensure that there are no incompatible changes
if (definition.isGlobal() && !Objects.equals(value, other.value)) {
throw Log.CONFIG.incompatibleAttribute(parentName, definition.name(), String.valueOf(value), String.valueOf(other.value));
}
}
} else {
throw new IllegalArgumentException(this + "!=" + other);
}
}
public void apply(Consumer<T> consumer) {
if (isModified()) {
consumer.accept(value);
}
}
@Override
public String toString() {
return definition.name() + "=" + value;
}
public void reset() {
if (protect) {
throw new IllegalStateException("Cannot reset a protected Attribute");
}
value = definition.getDefaultValue();
modified = false;
}
void write(ConfigurationWriter writer, String name) {
if (modified && value != null) {
definition.serializer().serialize(writer, name, value);
}
}
}
| 8,888
| 28.828859
| 142
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/AttributeSerializer.java
|
package org.infinispan.commons.configuration.attributes;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.infinispan.commons.configuration.io.ConfigurationWriter;
/**
* AttributeSerializer.
*
* @since 10.0
*/
public interface AttributeSerializer<T> {
AttributeSerializer<Object> DEFAULT = (writer, name, value) -> {
if (Boolean.class == value.getClass()) {
writer.writeAttribute(name, (Boolean) value);
} else {
writer.writeAttribute(name, value.toString());
}
};
AttributeSerializer<Supplier<char[]>> SECRET = (writer, name, value) -> {
if (writer.clearTextSecrets()) {
writer.writeAttribute(name, new String(value.get()));
} else {
writer.writeAttribute(name, "***");
}
};
AttributeSerializer<String[]> STRING_ARRAY = (writer, name, value) -> writer.writeAttribute(name, Arrays.asList(value));
AttributeSerializer<Collection<String>> STRING_COLLECTION = (writer, name, value) -> writer.writeAttribute(name, value);
AttributeSerializer<Collection<? extends Enum<?>>> ENUM_COLLECTION = (writer, name, value) -> writer.writeAttribute(name, value.stream().map(Enum::toString).collect(Collectors.toList()));
AttributeSerializer<Object> INSTANCE_CLASS_NAME = ((writer, name, value) -> writer.writeAttribute(name, value.getClass().getName()));
AttributeSerializer<Class> CLASS_NAME = ((writer, name, value) -> writer.writeAttribute(name, value.getName()));
void serialize(ConfigurationWriter writer, String name, T value);
}
| 1,618
| 41.605263
| 190
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/IdentityAttributeCopier.java
|
package org.infinispan.commons.configuration.attributes;
/**
* IdentityAttributeCopier. This {@link AttributeCopier} does not copy the source attribute, but
* returns it, so that the same instance can be shared across multiple configurations. Since this
* can only be safely done with threadsafe objects which store no state, be very careful when using
* it.
*
* @author Tristan Tarrant
* @since 7.2
*/
public class IdentityAttributeCopier<T> implements AttributeCopier<T> {
private static final AttributeCopier<Object> INSTANCE = new IdentityAttributeCopier<>();
public static <T> IdentityAttributeCopier<T> identityCopier() {
return (IdentityAttributeCopier<T>) INSTANCE;
}
@Override
public T copyAttribute(T attribute) {
return attribute;
}
}
| 787
| 31.833333
| 99
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/SimpleInstanceAttributeCopier.java
|
package org.infinispan.commons.configuration.attributes;
import org.infinispan.commons.util.Util;
/**
* SimpleInstanceAttributeCopier. This {@link AttributeCopier} "copies" an instance by creating a new instance. It does
* not copy any fields.
*
* @author Tristan Tarrant
* @since 7.2
*/
public class SimpleInstanceAttributeCopier<T> implements AttributeCopier<T> {
public static final AttributeCopier<Object> INSTANCE = new SimpleInstanceAttributeCopier<>();
private SimpleInstanceAttributeCopier() {
// Singleton constructor
}
@Override
public T copyAttribute(T attribute) {
if (attribute == null)
return null;
else
return (T) Util.getInstance(attribute.getClass());
}
}
| 738
| 25.392857
| 119
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/configuration/attributes/CopyConstructorAttributeCopier.java
|
package org.infinispan.commons.configuration.attributes;
import java.lang.reflect.Constructor;
import org.infinispan.commons.CacheConfigurationException;
/**
* CopyConstructorAttributeCopier. This {@link AttributeCopier} expects the attribute value class to have a copy constructor
*
* @author Tristan Tarrant
* @since 9.2
*/
public class CopyConstructorAttributeCopier<T> implements AttributeCopier<T> {
public static final AttributeCopier<Object> INSTANCE = new CopyConstructorAttributeCopier<>();
private CopyConstructorAttributeCopier() {
// Singleton constructor
}
@Override
public T copyAttribute(T attribute) {
try {
Class<T> klass = (Class<T>) attribute.getClass();
Constructor<T> constructor = klass.getConstructor(klass);
return constructor.newInstance(attribute);
} catch (Exception e) {
throw new CacheConfigurationException(e);
}
}
}
| 937
| 27.424242
| 124
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/io/ByteBufferImpl.java
|
package org.infinispan.commons.io;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
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;
import org.infinispan.commons.util.Util;
/**
* A byte buffer that exposes the internal byte array with minimal copying
*
* @author (various)
* @since 4.0
*/
public class ByteBufferImpl implements ByteBuffer {
public static final ByteBufferImpl EMPTY_INSTANCE = new ByteBufferImpl(Util.EMPTY_BYTE_ARRAY, 0, 0);
private final byte[] buf;
private final int offset;
private final int length;
public static ByteBufferImpl create(byte[] array) {
return array == null || array.length == 0 ? EMPTY_INSTANCE : new ByteBufferImpl(array, 0, array.length);
}
public static ByteBufferImpl create(byte[] array, int offset, int length) {
if (array == null || length == 0 || array.length == 0) {
return EMPTY_INSTANCE;
}
if (array.length < offset + length)
throw new IllegalArgumentException("Incorrect arguments: array.length" + array.length + ", offset=" + offset + ", length=" + length);
return new ByteBufferImpl(array, offset, length);
}
public static ByteBufferImpl create(java.nio.ByteBuffer javaBuffer) {
int remaining = javaBuffer.remaining();
if (remaining == 0) {
return EMPTY_INSTANCE;
}
return new ByteBufferImpl(javaBuffer.array(), javaBuffer.arrayOffset(), remaining);
}
public static ByteBufferImpl create(byte b) {
return new ByteBufferImpl(new byte[] {b}, 0, 1);
}
private ByteBufferImpl(byte[] buf, int offset, int length) {
this.buf = buf;
this.offset = offset;
this.length = length;
}
@Override
public byte[] getBuf() {
return buf;
}
@Override
public int getOffset() {
return offset;
}
@Override
public int getLength() {
return length;
}
@Override
public ByteBufferImpl copy() {
if (this == EMPTY_INSTANCE)
return this;
byte[] new_buf = new byte[length];
System.arraycopy(buf, offset, new_buf, 0, length);
return new ByteBufferImpl(new_buf, 0, length);
}
@Override
public String toString() {
return String.format("ByteBufferImpl{length=%d, offset=%d, bytes=%s}", length, offset, Util.hexDump(buf, offset, length));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ByteBufferImpl)) return false;
ByteBufferImpl that = (ByteBufferImpl) o;
if (length != that.length)
return false;
for (int i = 0; i < length; i++)
if (buf[offset + i] != that.buf[that.offset + i])
return false;
return true;
}
@Override
public int hashCode() {
int result = 1;
for (int i = 0; i < length; i++) {
result = 31 * result + buf[offset + i];
}
return result;
}
/**
* @return an input stream for the bytes in the buffer
*/
public InputStream getStream() {
return new ByteArrayInputStream(getBuf(), getOffset(), getLength());
}
public java.nio.ByteBuffer toJDKByteBuffer() {
return java.nio.ByteBuffer.wrap(buf, offset, length);
}
public static class Externalizer extends AbstractExternalizer<ByteBufferImpl> {
private static final long serialVersionUID = -5291318076267612501L;
@Override
public void writeObject(ObjectOutput output, ByteBufferImpl b) throws IOException {
UnsignedNumeric.writeUnsignedInt(output, b.length);
if (b.length > 0) {
output.write(b.buf, b.offset, b.length);
}
}
@Override
public ByteBufferImpl readObject(ObjectInput input) throws IOException {
int length = UnsignedNumeric.readUnsignedInt(input);
if (length == 0) { //no need to allocate new objects
return EMPTY_INSTANCE;
}
byte[] data = new byte[length];
input.readFully(data, 0, length);
return new ByteBufferImpl(data, 0, length);
}
@Override
public Integer getId() {
return Ids.BYTE_BUFFER;
}
@Override
public Set<Class<? extends ByteBufferImpl>> getTypeClasses() {
return Collections.singleton(ByteBufferImpl.class);
}
}
}
| 4,514
| 26.87037
| 142
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/io/package-info.java
|
/**
* Commons IO package
*
* @api.public
*/
package org.infinispan.commons.io;
| 83
| 11
| 34
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/io/LazyByteArrayOutputStream.java
|
package org.infinispan.commons.io;
import java.io.OutputStream;
import java.util.Arrays;
import org.infinispan.commons.util.Util;
import net.jcip.annotations.NotThreadSafe;
/**
* ByteArrayOutputStream alternative exposing the internal buffer. Using this, callers don't need to call toByteArray()
* which copies the internal buffer.
*
* <p>This class doubles the size until the internal buffer reaches a
* configurable max size (default is 4MB), after which it begins growing the buffer in 25% increments.
* This is intended to help prevent an OutOfMemoryError during a resize of a large buffer. </p>
* <p> A version of this class was originally created by Bela Ban as part of the JGroups library. </p>
* <p>This class is not threadsafe as it will not support concurrent readers and writers. <p/>
*
* @author <a href="mailto://brian.stansberry@jboss.com">Brian Stansberry</a>
* @author Dan Berindei
* @since 13.0
*/
@NotThreadSafe
public final class LazyByteArrayOutputStream extends OutputStream {
public static final int DEFAULT_SIZE = 32;
/**
* Default buffer size after which if more buffer capacity is needed the buffer will grow by 25% rather than 100%
*/
public static final int DEFAULT_DOUBLING_SIZE = 4 * 1024 * 1024; // 4MB
private byte[] buf;
private int count;
private int maxDoublingSize = DEFAULT_DOUBLING_SIZE;
public LazyByteArrayOutputStream() {
buf = null;
}
public LazyByteArrayOutputStream(int size) {
buf = new byte[size];
}
/**
* Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.
*
* @param size the initial size.
* @param maxDoublingSize the buffer size, after which if more capacity is needed the buffer will grow by 25% rather
* than 100%
* @throws IllegalArgumentException if size is negative.
*/
public LazyByteArrayOutputStream(int size, int maxDoublingSize) {
this(size);
this.maxDoublingSize = maxDoublingSize;
}
/**
* Gets the internal buffer array. Note that the length of this array will almost certainly be longer than the data
* written to it; call <code>size()</code> to get the number of bytes of actual data.
*/
public byte[] getRawBuffer() {
if (buf == null)
return Util.EMPTY_BYTE_ARRAY;
return buf;
}
/**
* Gets a buffer that is trimmed so that there are no excess bytes. If the current count does not match the
* underlying buffer than a new one is created with the written bytes.
*
* @return a byte[] that contains all the bytes written to this stream
*/
public byte[] getTrimmedBuffer() {
if (buf == null) {
return Util.EMPTY_BYTE_ARRAY;
}
if (buf.length == count) {
return buf;
}
return Arrays.copyOf(this.buf, this.count);
}
@Override
public void write(byte[] b, int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
int newcount = count + len;
ensureCapacity(newcount);
System.arraycopy(b, off, buf, count, len);
count = newcount;
}
@Override
public void write(int b) {
int newcount = count + 1;
ensureCapacity(newcount);
buf[count] = (byte) b;
count = newcount;
}
private void ensureCapacity(int newcount) {
if (buf == null) {
// Pretend we have half the default size so it's doubled
buf = new byte[Math.max(DEFAULT_SIZE, newcount)];
} else if (newcount > buf.length) {
byte[] newbuf = new byte[getNewBufferSize(buf.length, newcount)];
System.arraycopy(buf, 0, newbuf, 0, count);
buf = newbuf;
}
}
/**
* Gets the highest internal buffer size after which if more capacity is needed the buffer will grow in 25%
* increments rather than 100%.
*/
public final int getMaxDoublingSize() {
return maxDoublingSize;
}
/**
* Gets the number of bytes to which the internal buffer should be resized.
*
* @param curSize the current number of bytes
* @param minNewSize the minimum number of bytes required
* @return the size to which the internal buffer should be resized
*/
public int getNewBufferSize(int curSize, int minNewSize) {
if (curSize <= maxDoublingSize)
return Math.max(curSize << 1, minNewSize);
else
return Math.max(curSize + (curSize >> 2), minNewSize);
}
/**
* Overriden only to avoid unneeded synchronization
*/
public int size() {
return count;
}
}
| 4,766
| 31.209459
| 119
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/io/ByteBufferFactory.java
|
package org.infinispan.commons.io;
/**
* Used for building instances of {@link ByteBuffer}.
*
* @author Mircea Markus
* @since 6.0
*/
public interface ByteBufferFactory {
ByteBuffer newByteBuffer(byte[] b, int offset, int length);
ByteBuffer newByteBuffer(byte[] b);
}
| 284
| 16.8125
| 62
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/io/ExposedByteArrayOutputStream.java
|
package org.infinispan.commons.io;
import java.io.ByteArrayOutputStream;
import net.jcip.annotations.NotThreadSafe;
/**
* Extends ByteArrayOutputStream, but exposes the internal buffer. Using this, callers don't need to call toByteArray()
* which copies the internal buffer. <p> Also overrides the superclass' behavior of always doubling the size of the
* internal buffer any time more capacity is needed. This class doubles the size until the internal buffer reaches a
* configurable max size (default is 4MB), after which it begins growing the buffer in 25% increments. This is intended
* to help prevent an OutOfMemoryError during a resize of a large buffer. </p> <p> A version of this class was
* originally created by Bela Ban as part of the JGroups library. </p> This class is not threadsafe as it will not
* support concurrent readers and writers.
* <p/>
*
* @author <a href="mailto://brian.stansberry@jboss.com">Brian Stansberry</a>
* @since 4.0
* @deprecated Since 13.0, please use {@link LazyByteArrayOutputStream} instead.
*/
@NotThreadSafe
@Deprecated
public final class ExposedByteArrayOutputStream extends ByteArrayOutputStream {
/**
* Default buffer size after which if more buffer capacity is needed the buffer will grow by 25% rather than 100%
*/
public static final int DEFAULT_DOUBLING_SIZE = 4 * 1024 * 1024; // 4MB
private int maxDoublingSize = DEFAULT_DOUBLING_SIZE;
public ExposedByteArrayOutputStream() {
super();
}
public ExposedByteArrayOutputStream(int size) {
super(size);
}
/**
* Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.
*
* @param size the initial size.
* @param maxDoublingSize the buffer size, after which if more capacity is needed the buffer will grow by 25% rather
* than 100%
* @throws IllegalArgumentException if size is negative.
*/
public ExposedByteArrayOutputStream(int size, int maxDoublingSize) {
super(size);
this.maxDoublingSize = maxDoublingSize;
}
/**
* Gets the internal buffer array. Note that the length of this array will almost certainly be longer than the data
* written to it; call <code>size()</code> to get the number of bytes of actual data.
*/
public byte[] getRawBuffer() {
return buf;
}
@Override
public void write(byte[] b, int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
int newcount = count + len;
if (newcount > buf.length) {
byte newbuf[] = new byte[getNewBufferSize(buf.length, newcount)];
System.arraycopy(buf, 0, newbuf, 0, count);
buf = newbuf;
}
System.arraycopy(b, off, buf, count, len);
count = newcount;
}
@Override
public void write(int b) {
int newcount = count + 1;
if (newcount > buf.length) {
byte newbuf[] = new byte[getNewBufferSize(buf.length, newcount)];
System.arraycopy(buf, 0, newbuf, 0, count);
buf = newbuf;
}
buf[count] = (byte) b;
count = newcount;
}
/**
* Gets the highest internal buffer size after which if more capacity is needed the buffer will grow in 25%
* increments rather than 100%.
*/
public final int getMaxDoublingSize() {
return maxDoublingSize;
}
/**
* Gets the number of bytes to which the internal buffer should be resized.
*
* @param curSize the current number of bytes
* @param minNewSize the minimum number of bytes required
* @return the size to which the internal buffer should be resized
*/
public int getNewBufferSize(int curSize, int minNewSize) {
if (curSize <= maxDoublingSize)
return Math.max(curSize << 1, minNewSize);
else
return Math.max(curSize + (curSize >> 2), minNewSize);
}
/**
* Overriden only to avoid unneeded synchronization
*/
@Override
public int size() {
return count;
}
}
| 4,183
| 33.295082
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/io/StringBuilderWriter.java
|
package org.infinispan.commons.io;
import java.io.Writer;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 13.0
*/
public class StringBuilderWriter extends Writer {
private final StringBuilder builder;
public StringBuilderWriter() {
this.builder = new StringBuilder();
}
public StringBuilderWriter(final int capacity) {
this.builder = new StringBuilder(capacity);
}
public StringBuilderWriter(final StringBuilder builder) {
this.builder = builder != null ? builder : new StringBuilder();
}
public Writer append(final char value) {
this.builder.append(value);
return this;
}
public Writer append(final CharSequence value) {
this.builder.append(value);
return this;
}
public Writer append(final CharSequence value, final int start, final int end) {
this.builder.append(value, start, end);
return this;
}
public void close() {
}
public void flush() {
}
public void write(final String value) {
if (value != null) {
this.builder.append(value);
}
}
public void write(final char[] value, final int offset, final int length) {
if (value != null) {
this.builder.append(value, offset, length);
}
}
public StringBuilder getBuilder() {
return this.builder;
}
public String toString() {
return this.builder.toString();
}
}
| 1,431
| 21.030769
| 83
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/io/ByteBufferFactoryImpl.java
|
package org.infinispan.commons.io;
/**
* @author Mircea Markus
* @since 6.0
*/
public class ByteBufferFactoryImpl implements ByteBufferFactory {
@Override
public ByteBuffer newByteBuffer(byte[] b, int offset, int length) {
return ByteBufferImpl.create(b, offset, length);
}
@Override
public ByteBuffer newByteBuffer(byte[] b) {
return ByteBufferImpl.create(b);
}
}
| 401
| 20.157895
| 70
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/io/ByteBuffer.java
|
package org.infinispan.commons.io;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.infinispan.commons.util.Util;
/**
* A byte buffer that exposes the internal byte array with minimal copying. To be instantiated with {@link
* ByteBufferFactory}.
*
* @author Mircea Markus
* @since 6.0
*/
public interface ByteBuffer {
/**
* Returns the underlying buffer.
*/
byte[] getBuf();
/**
* Returns the offset within the underlying byte[] (as returned by {@link #getBuf()} owned by this buffer instance.
*/
int getOffset();
/**
* Length bytes, starting from offset, within the underlying byte[] (as returned by {@link #getBuf()} are owned by
* this buffer instance.
*/
int getLength();
/**
* Returns a new byte[] instance of size {@link #getLength()} that contains all the bytes owned by this buffer.
*/
ByteBuffer copy();
/**
* Returns a trimmed byte array.
* <p>
* The returned byte array should not be modified. A copy is not guaranteed.
* <p>
* It does not copy the byte array if {@link #getOffset()} is zero and {@link #getLength()} is equals to the
* underlying byte array length.
*
* @return A trimmed byte array.
*/
default byte[] trim() {
if (getLength() == 0) {
return Util.EMPTY_BYTE_ARRAY;
}
if (getOffset() == 0 && getBuf().length == getLength()) {
// avoid copying it
return getBuf();
}
byte[] trimBuf = new byte[getLength()];
System.arraycopy(getBuf(), getOffset(), trimBuf, 0, getLength());
return trimBuf;
}
/**
* @return An {@link InputStream} for the content of this {@link ByteBuffer}.
*/
default InputStream getStream() {
return new ByteArrayInputStream(getBuf(), getOffset(), getLength());
}
}
| 1,844
| 26.537313
| 118
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/io/UnsignedNumeric.java
|
package org.infinispan.commons.io;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Helper to read and write unsigned numerics
*
* @author Manik Surtani
* @since 4.0
*/
public class UnsignedNumeric {
/**
* Reads an int stored in variable-length format. Reads between one and five bytes. Smaller values take fewer
* bytes. Negative numbers are not supported.
*/
public static int readUnsignedInt(DataInput in) throws IOException {
byte b = in.readByte();
int i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = in.readByte();
i |= (b & 0x7FL) << shift;
}
return i;
}
public static int readUnsignedInt(InputStream in) throws IOException {
int b = in.read();
int i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = in.read();
i |= (b & 0x7FL) << shift;
}
return i;
}
public static int readUnsignedInt(java.nio.ByteBuffer in) {
int b = in.get();
int i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = in.get();
i |= (b & 0x7FL) << shift;
}
return i;
}
/**
* Writes an int in a variable-length format. Writes between one and five bytes. Smaller values take fewer bytes.
* Negative numbers are not supported.
*
* @param i int to write
*/
public static void writeUnsignedInt(DataOutput out, int i) throws IOException {
while ((i & ~0x7F) != 0) {
out.writeByte((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
out.writeByte((byte) i);
}
public static void writeUnsignedInt(OutputStream out, int i) throws IOException {
while ((i & ~0x7F) != 0) {
out.write((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
out.write((byte) i);
}
public static byte sizeUnsignedInt(int i) {
byte size = 1;
while ((i & ~0x7F) != 0) {
size += 1;
i >>>= 7;
}
return size;
}
public static void writeUnsignedInt(java.nio.ByteBuffer out, int i) {
while ((i & ~0x7F) != 0) {
out.put((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
out.put((byte) i);
}
/**
* Reads a long stored in variable-length format. Reads between one and nine bytes. Smaller values take fewer
* bytes. Negative numbers are not supported.
*/
public static long readUnsignedLong(DataInput in) throws IOException {
byte b = in.readByte();
long i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = in.readByte();
i |= (b & 0x7FL) << shift;
}
return i;
}
public static long readUnsignedLong(InputStream in) throws IOException {
int b = in.read();
long i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = in.read();
i |= (b & 0x7FL) << shift;
}
return i;
}
public static long readUnsignedLong(java.nio.ByteBuffer in) {
int b = in.get();
long i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = in.get();
i |= (b & 0x7FL) << shift;
}
return i;
}
/**
* Writes a long in a variable-length format. Writes between one and nine bytes. Smaller values take fewer bytes.
* Negative numbers are not supported.
*
* @param i int to write
*/
public static void writeUnsignedLong(DataOutput out, long i) throws IOException {
while ((i & ~0x7F) != 0) {
out.writeByte((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
out.writeByte((byte) i);
}
public static void writeUnsignedLong(OutputStream out, long i) throws IOException {
while ((i & ~0x7F) != 0) {
out.write((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
out.write((byte) i);
}
public static void writeUnsignedLong(java.nio.ByteBuffer out, long i) {
while ((i & ~0x7F) != 0) {
out.put((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
out.put((byte) i);
}
/**
* Reads an int stored in variable-length format. Reads between one and five bytes. Smaller values take fewer
* bytes. Negative numbers are not supported.
*/
public static int readUnsignedInt(byte[] bytes, int offset) {
byte b = bytes[offset++];
int i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = bytes[offset++];
i |= (b & 0x7FL) << shift;
}
return i;
}
/**
* Writes an int in a variable-length format. Writes between one and five bytes. Smaller values take fewer bytes.
* Negative numbers are not supported.
*
* @param i int to write
*/
public static int writeUnsignedInt(byte[] bytes, int offset, int i) {
int localOffset = offset;
while ((i & ~0x7F) != 0) {
bytes[localOffset++] = (byte) ((i & 0x7f) | 0x80);
i >>>= 7;
}
bytes[localOffset++] = (byte) i;
return localOffset - offset;
}
/**
* Reads an int stored in variable-length format. Reads between one and nine bytes. Smaller values take fewer
* bytes. Negative numbers are not supported.
*/
public static long readUnsignedLong(byte[] bytes, int offset) {
byte b = bytes[offset++];
long i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = bytes[offset++];
i |= (b & 0x7FL) << shift;
}
return i;
}
/**
* Writes an int in a variable-length format. Writes between one and nine bytes. Smaller values take fewer bytes.
* Negative numbers are not supported.
*
* @param i int to write
*/
public static void writeUnsignedLong(byte[] bytes, int offset, long i) {
while ((i & ~0x7F) != 0) {
bytes[offset++] = (byte) ((i & 0x7f) | 0x80);
i >>>= 7;
}
bytes[offset] = (byte) i;
}
}
| 6,075
| 27.660377
| 118
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/io/SignedNumeric.java
|
package org.infinispan.commons.io;
import static org.infinispan.commons.io.UnsignedNumeric.readUnsignedInt;
import static org.infinispan.commons.io.UnsignedNumeric.writeUnsignedInt;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.OutputStream;
/**
* Variable length encoding for signed numbers, using the ZigZag technique
* @see <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">
* https://developers.google.com/protocol-buffers/docs/encoding#types</a>
*
* @author gustavonalle
* @since 8.0
*/
public final class SignedNumeric {
private SignedNumeric() {
}
public static int readSignedInt(ObjectInput in) throws IOException {
return decode(readUnsignedInt(in));
}
public static int readSignedInt(InputStream in) throws IOException {
return decode(readUnsignedInt(in));
}
public static void writeSignedInt(ObjectOutput out, int i) throws IOException {
writeUnsignedInt(out, encode(i));
}
public static void writeSignedInt(OutputStream out, int i) throws IOException {
writeUnsignedInt(out, encode(i));
}
public static int decode(int vint) {
return (vint & 1) == 0 ? vint >>> 1 : ~(vint >>> 1);
}
public static int encode(int vint) {
return (vint << 1) ^ (vint >> 31);
}
}
| 1,377
| 26.56
| 85
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/reactive/RxJavaInterop.java
|
package org.infinispan.commons.reactive;
import java.util.Map;
import org.infinispan.commons.util.Util;
import org.reactivestreams.Publisher;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
/**
* Static factory class that provides methods to obtain commonly used instances for interoperation between RxJava
* and standard JRE.
* @author wburns
* @since 10.0
*/
public class RxJavaInterop {
protected RxJavaInterop() { }
/**
* Provides a {@link Function} that can be used to convert from an instance of {@link java.util.Map.Entry} to
* the key of the entry. This is useful for the instance passed to a method like {@link Flowable#map(Function)}.
*
* @param <K> key type
* @param <V> value type
* @return rxjava function to convert from a Map.Entry to its key.
*/
public static <K, V> Function<Map.Entry<K, V>, K> entryToKeyFunction() {
return (Function) entryToKeyFunction;
}
/**
* Provides a {@link Function} that can be used to convert from an instance of {@link java.util.Map.Entry} to
* the value of the entry. This is useful for the instance passed to a method like {@link Flowable#map(Function)}.
*
* @param <K> key type
* @param <V> value type
* @return rxjava function to convert from a Map.Entry to its value.
*/
public static <K, V> Function<Map.Entry<K, V>, V> entryToValueFunction() {
return (Function) entryToValueFunction;
}
public static <R> Function<? super Throwable, Publisher<R>> cacheExceptionWrapper() {
return (Function) wrapThrowable;
}
public static <R> Function<R, R> identityFunction() {
return (Function) identityFunction;
}
public static <R> Consumer<R> emptyConsumer() {
return (Consumer) emptyConsumer;
}
private static final Function<Object, Object> identityFunction = i -> i;
private static final Consumer<Object> emptyConsumer = ignore -> { };
private static final Function<Map.Entry<Object, Object>, Object> entryToKeyFunction = Map.Entry::getKey;
private static final Function<Map.Entry<Object, Object>, Object> entryToValueFunction = Map.Entry::getValue;
private static final Function<? super Throwable, Publisher<?>> wrapThrowable = t -> Flowable.error(Util.rewrapAsCacheException(t));
}
| 2,370
| 36.634921
| 134
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/reactive/AbstractAsyncPublisherHandler.java
|
package org.infinispan.commons.reactive;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import io.reactivex.rxjava3.functions.Action;
import io.reactivex.rxjava3.functions.LongConsumer;
import io.reactivex.rxjava3.processors.FlowableProcessor;
import io.reactivex.rxjava3.processors.UnicastProcessor;
/**
* Abstract handler that handles request and cancellation of a given non blocking resource.
* When additional entries are requested via {@link org.reactivestreams.Subscription#request(long)} the handler will keep
* track of the outstanding count and invoke either {@link #sendInitialCommand(Object, int)} or
* {@link #sendNextCommand(Object, int)} depending upon if it is the first request or subsequent.
* This handler guarantees that there is only one outstanding request and that if the request amount is larger than the
* batch, it will continue to send new commands one at a time until the request amount has been satisfied.
* <p>
* The handler processes each target via the provided {@link Supplier} one by one, exhausting all values from the
* target, until there are no more targets left or the publishing has been cancelled by the subscriber.
* <p>
* When a command returns successfully either the {@link #handleInitialResponse(Object, Object)} or
* {@link #handleNextResponse(Object, Object)} will be invoked with the response object. The returned entries can then
* be emitted by invoking the {@link #onNext(Object)} method for each value. Note that the return of {@code onNext}
* should be checked in case if the {@code Subscriber} has cancelled the publishing of values in the middle.
* <p>
* A command may also encounter a Throwable and it is possible to customize what happens by implementing the
* {@link #handleThrowableInResponse(Throwable, Object)} method. For example you may want to skip the given
* <p>
* Each request is provided a {@code batchSize} argument and the underlying resource should adhere to this,
* failure to do so may cause an {@link OutOfMemoryError}, since entries are only emitted to the Subscriber based on the
* requested amount, and any additional are enqueued.
* <p>
* This handler also supports {@link Subscription#cancel()} by extending the {@link #sendCancel(Object)} command and
* the underlying service must be cancelled in an asynchronous and non blocking fashion. Once cancelled this Publisher
* will not publish additional values or requests.
* <p>
* Note this handler only supports a single Subscriber for the returned Publisher from {@link #startPublisher()}. Failure
* to do so can cause multiple requests and unexpected problems.
*/
public abstract class AbstractAsyncPublisherHandler<Target, Output, InitialResponse, NextResponse> implements LongConsumer, Action {
protected final static Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
protected final int batchSize;
protected final Supplier<Target> supplier;
private final FlowableProcessor<Output> flowableProcessor;
private final AtomicLong requestedAmount = new AtomicLong();
// The current address and segments we are processing or null if another one should be acquired
private volatile Target currentTarget;
// whether this subscription was cancelled by a caller (means we can stop processing)
private volatile boolean cancelled;
// whether the initial request was already sent or not (if so then a next command is used)
private volatile boolean alreadyCreated;
private volatile boolean started = false;
private final InitialBiConsumer initialBiConsumer = new InitialBiConsumer();
private final NextBiConsumer nextBiConsumer = new NextBiConsumer();
protected AbstractAsyncPublisherHandler(int batchSize, Supplier<Target> supplier, Target firstTarget) {
this.batchSize = batchSize;
this.supplier = supplier;
this.flowableProcessor = UnicastProcessor.create(batchSize);
this.currentTarget = firstTarget;
}
public Publisher<Output> startPublisher() {
if (!started) {
started = true;
} else {
throw new IllegalStateException("Publisher was already started!");
}
return flowableProcessor.doOnLifecycle(RxJavaInterop.emptyConsumer(), this, this);
}
/**
* This is invoked when the Subscription is cancelled
*/
@Override
public void run() {
cancelled = true;
if (alreadyCreated) {
Target target = currentTarget;
if (target != null) {
sendCancel(target);
}
}
}
protected abstract void sendCancel(Target target);
protected abstract CompletionStage<InitialResponse> sendInitialCommand(Target target, int batchSize);
protected abstract CompletionStage<NextResponse> sendNextCommand(Target target, int batchSize);
protected abstract long handleInitialResponse(InitialResponse response, Target target);
protected abstract long handleNextResponse(NextResponse response, Target target);
/**
* Allows any implementor to handle what happens when a Throwable is encountered. By default the returned publisher
* invokes {@link org.reactivestreams.Subscriber#onError(Throwable)} and stops processing. It is possible to
* ignore the throwable and continue processing by invoking {@link #accept(long)} with a value of 0. It may also
* be required to reset the {@link #currentTarget} so it is initialized to the next supplied value.
* @param t throwable that was encountered
* @param target the target which was invoked that caused the throwable
*/
protected void handleThrowableInResponse(Throwable t, Target target) {
flowableProcessor.onError(t);
}
/**
* This method is invoked every time a new request is sent to the underlying publisher. We need to submit a request
* if there is not a pending one. Whenever requestedAmount is a number greater than 0, that means we must submit or
* there is a pending one.
* @param count request count
*/
@Override
public void accept(long count) {
if (shouldSubmit(count)) {
if (checkCancelled()) {
return;
}
// Find which address and segments we still need to retrieve - when the supplier returns null that means
// we don't need to do anything else (normal termination state)
Target target = currentTarget;
if (target == null) {
alreadyCreated = false;
target = supplier.get();
if (target == null) {
if (log.isTraceEnabled()) {
log.tracef("Completing processor %s", flowableProcessor);
}
flowableProcessor.onComplete();
return;
} else {
currentTarget = target;
}
}
try {
if (alreadyCreated) {
CompletionStage<NextResponse> stage = sendNextCommand(target, batchSize);
stage.whenComplete(nextBiConsumer);
} else {
alreadyCreated = true;
CompletionStage<InitialResponse> stage = sendInitialCommand(target, batchSize);
stage.whenComplete(initialBiConsumer);
}
} catch (Throwable t) {
handleThrowableInResponse(t, target);
}
}
}
private class InitialBiConsumer extends ResponseConsumer<InitialResponse> {
@Override
long handleResponse(InitialResponse response, Target target) {
return handleInitialResponse(response, target);
}
}
private class NextBiConsumer extends ResponseConsumer<NextResponse> {
@Override
long handleResponse(NextResponse response, Target target) {
return handleNextResponse(response, target);
}
}
private abstract class ResponseConsumer<Type> implements BiConsumer<Type, Throwable> {
@Override
public void accept(Type response, Throwable throwable) {
if (throwable != null) {
handleThrowableInResponse(throwable, currentTarget);
return;
}
try {
long produced = handleResponse(response, currentTarget);
AbstractAsyncPublisherHandler.this.accept(-produced);
} catch (Throwable innerT) {
handleThrowableInResponse(innerT, currentTarget);
}
}
abstract long handleResponse(Type response, Target target);
}
/**
* Method that should be called for each emitted output value. The returned boolean is whether the handler should
* continue publishing values or not.
* @param value value emit to the publisher
* @return whether to continue emitting values
*/
protected boolean onNext(Output value) {
if (checkCancelled()) {
return false;
}
flowableProcessor.onNext(value);
return true;
}
/**
* Method to invoke when a given target is found to have been completed and the next target should be used
*/
protected void targetComplete() {
// Setting to null will force the next invocation of accept to retrieve the next target if available
currentTarget = null;
}
private boolean shouldSubmit(long count) {
while (true) {
long prev = requestedAmount.get();
long newValue = prev + count;
if (requestedAmount.compareAndSet(prev, newValue)) {
// This ensures that only a single submission can be done at one time
// It will only submit if there were none prior (prev <= 0) or if it is the current one (count <= 0).
return newValue > 0 && (prev <= 0 || count <= 0);
}
}
}
/**
* This method returns whether this subscription has been cancelled
*/
// This method doesn't have to be protected by requestors, but there is no reason for a method who doesn't have
// the requestors "lock" to invoke this
protected boolean checkCancelled() {
if (cancelled) {
if (log.isTraceEnabled()) {
log.tracef("Subscription %s was cancelled, terminating early", this);
}
return true;
}
return false;
}
}
| 10,465
| 40.864
| 132
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/api/package-info.java
|
/**
* Commons API package
*
* @api.public
*/
package org.infinispan.commons.api;
| 85
| 11.285714
| 35
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/api/BasicCache.java
|
package org.infinispan.commons.api;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* BasicCache provides the common building block for the two different types of caches that Infinispan provides:
* embedded and remote.
* <p/>
* For convenience, BasicCache extends {@link ConcurrentMap} and implements all methods accordingly, although methods like
* {@link ConcurrentMap#keySet()}, {@link ConcurrentMap#values()} and {@link ConcurrentMap#entrySet()} are expensive
* (prohibitively so when using a distributed cache) and frequent use of these methods is not recommended.
* <p />
* Other methods such as {@link #size()} provide an approximation-only, and should not be relied on for an accurate picture
* as to the size of the entire, distributed cache. Remote nodes are <i>not</i> queried and in-fly transactions are not
* taken into account, even if {@link #size()} is invoked from within such a transaction.
* <p/>
* Also, like many {@link ConcurrentMap} implementations, BasicCache does not support the use of <tt>null</tt> keys or
* values.
* <p/>
* <h3>Unsupported operations</h3>
* <p>{@link #containsValue(Object)}</p>
*
* Please see the <a href="http://www.jboss.org/infinispan/docs">Infinispan documentation</a> and/or the <a
* href="https://docs.jboss.org/author/display/ISPN/Getting+Started+Guide#GettingStartedGuide-5minutetutorial">5 Minute Usage Tutorial</a> for more details.
* <p/>
*
* @author Mircea.Markus@jboss.com
* @author Manik Surtani
* @author Galder Zamarreño
* @author Tristan Tarrant
*
* @see <a href="http://www.jboss.org/infinispan/docs">Infinispan documentation</a>
* @see <a href="http://www.jboss.org/community/wiki/5minutetutorialonInfinispan">5 Minute Usage Tutorial</a>
*
* @since 5.1
*/
public interface BasicCache<K, V> extends AsyncCache<K, V>, ConcurrentMap<K, V>, Lifecycle {
/**
* Retrieves the name of the cache
*
* @return the name of the cache
*/
String getName();
/**
* Retrieves the version of Infinispan
*
* @return a version string
*/
String getVersion();
/**
* {@inheritDoc}
*
* If the return value of this operation will be ignored by the application,
* the user is strongly encouraged to use the {@link org.infinispan.context.Flag#IGNORE_RETURN_VALUES}
* flag when invoking this method in order to make it behave as efficiently
* as possible (i.e. avoiding needless remote or network calls).
*/
@Override
V put(K key, V value);
/**
* An overloaded form of {@link #put(Object, Object)}, which takes in lifespan parameters.
*
* @param key key to use
* @param value value to store
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param unit unit of measurement for the lifespan
* @return the value being replaced, or null if nothing is being replaced.
*/
V put(K key, V value, long lifespan, TimeUnit unit);
/**
* An overloaded form of {@link #putIfAbsent(Object, Object)}, which takes in lifespan parameters.
*
* @param key key to use
* @param value value to store
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param unit unit of measurement for the lifespan
* @return the value being replaced, or null if nothing is being replaced.
*/
V putIfAbsent(K key, V value, long lifespan, TimeUnit unit);
/**
* An overloaded form of {@link #putAll(Map)}, which takes in lifespan parameters. Note that the lifespan is applied
* to all mappings in the map passed in.
*
* @param map map containing mappings to enter
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param unit unit of measurement for the lifespan
*/
void putAll(Map<? extends K, ? extends V> map, long lifespan, TimeUnit unit);
/**
* An overloaded form of {@link #replace(Object, Object)}, which takes in lifespan parameters.
*
* @param key key to use
* @param value value to store
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param unit unit of measurement for the lifespan
* @return the value being replaced, or null if nothing is being replaced.
*/
V replace(K key, V value, long lifespan, TimeUnit unit);
/**
* An overloaded form of {@link #replace(Object, Object, Object)}, which takes in lifespan parameters.
*
* @param key key to use
* @param oldValue value to replace
* @param value value to store
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param unit unit of measurement for the lifespan
* @return true if the value was replaced, false otherwise
*/
boolean replace(K key, V oldValue, V value, long lifespan, TimeUnit unit);
/**
* An overloaded form of {@link #put(Object, Object)}, which takes in lifespan parameters.
*
* @param key key to use
* @param value value to store
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @param maxIdleTime the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleTimeUnit time unit for max idle time
* @return the value being replaced, or null if nothing is being replaced.
*/
V put(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit);
/**
* An overloaded form of {@link #putIfAbsent(Object, Object)}, which takes in lifespan parameters.
*
* @param key key to use
* @param value value to store
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @param maxIdleTime the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleTimeUnit time unit for max idle time
* @return the value being replaced, or null if nothing is being replaced.
*/
V putIfAbsent(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit);
/**
* An overloaded form of {@link #putAll(Map)}, which takes in lifespan parameters. Note that the lifespan is applied
* to all mappings in the map passed in.
*
* @param map map containing mappings to enter
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @param maxIdleTime the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleTimeUnit time unit for max idle time
*/
void putAll(Map<? extends K, ? extends V> map, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit);
/**
* An overloaded form of {@link #replace(Object, Object)}, which takes in lifespan parameters.
*
* @param key key to use
* @param value value to store
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @param maxIdleTime the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleTimeUnit time unit for max idle time
* @return the value being replaced, or null if nothing is being replaced.
*/
V replace(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit);
/**
* An overloaded form of {@link #replace(Object, Object, Object)}, which takes in lifespan parameters.
*
* @param key key to use
* @param oldValue value to replace
* @param value value to store
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @param maxIdleTime the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleTimeUnit time unit for max idle time
* @return true if the value was replaced, false otherwise
*/
boolean replace(K key, V oldValue, V value, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit);
/**
* An overloaded form of {@link #merge(Object, Object, BiFunction)} which takes in lifespan parameters.
*
* @param key key to use
* @param value new value to merge with existing value
* @param remappingFunction function to use to merge new and existing values into a merged value to store under key
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @return the merged value that was stored under key
*/
V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit);
/**
* An overloaded form of {@link #merge(Object, Object, BiFunction)} which takes in lifespan parameters.
*
* @param key key to use
* @param value new value to merge with existing value
* @param remappingFunction function to use to merge new and existing values into a merged value to store under key
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @param maxIdleTime the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleTimeUnit time unit for max idle time
* @return the merged value that was stored under key
*/
V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit);
/**
* An overloaded form of {@link #compute(Object, BiFunction)} which takes in lifespan parameters.
*
* @param key key to use
* @param remappingFunction function to use to compute and store the value under key
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @return the computed value that was stored under key
*/
V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit);
/**
* An overloaded form of {@link #compute(Object, BiFunction)} which takes in lifespan and maxIdleTime parameters.
*
* @param key key to use
* @param remappingFunction function to use to compute and store the value under key
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @param maxIdleTime the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleTimeUnit time unit for max idle time
* @return the computed value that was stored under key
*/
V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit);
/**
* An overloaded form of {@link #computeIfPresent(Object, BiFunction)} which takes in lifespan parameters.
*
* @param key key to use
* @param remappingFunction function to use to compute and store the value under key, if such exists
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @return the computed value that was stored under key
*/
V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit);
/**
* An overloaded form of {@link #computeIfPresent(Object, BiFunction)} which takes in lifespan and maxIdleTime parameters.
*
* @param key key to use
* @param remappingFunction function to use to compute and store the value under key, if such exists
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @param maxIdleTime the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleTimeUnit time unit for max idle time
* @return the computed value that was stored under key
*/
V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit);
/**
* An overloaded form of {@link #computeIfAbsent(Object, Function)} which takes in lifespan parameters.
*
* @param key key to use
* @param mappingFunction function to use to compute and store the value under key, if the key is absent
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @return the computed value that was stored under key
*/
V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit);
/**
* An overloaded form of {@link #computeIfAbsent(Object, Function)} which takes in lifespan and maxIdleTime parameters.
*
* @param key key to use
* @param mappingFunction function to use to compute and store the value under key, if the key is absent
* @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan.
* @param lifespanUnit time unit for lifespan
* @param maxIdleTime the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleTimeUnit time unit for max idle time
* @return the computed value that was stored under key
*/
V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit);
/**
* {@inheritDoc}
*
* If the return value of this operation will be ignored by the application,
* the user is strongly encouraged to use the {@link org.infinispan.context.Flag#IGNORE_RETURN_VALUES}
* flag when invoking this method in order to make it behave as efficiently
* as possible (i.e. avoiding needless remote or network calls).
*/
@Override
V remove(Object key);
}
| 15,659
| 50.344262
| 176
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/api/AsyncCache.java
|
package org.infinispan.commons.api;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* AsyncCache. This interface is implemented by caches which support asynchronous variants of the various
* put/get/remove/clear/replace/putAll methods
*
* Note that these methods only really make sense if you are using a clustered cache. I.e., when used in LOCAL mode,
* these "async" operations offer no benefit whatsoever. These methods, such as {@link #putAsync(Object, Object)}
* offer the best of both worlds between a fully synchronous and a fully asynchronous cache in that a
* {@link CompletableFuture} is returned. The <tt>CompletableFuture</tt> can then be ignored or thrown away for typical
* asynchronous behaviour, or queried for synchronous behaviour, which would block until any remote calls complete.
* Note that all remote calls are, as far as the transport is concerned, synchronous. This allows you the guarantees
* that remote calls succeed, while not blocking your application thread unnecessarily. For example, usage such as
* the following could benefit from the async operations:
* <pre>
* CompletableFuture f1 = cache.putAsync("key1", "value1");
* CompletableFuture f2 = cache.putAsync("key2", "value2");
* CompletableFuture f3 = cache.putAsync("key3", "value3");
* f1.get();
* f2.get();
* f3.get();
* </pre>
* The net result is behavior similar to synchronous RPC calls in that at the end, you have guarantees that all calls
* completed successfully, but you have the added benefit that the three calls could happen in parallel. This is
* especially advantageous if the cache uses distribution and the three keys map to different cache instances in the
* cluster.
* <p/>
* Also, the use of async operations when within a transaction return your local value only, as expected. A
* {@link CompletableFuture} is still returned though for API consistency.
*
* These methods can have benefit over their sync versions even in LOCAL mode.
*
* <p/>
*
* @author Mircea Markus
* @author Manik Surtani
* @author Galder Zamarreño
* @author Tristan Tarrant
* @since 6.0
*/
public interface AsyncCache<K, V> {
/**
* Asynchronous version of {@link BasicCache#put(Object, Object)}. This method does not block on remote calls, even if your
* cache mode is synchronous.
*
* @param key key to use
* @param value value to store
* @return a future containing the old value replaced.
*/
CompletableFuture<V> putAsync(K key, V value);
/**
* Asynchronous version of {@link BasicCache#put(Object, Object, long, TimeUnit)} . This method does not block on remote
* calls, even if your cache mode is synchronous.
*
* @param key key to use
* @param value value to store
* @param lifespan lifespan of entry
* @param unit time unit for lifespan
* @return a future containing the old value replaced
*/
CompletableFuture<V> putAsync(K key, V value, long lifespan, TimeUnit unit);
/**
* Asynchronous version of {@link BasicCache#put(Object, Object, long, TimeUnit, long, TimeUnit)}. This method does not block
* on remote calls, even if your cache mode is synchronous.
*
* @param key key to use
* @param value value to store
* @param lifespan lifespan of entry
* @param lifespanUnit time unit for lifespan
* @param maxIdle the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleUnit time unit for max idle time
* @return a future containing the old value replaced
*/
CompletableFuture<V> putAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit);
/**
* Asynchronous version of {@link BasicCache#putAll(Map)}. This method does not block on remote calls, even if your cache mode
* is synchronous.
*
* @param data to store
* @return a future containing a void return type
*/
CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data);
/**
* Asynchronous version of {@link BasicCache#putAll(Map, long, TimeUnit)}. This method does not block on remote calls, even if
* your cache mode is synchronous.
*
* @param data to store
* @param lifespan lifespan of entry
* @param unit time unit for lifespan
* @return a future containing a void return type
*/
CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data, long lifespan, TimeUnit unit);
/**
* Asynchronous version of {@link BasicCache#putAll(Map, long, TimeUnit, long, TimeUnit)}. This method does not block on
* remote calls, even if your cache mode is synchronous.
*
* @param data to store
* @param lifespan lifespan of entry
* @param lifespanUnit time unit for lifespan
* @param maxIdle the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleUnit time unit for max idle time
* @return a future containing a void return type
*/
CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> data, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit);
/**
* Asynchronous version of {@link BasicCache#clear()}. This method does not block on remote calls, even if your cache mode is
* synchronous.
*
* @return a future containing a void return type
*/
CompletableFuture<Void> clearAsync();
/**
* Asynchronous version of {@link BasicCache#size()}. This method does not block on remote calls, even if your cache mode is
* synchronous.
*
* @return a future containing the count of the cache
*/
CompletableFuture<Long> sizeAsync();
/**
* Asynchronous version of {@link BasicCache#putIfAbsent(Object, Object)}. This method does not block on remote calls, even if
* your cache mode is synchronous.
*
* @param key key to use
* @param value value to store
* @return a future containing the old value replaced.
*/
CompletableFuture<V> putIfAbsentAsync(K key, V value);
/**
* Asynchronous version of {@link BasicCache#putIfAbsent(Object, Object, long, TimeUnit)} . This method does not block on
* remote calls, even if your cache mode is synchronous.
*
* @param key key to use
* @param value value to store
* @param lifespan lifespan of entry
* @param unit time unit for lifespan
* @return a future containing the old value replaced
*/
CompletableFuture<V> putIfAbsentAsync(K key, V value, long lifespan, TimeUnit unit);
/**
* Asynchronous version of {@link BasicCache#putIfAbsent(Object, Object, long, TimeUnit, long, TimeUnit)}. This method does
* not block on remote calls, even if your cache mode is synchronous.
*
* @param key key to use
* @param value value to store
* @param lifespan lifespan of entry
* @param lifespanUnit time unit for lifespan
* @param maxIdle the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleUnit time unit for max idle time
* @return a future containing the old value replaced
*/
CompletableFuture<V> putIfAbsentAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit);
/**
* Asynchronous version of {@link BasicCache#remove(Object)}. This method does not block on remote calls, even if your cache
* mode is synchronous.
*
* @param key key to remove
* @return a future containing the value removed
*/
CompletableFuture<V> removeAsync(Object key);
/**
* Asynchronous version of {@link BasicCache#remove(Object, Object)}. This method does not block on remote calls, even if your
* cache mode is synchronous.
*
* @param key key to remove
* @param value value to match on
* @return a future containing a boolean, indicating whether the entry was removed or not
*/
CompletableFuture<Boolean> removeAsync(Object key, Object value);
/**
* Asynchronous version of {@link BasicCache#replace(Object, Object)}. This method does not block on remote calls, even if
* your cache mode is synchronous.
*
* @param key key to remove
* @param value value to store
* @return a future containing the previous value overwritten
*/
CompletableFuture<V> replaceAsync(K key, V value);
/**
* Asynchronous version of {@link BasicCache#replace(Object, Object, long, TimeUnit)}. This method does not block on remote
* calls, even if your cache mode is synchronous.
*
* @param key key to remove
* @param value value to store
* @param lifespan lifespan of entry
* @param unit time unit for lifespan
* @return a future containing the previous value overwritten
*/
CompletableFuture<V> replaceAsync(K key, V value, long lifespan, TimeUnit unit);
/**
* Asynchronous version of {@link BasicCache#replace(Object, Object, long, TimeUnit, long, TimeUnit)}. This method does not
* block on remote calls, even if your cache mode is synchronous.
*
* @param key key to remove
* @param value value to store
* @param lifespan lifespan of entry
* @param lifespanUnit time unit for lifespan
* @param maxIdle the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleUnit time unit for max idle time
* @return a future containing the previous value overwritten
*/
CompletableFuture<V> replaceAsync(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit);
/**
* Asynchronous version of {@link BasicCache#replace(Object, Object, Object)}. This method does not block on remote calls,
* even if your cache mode is synchronous.
*
* @param key key to remove
* @param oldValue value to overwrite
* @param newValue value to store
* @return a future containing a boolean, indicating whether the entry was replaced or not
*/
CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue);
/**
* Asynchronous version of {@link BasicCache#replace(Object, Object, Object, long, TimeUnit)}. This method does not block on
* remote calls, even if your cache mode is synchronous.
*
* @param key key to remove
* @param oldValue value to overwrite
* @param newValue value to store
* @param lifespan lifespan of entry
* @param unit time unit for lifespan
* @return a future containing a boolean, indicating whether the entry was replaced or not
*/
CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue, long lifespan, TimeUnit unit);
/**
* Asynchronous version of {@link BasicCache#replace(Object, Object, Object, long, TimeUnit, long, TimeUnit)}. This method
* does not block on remote calls, even if your cache mode is synchronous.
*
* @param key key to remove
* @param oldValue value to overwrite
* @param newValue value to store
* @param lifespan lifespan of entry
* @param lifespanUnit time unit for lifespan
* @param maxIdle the maximum amount of time this key is allowed to be idle for before it is considered as
* expired
* @param maxIdleUnit time unit for max idle time
* @return a future containing a boolean, indicating whether the entry was replaced or not
*/
CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit);
/**
* Asynchronous version of {@link BasicCache#get(Object)} that allows user code to
* retrieve the value associated with a key at a later stage, hence allowing
* multiple parallel get requests to be sent. Normally, when this method
* detects that the value is likely to be retrieved from from a remote
* entity, it will span a different thread in order to allow the
* asynchronous get call to return immediately. If the call will definitely
* resolve locally, for example when the cache is configured with LOCAL mode
* and no stores are configured, the get asynchronous call will act
* sequentially and will have no different to {@link BasicCache#get(Object)}.
*
* @param key key to retrieve
* @return a future that can be used to retrieve value associated with the
* key when this is available. The actual value returned by the future
* follows the same rules as {@link BasicCache#get(Object)}
*/
CompletableFuture<V> getAsync(K key);
/**
* Asynchronous version of {@link BasicCache#containsKey(Object)}
* @param key key to retrieve
* @return future containing true if the mapping exists.
*
* @since 9.2
*/
default CompletableFuture<Boolean> containsKeyAsync(K key) {
return getAsync(key).thenApply(Objects::nonNull);
}
/**
* TODO This should be in AdvancedCache with getAll
*
* @since 9.2
*/
default CompletableFuture<Map<K, V>> getAllAsync(Set<?> keys) {
Object[] orderedKeys = new Object[keys.size()];
CompletableFuture[] futures = new CompletableFuture[keys.size()];
int i = 0;
for (Object key : keys) {
orderedKeys[i] = key;
futures[i] = getAsync((K) key);
++i;
}
return CompletableFuture.allOf(futures).thenApply(nil -> {
Map<K, V> map = new HashMap<>(futures.length);
for (int j = 0; j < futures.length; ++j) {
V value = (V) futures[j].join();
if (value != null) map.put((K) orderedKeys[j], value);
}
return map;
});
}
/**
* Asynchronous version of {@link BasicCache#compute(Object, BiFunction)}. This method does not block on remote
* calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction);
/**
* Asynchronous version of {@link BasicCache#compute(Object, BiFunction, long, TimeUnit)}. This method does not block on remote
* calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit);
/**
* Asynchronous version of {@link BasicCache#compute(Object, BiFunction, long, TimeUnit, long, TimeUnit)}. This method does not block on remote
* calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit);
/**
* Asynchronous version of {@link BasicCache#computeIfAbsent(Object, Function)}. This method does not block on remote
* calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction);
/**
* Asynchronous version of {@link BasicCache#computeIfAbsent(Object, Function, long, TimeUnit)}. This method does not block on remote
* calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit);
/**
* Asynchronous version of {@link BasicCache#computeIfAbsent(Object, Function, long, TimeUnit, long, TimeUnit)}. This method does not block on remote
* calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit);
/**
* Asynchronous version of {@link BasicCache#computeIfPresent(Object, BiFunction)}. This method does not block on
* remote calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction);
/**
* Asynchronous version of {@link BasicCache#computeIfPresent(Object, BiFunction, long, TimeUnit)} . This method does not block on
* remote calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit);
/**
* Asynchronous version of {@link BasicCache#computeIfPresent(Object, BiFunction, long, TimeUnit, long, TimeUnit)} . This method does not block on
* remote calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit);
/**
* Asynchronous version of {@link BasicCache#merge(Object, Object, BiFunction)}. This method does not block on remote
* calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction);
/**
* Asynchronous version of {@link BasicCache#merge(Object, Object, BiFunction, long, TimeUnit)}. This method does not
* block on remote calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit);
/**
* Asynchronous version of {@link BasicCache#merge(Object, Object, BiFunction, long, TimeUnit, long, TimeUnit)}. This
* method does not block on remote calls, even if your cache mode is synchronous.
*
* @since 9.4
*/
CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit);
}
| 18,706
| 43.224586
| 192
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/api/TransactionalCache.java
|
package org.infinispan.commons.api;
import jakarta.transaction.TransactionManager;
/**
* This interface is implemented by caches that support (i.e. can interact with) transactions.
*
* @author Pedro Ruivo
* @since 9.3
*/
public interface TransactionalCache {
/**
* @return the {@link TransactionManager} in use by this cache or {@code null} if the cache isn't transactional.
*/
default TransactionManager getTransactionManager() {
return null;
}
}
| 480
| 21.904762
| 115
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/api/CacheContainerAdmin.java
|
package org.infinispan.commons.api;
import java.util.EnumSet;
import org.infinispan.commons.configuration.BasicConfiguration;
/**
* Administrative cache container operations.
*
* @author Tristan Tarrant
* @since 9.2
*/
public interface CacheContainerAdmin<C extends CacheContainerAdmin, A extends BasicConfiguration> {
/**
* Flags which affect only administrative operations
*
* @author Tristan Tarrant
* @since 9.2
*/
enum AdminFlag {
/**
* If the operation affects configuration, make it permanent, which means it will survive restarts.
* If the server cannot honor this flag an error will be returned
* @deprecated configurations are now always permanent by default. Use the {@link #VOLATILE} flag to obtain the opposite behaviour.
*/
@Deprecated
PERMANENT,
/**
* Configuration changes will not be persisted to the global state.
*/
VOLATILE,
/**
* If a configuration already exists, and is compatible with the supplied configuration, update it.
*/
UPDATE;
private static final AdminFlag[] CACHED_VALUES = AdminFlag.values();
public static AdminFlag valueOf(int index) {
return CACHED_VALUES[index];
}
public static EnumSet<AdminFlag> fromString(String s) {
EnumSet<AdminFlag> flags = EnumSet.noneOf(AdminFlag.class);
if (s != null) {
for (String name : s.split(",")) {
flags.add(AdminFlag.valueOf(name));
}
}
return flags;
}
}
/**
* Creates a cache on the container using the specified template.
*
* @param name the name of the cache to create
* @param template the template to use for the cache. If null, the configuration marked as default on the container
* will be used
* @return the cache
*
* @throws org.infinispan.commons.CacheException if a cache with the same name already exists
*/
<K, V> BasicCache<K, V> createCache(String name, String template);
/**
* Creates a cache on the container using the specified template.
*
* @param name the name of the cache to create
* @param configuration the configuration to use for the cache. If null, the configuration marked as default on the container
* will be used
* @return the cache
*
* @throws org.infinispan.commons.CacheException if a cache with the same name already exists
*/
<K, V> BasicCache<K, V> createCache(String name, A configuration);
/**
* Retrieves an existing cache or creates one using the specified template if it doesn't exist
*
* @param name the name of the cache to create
* @param template the template to use for the cache. If null, the configuration marked as default on the container
* will be used
* @return the cache
*/
<K, V> BasicCache<K, V> getOrCreateCache(String name, String template);
/**
* Retrieves an existing cache or creates one using the specified template if it doesn't exist
*
* @param name the name of the cache to create
* @param configuration the configuration to use for the cache. If null, the configuration marked as default on the container
* will be used
* @return the cache
*/
<K, V> BasicCache<K, V> getOrCreateCache(String name, A configuration);
/**
* Removes a cache from the cache container. Any persisted data will be cleared.
*
* @param name the name of the cache to remove
*/
void removeCache(String name);
/**
* Sets any additional {@link AdminFlag}s to be used when performing administrative operations.
*
* <b>Note:</b> whether an operation supports a certain flag or not is dependent on the configuration and environment.
* If a flag cannot be honored, the operation will fail with an exception.
*
* @param flags
* @return
*/
C withFlags(AdminFlag... flags);
/**
* Sets any additional {@link AdminFlag}s to be used when performing administrative operations.
*
* <b>Note:</b> whether an operation supports a certain flag or not is dependent on the configuration and environment.
* If a flag cannot be honored, the operation will fail with an exception.
*
* @param flags
* @return
*/
C withFlags(EnumSet<AdminFlag> flags);
/**
* Creates a template on the container using the provided configuration.
*
* @param name the name of the template
* @param configuration the configuration to use. It must be a clustered configuration (e.g. distributed)
*/
void createTemplate(String name, A configuration);
/**
* Removes a template from the cache container. Any persisted data will be cleared.
*
* @param name the name of the template to remove
*/
void removeTemplate(String name);
}
| 4,936
| 33.048276
| 137
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/api/Lifecycle.java
|
package org.infinispan.commons.api;
/**
* Lifecycle interface that defines the lifecycle of components
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
public interface Lifecycle {
/**
* Invoked on component start
*/
void start();
/**
* Invoked on component stop
*/
void stop();
}
| 366
| 15.681818
| 79
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/api/BatchingCache.java
|
package org.infinispan.commons.api;
/**
* The BatchingCache is implemented by all caches which support batching
*
* @author Tristan Tarrant
* @since 6.0
*/
public interface BatchingCache {
/**
* Starts a batch. All operations on the current client thread are performed as a part of this batch, with locks
* held for the duration of the batch and any remote calls delayed till the end of the batch.
* <p/>
*
* @return true if a batch was successfully started; false if one was available and already running.
*/
boolean startBatch();
/**
* Completes a batch if one has been started using {@link #startBatch()}. If no batch has been started, this is a
* no-op.
* <p/>
*
* @param successful if true, the batch completes, otherwise the batch is aborted and changes are not committed.
*/
void endBatch(boolean successful);
}
| 888
| 30.75
| 117
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/api/BasicCacheContainer.java
|
package org.infinispan.commons.api;
import java.util.Set;
/**
* <tt>BasicCacheContainer</tt> defines the methods used to obtain a {@link org.infinispan.commons.api.BasicCache}.
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @author Galder Zamarreño
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public interface BasicCacheContainer extends Lifecycle {
/**
* Retrieves the default cache associated with this cache container.
* <p/>
*
* @return the default cache.
* @throws org.infinispan.commons.CacheConfigurationException if a default cache does not exist.
*/
<K, V> BasicCache<K, V> getCache();
/**
* Retrieves a cache by name.
* <p/>
* If the cache has been previously created with the same name, the running
* cache instance is returned.
* Otherwise, this method attempts to create the cache first.
*
* @param cacheName name of cache to retrieve
* @return a cache instance identified by cacheName
*/
<K, V> BasicCache<K, V> getCache(String cacheName);
/**
* This method returns a collection of all cache names.
* <p/>
* The configurations may have been defined via XML, in the programmatic configuration,
* or at runtime.
* <p/>
* Internal-only caches are not included.
*
* @return an immutable set of cache names registered in this cache manager.
*/
Set<String> getCacheNames();
}
| 1,459
| 29.416667
| 115
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/logging/Log.java
|
package org.infinispan.commons.logging;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import java.io.IOException;
import java.util.EnumSet;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.dataconversion.EncodingException;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.counter.exception.CounterException;
import org.infinispan.counter.exception.CounterOutOfBoundsException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.logging.annotations.Suppressed;
/**
* Infinispan's log abstraction layer on top of JBoss Logging.
* <p/>
* It contains explicit methods for all INFO or above levels so that they can
* be internationalized. For the commons module, message ids ranging from 0901
* to 1000 inclusively have been reserved.
* <p/>
* <code> Log log = LogFactory.getLog( getClass() ); </code> The above will get
* you an instance of <tt>Log</tt>, which can be used to generate log messages
* either via JBoss Logging which then can delegate to Log4J (if the libraries
* are present) or (if not) the built-in JDK logger.
* <p/>
* In addition to the 6 log levels available, this framework also supports
* parameter interpolation, similar to the JDKs {@link String#format(String, Object...)}
* method. What this means is, that the following block:
* <code> if (log.isTraceEnabled()) { log.trace("This is a message " + message + " and some other value is " + value); }
* </code>
* <p/>
* ... could be replaced with ...
* <p/>
* <code> if (log.isTraceEnabled()) log.tracef("This is a message %s and some other value is %s", message, value);
* </code>
* <p/>
* This greatly enhances code readability.
* <p/>
* If you are passing a <tt>Throwable</tt>, note that this should be passed in
* <i>before</i> the vararg parameter list.
* <p/>
*
* @author Manik Surtani
* @since 4.0
* @api.private
*/
@MessageLogger(projectCode = "ISPN")
public interface Log extends BasicLogger {
String LOG_ROOT = "org.infinispan.";
Log CONFIG = Logger.getMessageLogger(Log.class, LOG_ROOT + "CONFIG");
Log CONTAINER = Logger.getMessageLogger(Log.class, LOG_ROOT + "CONTAINER");
Log SECURITY = Logger.getMessageLogger(Log.class, LOG_ROOT + "SECURITY");
@LogMessage(level = WARN)
@Message(value = "Property %s could not be replaced as intended!", id = 901)
void propertyCouldNotBeReplaced(String line);
@LogMessage(level = WARN)
@Message(value = "Invocation of %s threw an exception %s. Exception is ignored.", id = 902)
void ignoringException(String methodName, String exceptionName, @Cause Throwable t);
// @LogMessage(level = ERROR)
// @Message(value = "Unable to set value!", id = 903)
// void unableToSetValue(@Cause Exception e);
@Message(value = "Error while initializing SSL context", id = 904)
CacheConfigurationException sslInitializationException(@Cause Throwable e);
@LogMessage(level = ERROR)
@Message(value = "Unable to load %s from any of the following classloaders: %s", id = 905)
void unableToLoadClass(String classname, String classloaders, @Cause Throwable cause);
@LogMessage(level = WARN)
@Message(value = "Unable to convert string property [%s] to an int! Using default value of %d", id = 906)
void unableToConvertStringPropertyToInt(String value, int defaultValue);
@LogMessage(level = WARN)
@Message(value = "Unable to convert string property [%s] to a long! Using default value of %d", id = 907)
void unableToConvertStringPropertyToLong(String value, long defaultValue);
@LogMessage(level = WARN)
@Message(value = "Unable to convert string property [%s] to a boolean! Using default value of %b", id = 908)
void unableToConvertStringPropertyToBoolean(String value, boolean defaultValue);
@Message(value = "Unwrapping %s to a type of %s is not a supported", id = 909)
IllegalArgumentException unableToUnwrap(Object o, Class<?> clazz);
@Message(value = "Illegal value for thread pool parameter(s) %s, it should be: %s", id = 910)
CacheConfigurationException illegalValueThreadPoolParameter(String parameter, String requirement);
@Message(value = "Unwrapping of any instances in %s to a type of %s is not a supported", id = 911)
IllegalArgumentException unableToUnwrapAny(String objs, Class<?> clazz);
@Message(value = "Expecting a protected configuration for %s", id = 912)
IllegalStateException unprotectedAttributeSet(String name);
@Message(value = "Expecting an unprotected configuration for %s", id = 913)
IllegalStateException protectedAttributeSet(String name);
@Message(value = "Duplicate attribute '%s' in attribute set '%s'", id = 914)
IllegalArgumentException attributeSetDuplicateAttribute(String name, String setName);
@Message(value = "No such attribute '%s' in attribute set '%s'", id = 915)
IllegalArgumentException noSuchAttribute(String name, String setName);
@Message(value = "No attribute copier for type '%s'", id = 916)
IllegalArgumentException noAttributeCopierForType(Class<?> klass);
// @Message(value = "Cannot resize unbounded container", id = 917)
// UnsupportedOperationException cannotResizeUnboundedContainer();
@Message(value = "Cannot find resource '%s'", id = 918)
IOException cannotFindResource(String fileName);
@Message(value = "Multiple errors encountered while validating configuration", id = 919)
CacheConfigurationException multipleConfigurationValidationErrors();
@Message(value = "Unable to load file using scheme %s", id = 920)
UnsupportedOperationException unableToLoadFileUsingScheme(String scheme);
@Message(value = "The alias '%s' does not exist in the key store '%s'", id = 921)
SecurityException noSuchAliasInKeyStore(String keyAlias, String keyStoreFileName);
@LogMessage(level = ERROR)
@Message(value = "Exception during rollback", id = 922)
void errorRollingBack(@Cause Throwable e);
@LogMessage(level = ERROR)
@Message(value = "Error enlisting resource", id = 923)
void errorEnlistingResource(@Cause Throwable e);
@LogMessage(level = ERROR)
@Message(value = "beforeCompletion() failed for %s", id = 924)
void beforeCompletionFailed(String synchronization, @Cause Throwable t);
@LogMessage(level = ERROR)
@Message(value = "Unexpected error from resource manager!", id = 925)
void unexpectedErrorFromResourceManager(@Cause Throwable t);
@LogMessage(level = ERROR)
@Message(value = "afterCompletion() failed for %s", id = 926)
void afterCompletionFailed(String synchronization, @Cause Throwable t);
@LogMessage(level = WARN)
@Message(value = "exception while committing", id = 927)
void errorCommittingTx(@Cause Throwable e);
@LogMessage(level = ERROR)
@Message(value = "end() failed for %s", id = 928)
void xaResourceEndFailed(String xaResource, @Cause Throwable t);
@Message(value = "Media type cannot be empty or null!", id = 929)
EncodingException missingMediaType();
@Message(value = "Invalid media type '%s': must contain a type and a subtype separated by '/'", id = 930)
EncodingException invalidMediaTypeSubtype(String mediaType);
@Message(value = "Invalid media type '%s': invalid param '%s'", id = 931)
EncodingException invalidMediaTypeParam(String mediaType, String param);
@Message(value = "Invalid media type list '%s': comma expected", id = 932)
EncodingException invalidMediaTypeListCommaMissing(String mediaType);
@Message(value = "Invalid media type list '%s': type expected after comma", id = 933)
EncodingException invalidMediaTypeListCommaAtEnd(String mediaType);
//
@Message(value = "Errors converting '%s' from '%s' to '%s'", id = 934)
EncodingException errorTranscoding(String content, MediaType contentType, MediaType requestType, @Cause Throwable t);
@Message(value = "Invalid Weight '%s'. Supported values are between 0 and 1.0", id = 935)
EncodingException invalidWeight(Object weight);
@Message(value = "Class '%s' blocked by deserialization allow list. Adjust the configuration serialization allow list regular expression to include this class.", id = 936)
CacheException classNotInAllowList(String className);
@Message(value = "Invalid media type. Expected '%s' but got '%s'", id = 937)
EncodingException invalidMediaType(String expected, String actual);
@Message(value = "Invalid text content '%s'", id = 938)
EncodingException invalidTextContent(Object content);
@Message(value = "Conversion of content '%s' from '%s' to '%s' not supported", id = 939)
EncodingException conversionNotSupported(Object content, String fromMediaType, String toMediaType);
@Message(value = "Invalid application/x-www-form-urlencoded content: '%s'", id = 940)
EncodingException cannotDecodeFormURLContent(Object content);
@Message(value = "Error encoding content '%s' to '%s'", id = 941)
EncodingException errorEncoding(Object content, MediaType mediaType);
@LogMessage(level = WARN)
@Message(value = "Unable to convert property [%s] to an enum! Using default value of %d", id = 942)
void unableToConvertStringPropertyToEnum(String value, String defaultValue);
// @LogMessage(level = ERROR)
// @Message(value = "Could not register object with name: %s", id = 943)
// void couldNotRegisterObjectName(ObjectName objectName, @Cause Exception e);
@Message(value = "Feature %s is disabled!", id = 944)
CacheConfigurationException featureDisabled(String feature);
// @Message(value = "Unable to marshall Object '%s' wrapped by '%s', the wrapped object must be registered with the marshallers SerializationContext", id = 945)
// MarshallingException unableToMarshallRuntimeObject(String wrappedObjectClass, String wrapperClass);
@LogMessage(level = INFO)
@Message(value = "Using OpenSSL Provider", id = 946)
void openSSLAvailable();
@LogMessage(level = INFO)
@Message(value = "Using Java SSL Provider", id = 947)
void openSSLNotAvailable();
@Message(value = "Unsupported conversion of '%s' from '%s' to '%s'", id = 948)
EncodingException unsupportedConversion(String content, MediaType contentType, MediaType requestType);
@Message(value = "Unsupported conversion of '%s' to '%s'", id = 949)
EncodingException unsupportedConversion(String content, MediaType requestType);
@Message(value = "Encoding '%s' is not supported", id = 950)
EncodingException encodingNotSupported(String enc);
@Message(value = "Invalid value %s for attribute %s: must be a number greater than zero", id = 951)
CacheConfigurationException attributeMustBeGreaterThanZero(Number value, Enum<?> attribute);
@LogMessage(level = INFO)
@Message(value = "OpenTelemetry instance loaded: %s", id = 952)
void telemetryLoaded(Object telemetry);
@LogMessage(level = INFO)
@Message(value = "OpenTelemetry integration is disabled", id = 953)
void telemetryDisabled();
@LogMessage(level = WARN)
@Message(value = "OpenTelemetry cannot be configured", id = 954)
void errorOnLoadingTelemetry();
@Message(value = "'%s' is not a valid boolean value (true|false|yes|no|y|n|on|off)", id = 955)
IllegalArgumentException illegalBooleanValue(String value);
@Message(value = "'%s' is not one of %s", id = 956)
IllegalArgumentException illegalEnumValue(String value, EnumSet<?> set);
@LogMessage(level = ERROR)
@Message(value = "Cannot load %s", id = 957)
void cannotLoadMimeTypes(String mimeTypes);
@Message(value = "Cannot parse bytes quantity %s", id = 958)
IllegalArgumentException cannotParseQuantity(String str);
@LogMessage(level = WARN)
@Message(value = "Property '%s' has been deprecated. Please use '%s' instead.", id = 959)
void deprecatedProperty(String oldName, String newName);
@Message(value = "No attribute '%s' in '%s'", id = 960)
IllegalArgumentException noAttribute(String name, String element);
@Message(value = "Incompatible attribute '%s.%s' existing value='%s', new value='%s'", id = 961)
IllegalArgumentException incompatibleAttribute(String parentName, String name, String v1, String v2);
@Message(value = "Cannot modify protected attribute '%s'", id = 962)
IllegalStateException protectedAttribute(String name);
@Message(value = "Invalid configuration in '%s'", id = 963)
IllegalArgumentException invalidConfiguration(String name);
//----- counters exceptions // don't use the same id range ------
@Message(value = CounterOutOfBoundsException.FORMAT_MESSAGE, id = 29501)
CounterOutOfBoundsException counterOurOfBounds(String bound);
@Message(value = "Invalid counter type. Expected=%s but got %s", id = 29514)
CounterException invalidCounterType(String expected, String actual);
@Message(value = "Counter '%s' is not defined.", id = 29516)
CounterException undefinedCounter(String name);
@Message(value = "WEAK and BOUNDED encoded flag isn't supported!", id = 29522)
CounterException invalidCounterTypeEncoded();
@Message(value = "Cannot instantiate class '%s'")
CacheConfigurationException cannotInstantiateClass(String classname, @Suppressed Throwable t);
//----- counters exceptions // don't use the same id range ------
}
| 13,597
| 44.630872
| 174
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/logging/LogFactory.java
|
package org.infinispan.commons.logging;
import org.jboss.logging.Logger;
/**
* Factory that creates {@link Log} instances.
*
* @author Manik Surtani
* @since 4.0
*/
public class LogFactory {
public static Log getLog(Class<?> clazz) {
return Logger.getMessageLogger(Log.class, clazz.getName());
}
public static <T> T getLog(Class<?> clazz, Class<T> logClass) {
return Logger.getMessageLogger(logClass, clazz.getName());
}
}
| 456
| 20.761905
| 66
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/logging/BasicLogFactory.java
|
package org.infinispan.commons.logging;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
/**
* Factory that creates {@link Log} instances.
*
* @author Manik Surtani
* @since 4.0
*/
public class BasicLogFactory {
public static BasicLogger getLog(Class<?> clazz) {
return Logger.getLogger(clazz.getName());
}
public static <T> T getLog(Class<?> clazz, Class<T> logClass) {
return Logger.getMessageLogger(logClass, clazz.getName());
}
}
| 490
| 20.347826
| 66
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/BloomFilter.java
|
package org.infinispan.commons.util;
import java.util.function.ToIntFunction;
public class BloomFilter<E> {
private final int bitsToUse;
private final IntSet intSet;
private final Iterable<ToIntFunction<? super E>> hashFunctions;
BloomFilter(int bitsToUse, IntSet intSet, Iterable<ToIntFunction<? super E>> hashFunctions) {
this.bitsToUse = bitsToUse;
this.intSet = intSet;
this.hashFunctions = hashFunctions;
}
public static <E> BloomFilter<E> createFilter(int bitsToUse, Iterable<ToIntFunction<? super E>> hashFunctions) {
return new BloomFilter<>(bitsToUse, IntSets.mutableEmptySet(bitsToUse), hashFunctions);
}
/**
* Same as {@link #createFilter(int, Iterable)} except the returned {code BloomFilter} instance may be used
* concurrently without additional synchronization.
* <p>
* The provided function iterable must be able to be iterated upon concurrently.
* @param bitsToUse
* @param hashFunctions
* @param <E>
* @return
*/
public static <E> BloomFilter<E> createConcurrentFilter(int bitsToUse, Iterable<ToIntFunction<? super E>> hashFunctions) {
return new BloomFilter<>(bitsToUse, IntSets.concurrentSet(bitsToUse), hashFunctions);
}
/**
* Adds a value to the filter setting up to a number of bits equal to the number of hash functions. This method
* will also return {code true} if any of the bits were updated, meaning this value was for sure not present before.
* @param value the value to add to the filter
* @return whether the filter was actually updated
*/
public boolean addToFilter(E value) {
boolean setABit = false;
for (ToIntFunction<? super E> function : hashFunctions) {
int hashResult = Math.abs(function.applyAsInt(value));
int bitToCheck = hashResult % bitsToUse;
setABit |= intSet.add(bitToCheck);
}
return setABit;
}
/**
* Returns {@code true} if the element might be present, {@code false} if the value was for sure not present.
* @param value the value to check for
* @return whether this value may be present or for sure not
*/
public boolean possiblyPresent(E value) {
for (ToIntFunction<? super E> function : hashFunctions) {
int hashResult = Math.abs(function.applyAsInt(value));
int bitToCheck = hashResult % bitsToUse;
if (!intSet.contains(bitToCheck)) {
return false;
}
}
return true;
}
/**
* Clears all current bits and sets them to the values in the provided {@link IntSet}. Since this method clears
* and sets the values any other concurrent operations may be ignored.
* @param intSet
*/
public void setBits(IntSet intSet) {
this.intSet.clear();
this.intSet.addAll(intSet);
}
public IntSet getIntSet() {
return IntSets.immutableSet(intSet);
}
@Override
public String toString() {
return "BloomFilter{" +
"bitsToUse=" + bitsToUse +
", intSet=" + intSet +
'}';
}
}
| 3,079
| 34
| 125
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/Features.java
|
package org.infinispan.commons.util;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Properties;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* Features allow conditional enabling/disabling of Infinispan's functionality.
* They are represented as named properties of the form 'org.infinispan.feature.*' and can either be set via one or
* more 'META-INF/infinispan-features.properties' file on the classpath or by setting a system property,
* e.g. -Dorg.infinispan.feature.A=true
*/
public class Features {
private static final Log log = LogFactory.getLog(Features.class);
public static final String FEATURE_PREFIX = "org.infinispan.feature.";
static final String FEATURES_FILE = "META-INF/infinispan-features.properties";
private final Properties features;
public Features(ClassLoader classLoader) {
features = new Properties();
try {
Collection<URL> featureFiles = FileLookupFactory.newInstance().lookupFileLocations(FEATURES_FILE, classLoader);
for (URL url : featureFiles) {
try (InputStream is = url.openStream()) {
features.load(is);
}
}
if (log.isDebugEnabled()) {
features.forEach((key, value) -> log.debugf("Feature %s=%s", key, value));
}
} catch (IOException e) {
log.debugf(e, "Error while attempting to obtain `%s` resources from the classpath", FEATURES_FILE);
throw new CacheConfigurationException(e);
}
}
public Features() {
this(Features.class.getClassLoader());
}
public boolean isAvailable(String featureName) {
String name = FEATURE_PREFIX + featureName;
String sysprop = System.getProperty(name);
if (sysprop != null) {
return Boolean.parseBoolean(sysprop);
} else {
return Boolean.parseBoolean(features.getProperty(name, "true"));
}
}
}
| 2,077
| 35.45614
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ForwardingList.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* A list which forwards all its method calls to another list. Subclasses should override one or more methods to modify the
* behavior of the backing list as desired per the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator
* pattern</a>.
*
* <p>
* This class does not implement {@link java.util.RandomAccess}. If the delegate supports random access, the
* {@code ForwardingList} subclass should implement the {@code RandomAccess} interface.
*
* @author Mike Bostock
* @since 2 (imported from Google Collections Library)
*/
public abstract class ForwardingList<E> implements List<E> {
/** Constructor for use by subclasses. */
protected ForwardingList() {
}
protected abstract List<E> delegate();
@Override
public void add(int index, E element) {
delegate().add(index, element);
}
@Override
public boolean addAll(int index, Collection<? extends E> elements) {
return delegate().addAll(index, elements);
}
@Override
public E get(int index) {
return delegate().get(index);
}
@Override
public int indexOf(Object element) {
return delegate().indexOf(element);
}
@Override
public int lastIndexOf(Object element) {
return delegate().lastIndexOf(element);
}
@Override
public ListIterator<E> listIterator() {
return delegate().listIterator();
}
@Override
public ListIterator<E> listIterator(int index) {
return delegate().listIterator(index);
}
@Override
public E remove(int index) {
return delegate().remove(index);
}
@Override
public E set(int index, E element) {
return delegate().set(index, element);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
return delegate().subList(fromIndex, toIndex);
}
@Override
public boolean equals(Object object) {
return object == this || delegate().equals(object);
}
@Override
public int hashCode() {
return delegate().hashCode();
}
@Override
public Iterator<E> iterator() {
return delegate().iterator();
}
@Override
public int size() {
return delegate().size();
}
@Override
public boolean removeAll(Collection<?> collection) {
return delegate().removeAll(collection);
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public boolean contains(Object object) {
return delegate().contains(object);
}
@Override
public Object[] toArray() {
return delegate().toArray();
}
@Override
public <T> T[] toArray(T[] array) {
return delegate().toArray(array);
}
@Override
public boolean add(E element) {
return delegate().add(element);
}
@Override
public boolean remove(Object object) {
return delegate().remove(object);
}
@Override
public boolean containsAll(Collection<?> collection) {
return delegate().containsAll(collection);
}
@Override
public boolean addAll(Collection<? extends E> collection) {
return delegate().addAll(collection);
}
@Override
public boolean retainAll(Collection<?> collection) {
return delegate().retainAll(collection);
}
@Override
public void clear() {
delegate().clear();
}
}
| 3,464
| 21.5
| 123
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/TypedProperties.java
|
package org.infinispan.commons.util;
import java.util.Map;
import java.util.Properties;
import java.util.function.Function;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* Type-aware properties. Extends the JDK {@link Properties} class to provide accessors that convert values to certain
* types, using default values if a conversion is not possible.
*
*
* @configRef name="Properties to add to the enclosing component."
*
* @author Manik Surtani
* @since 4.0
*/
public class TypedProperties extends Properties {
/** The serialVersionUID */
private static final long serialVersionUID = 3799321248100686287L;
private static final Log log = LogFactory.getLog(TypedProperties.class);
/**
* Copy constructor
*
* @param p properties instance to from. If null, then it is treated as an empty Properties instance.
*/
public TypedProperties(Map<?, ?> p) {
if (p != null && !p.isEmpty()) super.putAll(p);
}
/**
* Default constructor that returns an empty instance
*/
public TypedProperties() {
}
/**
* Factory method that converts a JDK {@link Map} (including {@link Properties} instance to an instance of TypedProperties, if needed.
*
* @param p properties to convert.
* @return A TypedProperties object. Returns an empty TypedProperties instance if p is null.
*/
public static TypedProperties toTypedProperties(Map<?, ?> p) {
if (p instanceof TypedProperties) return (TypedProperties) p;
return new TypedProperties(p);
}
public int getIntProperty(String key, int defaultValue) {
return getIntProperty(key, defaultValue, false);
}
public int getIntProperty(String key, int defaultValue, boolean doStringReplace) {
Object value = this.get(key);
if (value instanceof Integer) {
return (int) value;
} else {
return getPropertyFn(value, defaultValue, doStringReplace, valueStr -> {
try {
return Integer.parseInt(valueStr);
} catch (NumberFormatException nfe) {
log.unableToConvertStringPropertyToInt(valueStr, defaultValue);
return defaultValue;
}
});
}
}
public long getLongProperty(String key, long defaultValue) {
return getLongProperty(key, defaultValue, false);
}
public long getLongProperty(String key, long defaultValue, boolean doStringReplace) {
Object value = this.get(key);
if (value instanceof Long) {
return (long) value;
} else {
return getPropertyFn(value, defaultValue, doStringReplace, valueStr -> {
try {
return Long.parseLong(valueStr);
} catch (NumberFormatException nfe) {
log.unableToConvertStringPropertyToLong(valueStr, defaultValue);
return defaultValue;
}
});
}
}
public boolean getBooleanProperty(String key, boolean defaultValue) {
return getBooleanProperty(key, defaultValue, false);
}
public boolean getBooleanProperty(String key, boolean defaultValue, boolean doStringReplace) {
Object value = this.get(key);
if (value instanceof Boolean) {
return (boolean) value;
} else {
return getPropertyFn(value, defaultValue, doStringReplace, valueStr -> {
try {
return Boolean.parseBoolean(valueStr);
} catch (Exception e) {
log.unableToConvertStringPropertyToBoolean(valueStr, defaultValue);
return defaultValue;
}
});
}
}
public <T extends Enum<T>> T getEnumProperty(String key, Class<T> enumClass, T defaultValue) {
return getEnumProperty(key, enumClass, defaultValue, false);
}
public <T extends Enum<T>> T getEnumProperty(String key, Class<T> enumClass, T defaultValue, boolean doStringReplace) {
Object value = this.get(key);
if (value instanceof Enum && enumClass.isInstance(value)) {
return (T) value;
} else {
return getPropertyFn(value, defaultValue, doStringReplace, valueStr -> {
try {
return Enum.valueOf(enumClass, valueStr);
} catch (IllegalArgumentException e) {
log.unableToConvertStringPropertyToEnum(valueStr, defaultValue.name());
return defaultValue;
}
});
}
}
/**
* Get the property associated with the key, optionally applying string property replacement as defined in
* {@link StringPropertyReplacer#replaceProperties} to the result.
*
* @param key the hashtable key.
* @param defaultValue a default value.
* @param doStringReplace boolean indicating whether to apply string property replacement
* @return the value in this property list with the specified key value after optionally being inspected for String property replacement
*/
public synchronized String getProperty(String key, String defaultValue, boolean doStringReplace) {
if (doStringReplace)
return StringPropertyReplacer.replaceProperties(getProperty(key, defaultValue));
else
return getProperty(key, defaultValue);
}
/**
* Get the property associated with the key, optionally applying string property replacement as defined in
* {@link StringPropertyReplacer#replaceProperties} to the result.
*
* @param key the hashtable key.
* @param doStringReplace boolean indicating whether to apply string property replacement
* @return the value in this property list with the specified key value after optionally being inspected for String property replacement
*/
public synchronized String getProperty(String key, boolean doStringReplace) {
if (doStringReplace)
return StringPropertyReplacer.replaceProperties(getProperty(key));
else
return getProperty(key);
}
/**
* Put a value if the associated key is not present
* @param key new key
* @param value new value
* @return this TypedProperties instance for method chaining
*
*/
public synchronized TypedProperties putIfAbsent(String key, String value) {
if (getProperty(key) == null) {
put(key, value);
}
return this;
}
@Override
public synchronized TypedProperties setProperty(String key, String value) {
super.setProperty(key, value);
return this;
}
public synchronized TypedProperties setProperty(String key, int value) {
super.setProperty(key, Integer.toString(value));
return this;
}
public synchronized TypedProperties setProperty(String key, long value) {
super.setProperty(key, Long.toString(value));
return this;
}
public synchronized TypedProperties setProperty(String key, boolean value) {
super.setProperty(key, Boolean.toString(value));
return this;
}
private <V> V getPropertyFn(Object value, V defaultValue, boolean doStringReplace, Function<String, V> action) {
String valueStr = null;
if (value instanceof String) {
valueStr = (String) value;
}
if (valueStr == null) return defaultValue;
valueStr = valueStr.trim();
if (valueStr.length() == 0) return defaultValue;
if (doStringReplace)
valueStr = StringPropertyReplacer.replaceProperties(valueStr);
return action.apply(valueStr);
}
}
| 7,522
| 34.154206
| 140
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/PeekableMap.java
|
package org.infinispan.commons.util;
import java.util.Map;
/**
*
* @param <K>
* @param <V>
* @deprecated since 11.0 with no replacement - no longer used
*/
@Deprecated
public interface PeekableMap<K, V> extends Map<K, V> {
/**
* Peaks at a value for the given key. Note that this does not update any expiration or
* eviction information when this is performed on the map, unlike the get method.
* @param key The key to find the value for
* @return The value mapping to this key
*/
public V peek(Object key);
}
| 544
| 24.952381
| 91
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/package-info.java
|
/**
* Commons package providing various utility classes
*
* @api.public
*/
package org.infinispan.commons.util;
| 116
| 15.714286
| 52
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/IntSets.java
|
package org.infinispan.commons.util;
import java.util.PrimitiveIterator;
import java.util.Set;
import java.util.function.IntConsumer;
/**
* Static utility class for creating various {@link IntSet} objects.
* @author wburns
* @since 9.3
*/
public class IntSets {
private IntSets() { }
/**
* Returns an immutable IntSet containing no values
* @return IntSet with no values
*/
public static IntSet immutableEmptySet() {
return EmptyIntSet.getInstance();
}
/**
* Returns an immutable IntSet containing a single value
* @param value the value to be set on the IntSet
* @return IntSet with just the 1 value
*/
public static IntSet immutableSet(int value) {
return new SingletonIntSet(value);
}
/**
* Returns an immutable IntSet that wraps the given IntSet to prevent modifications.
* @param set set to wrap
* @return immutable IntSet
*/
public static IntSet immutableSet(IntSet set) {
if (set instanceof AbstractImmutableIntSet)
return set;
return new ImmutableIntSet(set);
}
/**
* Returns an immutable IntSet containing all values from {@code 0} to {@code endExclusive - 1}.
* @param endExclusive the exclusive upper bound
* @return IntSet with the values in the given range available
*/
public static IntSet immutableRangeSet(int endExclusive) {
return new RangeSet(endExclusive);
}
/**
* Returns an IntSet based on the provided Set. This method tries to return or create the most performant IntSet
* based on the Set provided. If the Set is already an IntSet it will just return that. The returned IntSet may or
* may not be immutable, so no guarantees are provided from that respect.
* @param integerSet IntSet to create from
* @return the IntSet that is equivalent to the Set
*/
public static IntSet from(Set<Integer> integerSet) {
if (integerSet instanceof IntSet) {
return (IntSet) integerSet;
}
int size = integerSet.size();
switch (size) {
case 0:
return EmptyIntSet.getInstance();
case 1:
return new SingletonIntSet(integerSet.iterator().next());
default:
return SmallIntSet.from(integerSet);
}
}
public static IntSet from(byte[] bytes) {
int size = bytes.length;
if (size == 0) {
return EmptyIntSet.getInstance();
}
return SmallIntSet.from(bytes);
}
/**
* Returns an IntSet based on the ints in the iterator. This method will try to return the most performant IntSet
* based on what ints are provided if any. The returned IntSet may or may not be immutable, so no guarantees are
* provided from that respect.
* @param iterator values set in the returned set
* @return IntSet with all the values set that the iterator had
*/
public static IntSet from(PrimitiveIterator.OfInt iterator) {
boolean hasNext = iterator.hasNext();
if (!hasNext) {
return EmptyIntSet.getInstance();
}
int firstValue = iterator.nextInt();
hasNext = iterator.hasNext();
if (!hasNext) {
return new SingletonIntSet(firstValue);
}
// We have 2 or more values so just set them in the SmallIntSet
SmallIntSet set = new SmallIntSet();
set.set(firstValue);
iterator.forEachRemaining((IntConsumer) set::set);
return set;
}
/**
* Returns an IntSet that is mutable that contains all of the values from the given set. If this provided Set is
* already an IntSet and mutable it will return the same object.
* @param integerSet set to use values from
* @return IntSet that is mutable with the values set
*/
public static IntSet mutableFrom(Set<Integer> integerSet) {
if (integerSet instanceof SmallIntSet) {
return (SmallIntSet) integerSet;
}
if (integerSet instanceof ConcurrentSmallIntSet) {
return (ConcurrentSmallIntSet) integerSet;
}
return mutableCopyFrom(integerSet);
}
/**
* Returns an IntSet that contains all ints from the given Set that is mutable. Updates to the original Set or
* the returned IntSet are not reflected in the other.
* @param mutableSet set to copy from
* @return IntSet with the values set
*/
public static IntSet mutableCopyFrom(Set<Integer> mutableSet) {
if (mutableSet instanceof SingletonIntSet) {
return mutableSet(((SingletonIntSet) mutableSet).value);
}
return new SmallIntSet(mutableSet);
}
/**
* Returns an IntSet that contains no values but is initialized to hold ints equal to the {@code maxExclusive -1} or
* smaller.
* @param maxExclusive largest int expected in set
* @return IntSet with no values set
*/
public static IntSet mutableEmptySet(int maxExclusive) {
return new SmallIntSet(maxExclusive);
}
/**
* Returns a mutable IntSet with no values set. Note this mutable set is initialized given a default size. If you wish
* to not have less initialization over, please use {@link #mutableEmptySet(int)} providing a {@code 0} or similar.
* @return IntSet with no values set
*/
public static IntSet mutableEmptySet() {
return new SmallIntSet();
}
/**
* Returns a mutable set with the initial value set. This set is optimized to insert values less than this. Values
* added that are larger may require additional operations.
* @param value the value to set
* @return IntSet with the value set
*/
public static IntSet mutableSet(int value) {
return SmallIntSet.of(value);
}
/**
* Returns a mutable IntSet that begins with the initialized values
* @param value1
* @param value2
* @return
*/
public static IntSet mutableSet(int value1, int value2) {
return SmallIntSet.of(value1, value2);
}
/**
* Returns a concurrent mutable IntSet that can store values in the range of {@code 0..maxExclusive-1}
* @param maxExclusive the maximum value - 1 that can be inserted into the set
* @return concurrent set
*/
public static IntSet concurrentSet(int maxExclusive) {
// if maxExclusive = 0; then we have an empty set
return maxExclusive == 0 ? immutableEmptySet() : new ConcurrentSmallIntSet(maxExclusive);
}
/**
* Returns a copy of the given set that supports concurrent operations. The returned set will contain all of the
* ints the provided set contained. The returned mutable IntSet can store values in the range of {@code 0..maxExclusive-1}
* @param intSet set to copy from
* @param maxExclusive the maximum value - 1 that can be inserted into the set
* @return concurrent copy
*/
public static IntSet concurrentCopyFrom(IntSet intSet, int maxExclusive) {
// if maxExclusive = 0; then we have an empty set
if (maxExclusive == 0) {
return immutableEmptySet();
}
ConcurrentSmallIntSet cis = new ConcurrentSmallIntSet(maxExclusive);
intSet.forEach((IntConsumer) cis::set);
return cis;
}
}
| 7,128
| 34.292079
| 125
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ArrayMap.java
|
package org.infinispan.commons.util;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.function.IntFunction;
/**
* Base for classes that implement hash map by storing keys in one array and values in another.
* It assumes that all keys that are in the array are contained in the map and that values
* are on corresponding indices in the map.
*
* Does not support null keys nor values.
*
* Forces implementation of methods {@link #get(Object)}, {@link #put(Object, Object)}, {@link #remove(Object)}
*/
public abstract class ArrayMap<K, V> extends java.util.AbstractMap<K, V> {
protected int size;
protected Object[] keys;
protected Object[] values;
protected int modCount;
private Set<K> keySet;
private Collection<V> valueCollection;
private Set<Entry<K, V>> entrySet;
@Override
public abstract V get(Object key);
@Override
public abstract V put(K key, V value);
@Override
public abstract V remove(Object key);
@Override
public int size() {
return size;
}
@Override
public boolean containsValue(Object value) {
Objects.requireNonNull(value);
for (int i = 0; i < values.length; ++i) {
Object v = values[i];
if (v != null && v.equals(value)) return true;
}
return false;
}
@Override
public Set<K> keySet() {
if (keySet == null) {
keySet = new KeySet();
}
return keySet;
}
@Override
public Collection<V> values() {
if (valueCollection == null) {
valueCollection = new Values();
}
return valueCollection;
}
@Override
public Set<Entry<K, V>> entrySet() {
if (entrySet == null) {
entrySet = new EntrySet();
}
return entrySet;
}
@Override
public boolean containsKey(Object key) {
return get(key) != null;
}
@Override
public void clear() {
size = 0;
++modCount;
Arrays.fill(keys, null);
Arrays.fill(values, null);
}
private class KeySet extends AbstractSet<K> {
@Override
public Iterator<K> iterator() {
return new It<>(i -> (K) keys[i], keys.length, modCount);
}
@Override
public int size() {
return ArrayMap.this.size();
}
@Override
public void clear() {
ArrayMap.this.clear();
}
@Override
public boolean contains(Object o) {
return containsKey(o);
}
@Override
public boolean remove(Object o) {
return ArrayMap.this.remove(o) != null;
}
}
private class Values extends AbstractCollection<V> {
@Override
public Iterator<V> iterator() {
return new It<>(i -> (V) values[i], values.length, modCount);
}
@Override
public int size() {
return ArrayMap.this.size();
}
@Override
public void clear() {
ArrayMap.this.clear();
}
}
private class EntrySet extends AbstractSet<Entry<K, V>> {
@Override
public Iterator<Entry<K, V>> iterator() {
return new It<>(i -> {
Object key = keys[i];
return key == null ? null : new SimpleEntry<K, V>((K) key, (V) values[i]);
}, keys.length, modCount);
}
@Override
public int size() {
return ArrayMap.this.size();
}
@Override
public void clear() {
ArrayMap.this.clear();
}
}
private class It<T> implements Iterator<T> {
private final IntFunction<T> retriever;
private final int length;
private final int initialModCount;
private int last = -1, pos = 0;
private T next;
public It(IntFunction<T> retriever, int length, int initialModCount) {
this.retriever = retriever;
this.length = length;
this.initialModCount = initialModCount;
}
@Override
public boolean hasNext() {
if (initialModCount != modCount) {
throw new ConcurrentModificationException();
}
if (next != null) {
return true;
}
while (pos < length) {
next = retriever.apply(pos);
++pos;
if (next != null) {
last = pos -1;
return true;
}
}
return false;
}
@Override
public T next() {
if (hasNext()) {
T tmp = next;
next = null;
return tmp;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
if (initialModCount != modCount) {
throw new ConcurrentModificationException();
}
keys[last] = null;
values[last] = null;
}
}
}
| 5,038
| 22.995238
| 111
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/CloseableSpliterator.java
|
package org.infinispan.commons.util;
import java.util.Spliterator;
/**
* Interface that provides semantics of a {@link Spliterator} and {@link AutoCloseable} interfaces. This is
* useful when you have data that can be splitted and may hold resources in the underlying implementation that
* must be closed.
* <p>A spliterator split from this is not closeable. Only the original {@link CloseableSpliterator} is
* required to be closed</p>
* <p>Some implementations may close resources automatically when the spliterator is exhausted however
* this is an implementation detail and all callers should call {@link AutoCloseable#close()} method to be
* sure all resources are freed properly.</p>
* @since 8.0
*/
public interface CloseableSpliterator<T> extends Spliterator<T>, AutoCloseable {
@Override
void close();
}
| 833
| 40.7
| 110
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/Either.java
|
package org.infinispan.commons.util;
import java.util.NoSuchElementException;
public abstract class Either<A, B> {
public enum Type {
LEFT, RIGHT
}
public static <A, B> Either<A, B> newLeft(A a) {
return new Left<>(a);
}
public static <A, B> Either<A, B> newRight(B b) {
return new Right<>(b);
}
public abstract Type type();
public abstract A left();
public abstract B right();
private static class Left<A, B> extends Either<A, B> {
private A leftValue;
Left(A a) { leftValue = a; }
@Override public Type type() { return Type.LEFT; }
@Override public A left() { return leftValue; }
@Override public B right() { throw new NoSuchElementException("Either.right() called on Left"); }
@Override
public String
toString() {
return "Left(" + leftValue + ')';
}
}
private static class Right<A, B> extends Either<A, B> {
private B rightValue;
Right(B b) { rightValue = b; }
@Override public Type type() { return Type.RIGHT; }
@Override public A left() { throw new NoSuchElementException("Either.left() called on Right"); }
@Override public B right() { return rightValue; }
@Override
public String
toString() {
return "Right(" + rightValue + ')';
}
}
}
| 1,335
| 25.72
| 103
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.