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/commons/time/TimeServiceTicker.java
|
package org.infinispan.commons.time;
import com.github.benmanes.caffeine.cache.Ticker;
/**
* A Ticker for Caffeine backed by a TimeService
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.0
**/
public class TimeServiceTicker implements Ticker {
private final TimeService timeService;
public TimeServiceTicker(TimeService timeService) {
this.timeService = timeService;
}
@Override
public long read() {
return timeService.time();
}
}
| 491
| 20.391304
| 57
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/MarshallerEncoder.java
|
package org.infinispan.commons.dataconversion;
import java.io.IOException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.marshall.StreamingMarshaller;
/**
* Encoder that uses a {@link StreamingMarshaller} to convert objects to byte[] and back.
*
* @since 9.1
* @deprecated Since 12.1, to be removed in a future version.
*/
@Deprecated
public abstract class MarshallerEncoder implements Encoder {
private final Marshaller marshaller;
public MarshallerEncoder(Marshaller marshaller) {
this.marshaller = marshaller;
}
@Override
public Object toStorage(Object content) {
try {
return marshall(content);
} catch (IOException | InterruptedException e) {
throw new CacheException(e);
}
}
@Override
public Object fromStorage(Object stored) {
try {
return stored instanceof byte[] ? marshaller.objectFromByteBuffer((byte[]) stored) : stored;
} catch (IOException | ClassNotFoundException e) {
throw new CacheException(e);
}
}
@Override
public boolean isStorageFormatFilterable() {
return false;
}
protected Object unmarshall(byte[] source) throws IOException, ClassNotFoundException {
return marshaller.objectFromByteBuffer(source);
}
protected byte[] marshall(Object source) throws IOException, InterruptedException {
return marshaller.objectToByteBuffer(source);
}
}
| 1,500
| 26.290909
| 101
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/WrapperIds.java
|
package org.infinispan.commons.dataconversion;
/**
* @since 9.2
*/
public interface WrapperIds {
byte NO_WRAPPER = 0;
byte BYTE_ARRAY_WRAPPER = 1;
byte PROTOBUF_WRAPPER = 2;
/**
* @deprecated Replaced by PROTOBUF_WRAPPER. Will be removed in next minor version.
*/
@Deprecated
byte PROTOSTREAM_WRAPPER = PROTOBUF_WRAPPER;
byte IDENTITY_WRAPPER = 3;
}
| 386
| 17.428571
| 86
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/MediaTypeIds.java
|
package org.infinispan.commons.dataconversion;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_INFINISPAN_MARSHALLING;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JBOSS_MARSHALLING;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PDF;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_RTF;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_UNKNOWN;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_ZIP;
import static org.infinispan.commons.dataconversion.MediaType.IMAGE_GIF;
import static org.infinispan.commons.dataconversion.MediaType.IMAGE_JPEG;
import static org.infinispan.commons.dataconversion.MediaType.IMAGE_PNG;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_CSS;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_CSV;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_HTML;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN;
import java.util.HashMap;
import java.util.Map;
/**
* @since 9.2
*/
public final class MediaTypeIds {
private static final Map<MediaType, Short> idByType = new HashMap<>(16);
private static final Map<Short, MediaType> typeById = new HashMap<>(16);
static {
idByType.put(APPLICATION_OBJECT, (short) 1);
idByType.put(APPLICATION_JSON, (short) 2);
idByType.put(APPLICATION_OCTET_STREAM, (short) 3);
idByType.put(APPLICATION_PDF, (short) 4);
idByType.put(APPLICATION_RTF, (short) 5);
idByType.put(APPLICATION_ZIP, (short) 6);
idByType.put(IMAGE_GIF, (short) 7);
idByType.put(IMAGE_JPEG, (short) 8);
idByType.put(IMAGE_PNG, (short) 9);
idByType.put(TEXT_CSS, (short) 10);
idByType.put(TEXT_CSV, (short) 11);
idByType.put(APPLICATION_PROTOSTREAM, (short) 12);
idByType.put(TEXT_PLAIN, (short) 13);
idByType.put(TEXT_HTML, (short) 14);
idByType.put(APPLICATION_JBOSS_MARSHALLING, (short) 15);
idByType.put(APPLICATION_INFINISPAN_MARSHALLING, (short) 16);
idByType.put(APPLICATION_UNKNOWN, (short) 17);
idByType.forEach((key, value) -> typeById.put(value, key));
}
public static Short getId(MediaType mediaType) {
if (mediaType == null) return null;
return idByType.get(mediaType.withoutParameters());
}
public static MediaType getMediaType(Short id) {
return typeById.get(id);
}
}
| 2,841
| 43.40625
| 97
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/JavaSerializationEncoder.java
|
package org.infinispan.commons.dataconversion;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.marshall.JavaSerializationMarshaller;
/**
* Encoder based on the default java serialization.
*
* @since 9.1
* @deprecated Since 11.0, will be removed in 14.0. Set the storage media type and use transcoding instead.
*/
@Deprecated
public class JavaSerializationEncoder extends MarshallerEncoder {
public JavaSerializationEncoder(ClassAllowList classAllowList) {
super(new JavaSerializationMarshaller(classAllowList));
}
@Override
public MediaType getStorageFormat() {
return MediaType.APPLICATION_SERIALIZED_OBJECT;
}
@Override
public short id() {
return EncoderIds.JAVA_SERIALIZATION;
}
}
| 778
| 25.862069
| 107
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/DefaultTranscoder.java
|
package org.infinispan.commons.dataconversion;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.infinispan.commons.dataconversion.JavaStringCodec.BYTE_ARRAY;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_WWW_FORM_URLENCODED;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN;
import static org.infinispan.commons.logging.Log.CONTAINER;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.util.Util;
/**
* Handle conversions between text/plain, url-encoded, java objects, and octet-stream contents.
*
* @since 9.2
*/
public final class DefaultTranscoder extends AbstractTranscoder {
private static final Set<MediaType> supportedTypes = new HashSet<>();
private final Marshaller marshaller;
public DefaultTranscoder(Marshaller marshaller) {
this.marshaller = marshaller;
}
static {
supportedTypes.add(APPLICATION_OBJECT);
supportedTypes.add(APPLICATION_OCTET_STREAM);
supportedTypes.add(APPLICATION_WWW_FORM_URLENCODED);
supportedTypes.add(TEXT_PLAIN);
}
@Override
public Object doTranscode(Object content, MediaType contentType, MediaType destinationType) {
try {
if (destinationType.match(APPLICATION_OCTET_STREAM)) {
return convertToOctetStream(content, contentType, destinationType);
}
if (destinationType.match(APPLICATION_OBJECT)) {
return convertToObject(content, contentType, destinationType);
}
if (destinationType.match(TEXT_PLAIN)) {
return convertToTextPlain(content, contentType, destinationType);
}
if (destinationType.match(APPLICATION_WWW_FORM_URLENCODED)) {
return content;
}
throw CONTAINER.unsupportedConversion(Util.toStr(content), contentType, destinationType);
} catch (EncodingException | InterruptedException | IOException | ClassNotFoundException e) {
throw CONTAINER.errorTranscoding(Util.toStr(content), contentType, destinationType, e);
}
}
private Object convertToTextPlain(Object content, MediaType contentType, MediaType destinationType) {
if (contentType.match(APPLICATION_OCTET_STREAM)) {
return StandardConversions.convertCharset(content, UTF_8, destinationType.getCharset());
}
if (contentType.match(APPLICATION_OBJECT)) {
if (content instanceof byte[]) {
return StandardConversions.convertCharset(content, StandardCharsets.UTF_8, destinationType.getCharset());
} else {
return content.toString().getBytes(destinationType.getCharset());
}
}
if (contentType.match(TEXT_PLAIN)) {
return StandardConversions.convertTextToText(content, contentType, destinationType);
}
if (contentType.match(APPLICATION_WWW_FORM_URLENCODED)) {
return content;
}
throw CONTAINER.unsupportedConversion(Util.toStr(content), contentType, destinationType);
}
private Object convertToObject(Object content, MediaType contentType, MediaType destinationType) throws IOException, ClassNotFoundException {
if (contentType.match(APPLICATION_OCTET_STREAM)) {
String classType = destinationType.getClassType();
if (classType != null && !(classType.startsWith("java.lang") || classType.equals(BYTE_ARRAY.getName()))) {
Object unmarshalled = marshaller.objectFromByteBuffer((byte[]) content);
if (unmarshalled.getClass().getName().equals(classType)) {
return unmarshalled;
}
} else {
return content;
}
}
if (contentType.match(APPLICATION_OBJECT)) {
return content;
}
if (contentType.match(TEXT_PLAIN)) {
return StandardConversions.convertTextToObject(content, contentType);
}
if (contentType.match(APPLICATION_WWW_FORM_URLENCODED)) {
return content instanceof byte[] ? new String((byte[]) content, destinationType.getCharset()) : content.toString();
}
throw CONTAINER.unsupportedConversion(Util.toStr(content), contentType, destinationType);
}
public Object convertToOctetStream(Object content, MediaType contentType, MediaType destinationType) throws IOException, InterruptedException {
if (contentType.match(APPLICATION_OBJECT)) {
if (content instanceof byte[]) return content;
if (content instanceof String) {
return content.toString().getBytes(UTF_8);
}
return marshaller.objectToByteBuffer(content);
}
return content;
}
@Override
public Set<MediaType> getSupportedMediaTypes() {
return supportedTypes;
}
private boolean in(MediaType mediaType, Set<MediaType> set) {
return set.stream().anyMatch(s -> s.match(mediaType));
}
@Override
public boolean supportsConversion(MediaType mediaType, MediaType other) {
return in(mediaType, supportedTypes) && in(other, supportedTypes);
}
}
| 5,342
| 39.78626
| 146
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/BinaryTranscoder.java
|
package org.infinispan.commons.dataconversion;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_UNKNOWN;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_WWW_FORM_URLENCODED;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN;
import static org.infinispan.commons.logging.Log.CONTAINER;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.util.Util;
/**
* Handle conversions for the generic binary format 'application/unknown' that is assumed when no MediaType is specified.
*
* This transcoder will not perform any conversion in the data, except those performed by {@link MediaTypeCodec} and
* for {@link MediaType#APPLICATION_OBJECT} it will use the default marshaller present in the server.
*
* @since 10.0
* @deprecated since 13.0. Will be removed in a future version together with {@link MediaType#APPLICATION_UNKNOWN}.
*/
@Deprecated
public final class BinaryTranscoder extends OneToManyTranscoder {
private final AtomicReference<Marshaller> marshallerRef;
public BinaryTranscoder(Marshaller marshaller) {
super(APPLICATION_UNKNOWN, APPLICATION_OBJECT, APPLICATION_OCTET_STREAM, APPLICATION_WWW_FORM_URLENCODED, TEXT_PLAIN);
this.marshallerRef = new AtomicReference<>(marshaller);
}
public void overrideMarshaller(Marshaller marshaller) {
marshallerRef.set(marshaller);
}
private Marshaller getMarshaller() {
return marshallerRef.get();
}
@Override
public Object doTranscode(Object content, MediaType contentType, MediaType destinationType) {
try {
if (destinationType.match(APPLICATION_OBJECT)) {
return getMarshaller().objectFromByteBuffer((byte[]) content);
}
if (contentType.match(APPLICATION_OBJECT)) {
content = getMarshaller().objectToByteBuffer(content);
}
return content;
} catch (ClassCastException | IOException | EncodingException | ClassNotFoundException | InterruptedException e) {
throw CONTAINER.errorTranscoding(Util.toStr(content), contentType, destinationType, e);
}
}
}
| 2,416
| 39.283333
| 124
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/OneToManyTranscoder.java
|
package org.infinispan.commons.dataconversion;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* Base class for {@link Transcoder} that converts between a single format and multiple other formats and back.
*/
public abstract class OneToManyTranscoder extends AbstractTranscoder {
protected final MediaType mainType;
protected final Set<MediaType> supportedTypes = new HashSet<>();
public OneToManyTranscoder(MediaType mainType, MediaType... supportedConversions) {
this.mainType = mainType;
this.supportedTypes.add(mainType);
Collections.addAll(supportedTypes, supportedConversions);
}
private boolean in(MediaType mediaType, Set<MediaType> set) {
return set.stream().anyMatch(s -> s.match(mediaType));
}
@Override
public Set<MediaType> getSupportedMediaTypes() {
return supportedTypes;
}
@Override
public boolean supportsConversion(MediaType mediaType, MediaType other) {
return mediaType.match(mainType) && in(other, supportedTypes) ||
other.match(mainType) && in(mediaType, supportedTypes);
}
}
| 1,127
| 28.684211
| 111
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/IdentityWrapper.java
|
package org.infinispan.commons.dataconversion;
/**
* A wrapper that does not change the content.
*/
public class IdentityWrapper implements Wrapper {
public static final IdentityWrapper INSTANCE = new IdentityWrapper();
private IdentityWrapper() {
}
@Override
public Object wrap(Object obj) {
return obj;
}
@Override
public Object unwrap(Object obj) {
return obj;
}
@Override
public byte id() {
return WrapperIds.IDENTITY_WRAPPER;
}
@Override
public boolean isFilterable() {
return true;
}
}
| 570
| 16.30303
| 72
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/Wrapper.java
|
package org.infinispan.commons.dataconversion;
/**
* A Wrapper is used to decorate objects produced by the {@link Encoder}.
* A Wrapper, contrary to the Encoder, does not cause data conversion and it's used to provide additional
* behaviour to the encoded data such as equality/hashCode and indexing capabilities.
*
* @since 9.1
*/
public interface Wrapper {
Object wrap(Object obj);
Object unwrap(Object obj);
byte id();
/**
* @return true if the wrapped format is suitable to be indexed or filtered, thus avoiding extra unwrapping.
*/
boolean isFilterable();
}
| 598
| 23.958333
| 111
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/MediaType.java
|
package org.infinispan.commons.dataconversion;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.stream;
import static java.util.Collections.emptyMap;
import static org.infinispan.commons.dataconversion.JavaStringCodec.BYTE_ARRAY;
import static org.infinispan.commons.logging.Log.CONTAINER;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.marshall.Externalizer;
import org.infinispan.commons.marshall.ProtoStreamTypeIds;
import org.infinispan.commons.marshall.SerializeWith;
import org.infinispan.commons.util.Immutables;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoTypeId;
/**
* Represent a content type with optional parameters.
*
* @since 9.2
*/
@ProtoTypeId(ProtoStreamTypeIds.MEDIA_TYPE)
@SerializeWith(value = MediaType.MediaTypeExternalizer.class)
public final class MediaType {
private static final Pattern TREE_PATTERN;
private static final Pattern LIST_SEPARATOR_PATTERN;
static {
// Adapted from https://stackoverflow.com/a/48046041/55870
// See also https://tools.ietf.org/html/rfc7231#section-3.1.1.1
// and https://tools.ietf.org/html/rfc7230#section-3.2.6
// Extended to support "*" as a media type (as used by java.net.HttpURLConnection)
// More details at https://bugs.openjdk.java.net/browse/JDK-8163921
// Use PrintPattern.main(new String(TREE_PATTERN.toString()) to view the regex structure
String ows = "[ \t]*";
// Expand ranges in token pattern so that it uses the ASCII-only BitClass for matching
String token = "[!#$%&'*+.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz^_`|~-]+";
String quotedString = "\"(?:[^\"\\\\]|\\\\.)*\"";
String typeSubtype = ows + "((" + token + ")/" + token + "|\\*)" + ows;
String parameter = ";" + ows + "(" + token + ")=(" + token + "|" + quotedString + ")" + ows;
String listSeparator = "\\G," + ows;
String tree = "^" + typeSubtype + "|\\G" + parameter + "|\\G" + listSeparator;
TREE_PATTERN = Pattern.compile(tree, Pattern.DOTALL);
LIST_SEPARATOR_PATTERN = Pattern.compile(listSeparator, Pattern.DOTALL);
}
// OpenMetrics aka Prometheus content type
public static final String APPLICATION_OPENMETRICS_TYPE = "application/openmetrics-text";
public static final String APPLICATION_JAVASCRIPT_TYPE = "application/javascript";
public static final String APPLICATION_JSON_TYPE = "application/json";
public static final String APPLICATION_OCTET_STREAM_TYPE = "application/octet-stream";
public static final String APPLICATION_OBJECT_TYPE = "application/x-java-object";
public static final String APPLICATION_PDF_TYPE = "application/pdf";
public static final String APPLICATION_RTF_TYPE = "application/rtf";
public static final String APPLICATION_SERIALIZED_OBJECT_TYPE = "application/x-java-serialized-object";
public static final String APPLICATION_XML_TYPE = "application/xml";
public static final String APPLICATION_YAML_TYPE = "application/yaml";
public static final String APPLICATION_ZIP_TYPE = "application/zip";
public static final String APPLICATION_JBOSS_MARSHALLING_TYPE = "application/x-jboss-marshalling";
public static final String APPLICATION_PROTOSTREAM_TYPE = "application/x-protostream";
/**
* @deprecated Since 11.0, without replacement.
*/
@Deprecated
public static final String APPLICATION_UNKNOWN_TYPE = "application/unknown";
public static final String WWW_FORM_URLENCODED_TYPE = "application/x-www-form-urlencoded";
public static final String IMAGE_GIF_TYPE = "image/gif";
public static final String IMAGE_JPEG_TYPE = "image/jpeg";
public static final String IMAGE_PNG_TYPE = "image/png";
public static final String MULTIPART_FORM_DATA_TYPE = "multipart/form-data";
public static final String TEXT_CSS_TYPE = "text/css";
public static final String TEXT_CSV_TYPE = "text/csv";
public static final String TEXT_PLAIN_TYPE = "text/plain";
public static final String TEXT_HTML_TYPE = "text/html";
public static final String TEXT_EVENT_STREAM_TYPE = "text/event-stream";
/**
* @deprecated Since 11.0, will be removed with ISPN-9622
*/
@Deprecated
public static final String APPLICATION_INFINISPAN_MARSHALLING_TYPE = "application/x-infinispan-marshalling";
/**
* @deprecated Since 11.0, will be removed in 14.0. No longer used for BINARY storage.
*/
@Deprecated
public static final String APPLICATION_INFINISPAN_BINARY_TYPE = "application/x-infinispan-binary";
public static final String MATCH_ALL_TYPE = "*/*";
// OpenMetrics aka Prometheus content type
public static final MediaType APPLICATION_OPENMETRICS = fromString(APPLICATION_OPENMETRICS_TYPE);
public static final MediaType APPLICATION_JAVASCRIPT = fromString(APPLICATION_JAVASCRIPT_TYPE);
public static final MediaType APPLICATION_JSON = fromString(APPLICATION_JSON_TYPE);
public static final MediaType APPLICATION_OCTET_STREAM = fromString(APPLICATION_OCTET_STREAM_TYPE);
public static final MediaType APPLICATION_OBJECT = fromString(APPLICATION_OBJECT_TYPE);
public static final MediaType APPLICATION_SERIALIZED_OBJECT = fromString(APPLICATION_SERIALIZED_OBJECT_TYPE);
public static final MediaType APPLICATION_XML = fromString(APPLICATION_XML_TYPE);
public static final MediaType APPLICATION_YAML = fromString(APPLICATION_YAML_TYPE);
public static final MediaType APPLICATION_PROTOSTREAM = fromString(APPLICATION_PROTOSTREAM_TYPE);
public static final MediaType APPLICATION_JBOSS_MARSHALLING = fromString(APPLICATION_JBOSS_MARSHALLING_TYPE);
/**
* @deprecated Since 11.0, will be removed with ISPN-9622
*/
@Deprecated
public static final MediaType APPLICATION_INFINISPAN_MARSHALLED = fromString(APPLICATION_INFINISPAN_MARSHALLING_TYPE);
public static final MediaType APPLICATION_WWW_FORM_URLENCODED = fromString(WWW_FORM_URLENCODED_TYPE);
public static final MediaType IMAGE_PNG = fromString(IMAGE_PNG_TYPE);
public static final MediaType MULTIPART_FORM_DATA = fromString(MULTIPART_FORM_DATA_TYPE);
public static final MediaType TEXT_PLAIN = fromString(TEXT_PLAIN_TYPE);
public static final MediaType TEXT_CSS = fromString(TEXT_CSS_TYPE);
public static final MediaType TEXT_CSV = fromString(TEXT_CSV_TYPE);
public static final MediaType TEXT_HTML = fromString(TEXT_HTML_TYPE);
public static final MediaType IMAGE_GIF = fromString(IMAGE_GIF_TYPE);
public static final MediaType IMAGE_JPEG = fromString(IMAGE_JPEG_TYPE);
public static final MediaType TEXT_EVENT_STREAM = fromString(TEXT_EVENT_STREAM_TYPE);
/**
* @deprecated Since 11.0, will be removed in 14.0. No longer used for BINARY storage.
*/
@Deprecated
public static final MediaType APPLICATION_INFINISPAN_BINARY = fromString(APPLICATION_INFINISPAN_BINARY_TYPE);
public static final MediaType APPLICATION_PDF = fromString(APPLICATION_PDF_TYPE);
public static final MediaType APPLICATION_RTF = fromString(APPLICATION_RTF_TYPE);
public static final MediaType APPLICATION_ZIP = fromString(APPLICATION_ZIP_TYPE);
/**
* @deprecated Since 11.0, will be removed with ISPN-9622
*/
@Deprecated
public static final MediaType APPLICATION_INFINISPAN_MARSHALLING = fromString(APPLICATION_INFINISPAN_MARSHALLING_TYPE);
/**
* @deprecated Since 11.0, without replacement.
*/
@Deprecated
public static final MediaType APPLICATION_UNKNOWN = fromString(APPLICATION_UNKNOWN_TYPE);
public static final MediaType MATCH_ALL = fromString(MATCH_ALL_TYPE);
@Deprecated
public static final String BYTE_ARRAY_TYPE = BYTE_ARRAY.getName();
private static final String WEIGHT_PARAM_NAME = "q";
private static final String CHARSET_PARAM_NAME = "charset";
private static final String CLASS_TYPE_PARAM_NAME = "type";
private static final String ENCODING_PARAM_NAME = "encoding";
private static final double DEFAULT_WEIGHT = 1.0;
private static final Charset DEFAULT_CHARSET = UTF_8;
public static final String HEX = "hex";
public static final String BASE_64 = "base64";
private final Map<String, String> params;
private final String typeSubtype;
private final int typeLength;
private final boolean matchesAll;
private final transient double weight;
public MediaType(String type, String subtype) {
this(type, subtype, emptyMap());
}
public MediaType(String type, String subtype, Map<String, String> params) {
this(type + "/" + subtype, type.length(), params);
}
public MediaType(String typeSubtype) {
this(typeSubtype, emptyMap());
}
public MediaType(String typeSubType, Map<String, String> params) {
this(typeSubType, validate(typeSubType), params);
}
private MediaType(String typeSubType, int typeLength, Map<String, String> params) {
this.typeSubtype = typeSubType;
this.typeLength = typeLength;
this.matchesAll = typeSubtype.equals(MATCH_ALL_TYPE);
if (params != null) {
this.params = Immutables.immutableMapCopy(params);
String weight = params.get(WEIGHT_PARAM_NAME);
this.weight = weight != null ? parseWeight(weight) : DEFAULT_WEIGHT;
} else {
this.params = emptyMap();
this.weight = DEFAULT_WEIGHT;
}
}
@ProtoField(1)
String getTree() {
return toString();
}
/**
* @deprecated replaced by {@link #fromString}
*/
@Deprecated
public static MediaType parse(String str) {
return fromString(str);
}
@ProtoFactory
public static MediaType fromString(String tree) {
if (tree == null || tree.isEmpty()) throw CONTAINER.missingMediaType();
Matcher matcher = TREE_PATTERN.matcher(tree);
return parseSingleMediaType(tree, matcher, false);
}
private static MediaType parseSingleMediaType(String input, Matcher matcher, boolean isList) {
if (!matcher.lookingAt() || matcher.start(1) < 0) {
throw CONTAINER.invalidMediaTypeSubtype(input);
}
String typeSubtype;
int typeLength;
if (matcher.start(2) >= 0) {
// group 1 is the full type+subtype, group 2 is the type
typeSubtype = matcher.group(1);
typeLength = matcher.end(2) - matcher.start(2);
} else {
// group 1 is "*"
typeSubtype = MATCH_ALL_TYPE;
typeLength = 1;
}
Map<String, String> paramMap = null;
String firstParamName = null;
String firstParamValue = null;
while (matcher.end() < input.length()) {
// find() doesn't skip any characters because of the \G
if (!matcher.find()) {
throw CONTAINER.invalidMediaTypeParam(input, input.substring(matcher.regionStart()));
}
// Groups 1 and 2 are only valid during the first match because of the ^
String paramName = matcher.group(3);
String paramValue = matcher.group(4);
if (paramName == null) {
// The comma alternative matched
if (!isList) {
throw CONTAINER.invalidMediaTypeSubtype(input);
} else if (matcher.end() < input.length()) {
// parseSingleMediaType will be called again
break;
} else {
throw CONTAINER.invalidMediaTypeListCommaAtEnd(input);
}
}
if (firstParamName == null) {
firstParamName = paramName;
firstParamValue = paramValue;
} else {
if (paramMap == null) {
paramMap = new HashMap<>();
}
paramMap.put(firstParamName, firstParamValue);
paramMap.put(paramName, paramValue);
}
}
if (paramMap == null && firstParamName != null) {
paramMap = Collections.singletonMap(firstParamName, firstParamValue);
}
return new MediaType(typeSubtype, typeLength, paramMap);
}
/**
* Parse a comma separated list of media type trees.
*/
public static Stream<MediaType> parseList(String mediaTypeList) {
if (mediaTypeList == null || mediaTypeList.isEmpty()) throw CONTAINER.missingMediaType();
Matcher matcher = TREE_PATTERN.matcher(mediaTypeList);
List<MediaType> list = new ArrayList<>();
while (true) {
MediaType mediaType = parseSingleMediaType(mediaTypeList, matcher, true);
list.add(mediaType);
if (matcher.end() == mediaTypeList.length())
break;
matcher.region(matcher.end(), mediaTypeList.length());
}
list.sort(Comparator.comparingDouble(MediaType::getWeight).reversed());
return list.stream();
}
private static double parseWeight(String weightValue) {
try {
return Double.parseDouble(weightValue);
} catch (NumberFormatException nf) {
throw CONTAINER.invalidWeight(weightValue);
}
}
public static MediaType fromExtension(String name) {
int last = name.lastIndexOf('.');
String extension = last < 0 ? name : name.substring(last + 1);
switch (extension) {
case "xml":
return APPLICATION_XML;
case "yaml":
case "yml":
return APPLICATION_YAML;
case "json":
return APPLICATION_JSON;
default:
Log.CONFIG.tracef("Unknown extension: %s", name);
return null;
}
}
public boolean match(MediaType other) {
if (other == this)
return true;
return other != null && (other.matchesAll() || this.matchesAll() || other.typeSubtype.equals(this.typeSubtype));
}
public boolean matchesAll() {
return matchesAll;
}
public String getTypeSubtype() {
return typeSubtype;
}
public MediaType withoutParameters() {
if (params.isEmpty()) return this;
return new MediaType(typeSubtype);
}
public double getWeight() {
return weight;
}
public Charset getCharset() {
return getParameter(CHARSET_PARAM_NAME).map(Charset::forName).orElse(DEFAULT_CHARSET);
}
public String getClassType() {
return getParameter(CLASS_TYPE_PARAM_NAME).orElse(null);
}
public MediaType withClassType(Class<?> clazz) {
return withParameter(CLASS_TYPE_PARAM_NAME, clazz.getName());
}
public MediaType withEncoding(String enc) {
return withParameter(ENCODING_PARAM_NAME, enc);
}
public String getEncoding() {
return getParameter(ENCODING_PARAM_NAME).orElse(null);
}
public boolean hasStringType() {
String classType = getClassType();
return classType != null && classType.equals(String.class.getName());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MediaType mediaType = (MediaType) o;
return params.equals(mediaType.params) && typeSubtype.equals(mediaType.typeSubtype);
}
@Override
public int hashCode() {
int result = params.hashCode();
result = 31 * result + typeSubtype.hashCode();
return result;
}
public String getType() {
return typeSubtype.substring(0, typeLength);
}
public String getSubType() {
return typeSubtype.substring(typeLength + 1);
}
public boolean hasParameters() {
return !params.isEmpty();
}
public Optional<String> getParameter(String name) {
return Optional.ofNullable(params.get(name));
}
public Map<String, String> getParameters() {
return Collections.unmodifiableMap(params);
}
public MediaType withParameters(Map<String, String> parameters) {
return parameters.isEmpty() ? this : new MediaType(this.typeSubtype, parameters);
}
private static int validate(String typeSubtype) {
if (typeSubtype == null) throw new NullPointerException("type and subtype cannot be null");
Matcher matcher = TREE_PATTERN.matcher(typeSubtype);
if (!matcher.matches())
throw CONTAINER.invalidMediaTypeSubtype(typeSubtype);
return matcher.end(2);
}
public MediaType withCharset(Charset charset) {
return withParameter(CHARSET_PARAM_NAME, charset.toString());
}
public MediaType withParameter(String name, String value) {
Map<String, String> newParams = new HashMap<>(params);
newParams.put(name, value);
return new MediaType(typeSubtype, newParams);
}
/**
* @deprecated Use {@link #getParameters()} and {@link #getTypeSubtype()} to build a custom String representation.
*/
@Deprecated
public String toStringExcludingParam(String... params) {
if (!hasParameters()) return typeSubtype;
StringBuilder builder = new StringBuilder().append(typeSubtype);
String strParams = this.params.entrySet().stream()
.filter(e -> stream(params).noneMatch(p -> p.equals(e.getKey())))
.map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining("; "));
if (strParams.isEmpty()) return builder.toString();
return builder.append("; ").append(strParams).toString();
}
/**
* @return true if the MediaType's java type is a byte array.
*/
public boolean isBinary() {
String customType = getClassType();
if (customType == null) return !this.match(MediaType.APPLICATION_OBJECT);
return BYTE_ARRAY.getName().equals(customType);
}
@Override
public String toString() {
if (!hasParameters()) return typeSubtype;
StringBuilder builder = new StringBuilder().append(typeSubtype);
String strParams = this.params.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining("; "));
return builder.append("; ").append(strParams).toString();
}
public static final class MediaTypeExternalizer implements Externalizer<MediaType> {
@Override
public void writeObject(ObjectOutput output, MediaType mediaType) throws IOException {
Short id = MediaTypeIds.getId(mediaType);
if (id == null) {
output.writeBoolean(false);
output.writeUTF(mediaType.typeSubtype);
output.writeObject(mediaType.params);
} else {
output.writeBoolean(true);
output.writeShort(id);
output.writeObject(mediaType.params);
}
}
@Override
@SuppressWarnings("unchecked")
public MediaType readObject(ObjectInput input) throws IOException, ClassNotFoundException {
boolean isInternal = input.readBoolean();
if (isInternal) {
short id = input.readShort();
Map<String, String> params = (Map<String, String>) input.readObject();
return MediaTypeIds.getMediaType(id).withParameters(params);
} else {
String typeSubType = input.readUTF();
Map<String, String> params = (Map<String, String>) input.readObject();
return new MediaType(typeSubType, params);
}
}
}
}
| 19,618
| 37.849505
| 122
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/Base16Codec.java
|
package org.infinispan.commons.dataconversion;
public final class Base16Codec {
private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
private Base16Codec() {
}
public static String encode(byte[] content) {
return bytesToHex(content);
}
public static byte[] decode(String content) {
return hexToBytes(content);
}
private static String bytesToHex(byte[] bytes) {
if (bytes == null) return null;
if (bytes.length == 0) return "";
StringBuilder r = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
r.append(HEX_DIGITS[b >> 4 & 0x0f]);
r.append(HEX_DIGITS[b & 0x0f]);
}
return "0x" + r;
}
private static int forDigit(char digit) {
if (digit >= '0' && digit <= '9') return digit - 48;
if (digit == 'a') return 10;
if (digit == 'b') return 11;
if (digit == 'c') return 12;
if (digit == 'd') return 13;
if (digit == 'e') return 14;
if (digit == 'f') return 15;
throw new EncodingException("Invalid digit found in hex format!");
}
private static byte[] hexToBytes(String hex) {
if (hex == null) return null;
if (hex.isEmpty()) return new byte[]{};
if (!hex.startsWith("0x") || hex.length() % 2 != 0) {
throw new EncodingException("Illegal hex literal!");
}
byte[] result = new byte[(hex.length() - 2) / 2];
for (int i = 2; i < hex.length(); i += 2) {
int msb = forDigit(hex.charAt(i));
int lsb = forDigit(hex.charAt(i + 1));
byte b = (byte) (msb * 16 + lsb);
result[(i - 2) / 2] = b;
}
return result;
}
}
| 1,683
| 28.54386
| 77
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/EncoderIds.java
|
package org.infinispan.commons.dataconversion;
/**
* @since 9.2
* @deprecated since 12.1, to be removed in a future version.
*/
@Deprecated
public interface EncoderIds {
short NO_ENCODER = 0;
short IDENTITY = 1;
short BINARY = 2;
short UTF8 = 3;
/**
* @deprecated Since 11.0, will be removed with ISPN-9622
*/
@Deprecated
short GLOBAL_MARSHALLER = 4;
/**
* @deprecated Since 11.0, will be removed in 14.0. Set the storage media type and use transcoding instead.
*/
@Deprecated
short GENERIC_MARSHALLER = 5;
/**
* @deprecated Since 11.0, will be removed in 14.0. Set the storage media type and use transcoding instead.
*/
@Deprecated
short JAVA_SERIALIZATION = 6;
}
| 732
| 24.275862
| 110
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/JavaMediaTypeCodec.java
|
package org.infinispan.commons.dataconversion;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
/**
* Encodes/decodes Java primitives, byte arrays and String as text.
*
* <br/> It only applies to {@link MediaType#APPLICATION_OBJECT} content with a "type" parameter.
*
* The following values are supported for the "type" param:
* <br/>
* <ul>
* <li>java.lang.String</li>
* <li>java.lang.String</li>
* <li>java.lang.Boolean</li>
* <li>java.lang.Short</li>
* <li>java.lang.Byte</li>
* <li>java.lang.Integer</li>
* <li>java.lang.Long</li>
* <li>java.lang.Float</li>
* <li>java.lang.Double</li>
* <li>ByteArray</li>
* </ul>
*
* When "ByteArray" is used, it implies the content is encoded as a <a href="https://www.ietf.org/rfc/rfc4648.txt">RFC 4648</a>
* hexadecimal prefixed by "0x". For all other supported types, it will use {@link Object#toString()}.
*
* @since 13.0
*/
class JavaMediaTypeCodec implements MediaTypeCodec {
@Override
public Object decodeContent(Object content, MediaType contentType) {
String type = contentType.getClassType();
if (!contentType.match(APPLICATION_OBJECT) || type == null) {
return content;
}
String strContent;
if (content instanceof byte[]) {
strContent = new String((byte[]) content, contentType.getCharset());
} else if (content instanceof String) {
strContent = content.toString();
} else {
return content;
}
if (content.getClass().getName().equals(type)) {
return content;
}
JavaStringCodec codec = JavaStringCodec.forType(type);
if (codec == null) {
throw new EncodingException("Type " + type + " is unsupported");
}
return codec.decode(strContent);
}
@Override
public Object encodeContent(Object content, MediaType destinationType) {
String type = destinationType.getClassType();
if (!destinationType.match(APPLICATION_OBJECT) || type == null) {
return content;
}
if (content.getClass().getName().equals(type)) {
return content;
}
JavaStringCodec codec = JavaStringCodec.forType(type);
return codec.encode(content, destinationType);
}
}
| 2,282
| 32.086957
| 127
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/EncodingUtils.java
|
package org.infinispan.commons.dataconversion;
/**
* Utilities to encode/decode keys and values from caches.
*
* @since 9.1
* @deprecated Use the org.infinispan.encoding.DataConversion obtained from the AdvancedCache.
*/
public final class EncodingUtils {
private EncodingUtils() {
}
/**
* Decode object from storage format.
*
* @param stored Object in the storage format.
* @param encoder the {@link Encoder} used for data conversion.
* @param wrapper the {@link Wrapper} used to decorate the converted data.
* @return Object decoded and unwrapped.
*/
public static Object fromStorage(Object stored, Encoder encoder, Wrapper wrapper) {
if (encoder == null || wrapper == null) {
throw new IllegalArgumentException("Both Encoder and Wrapper must be provided!");
}
if (stored == null) return null;
return encoder.fromStorage(wrapper.unwrap(stored));
}
/**
* Encode object to storage format.
*
* @param toStore Object to be encoded.
* @param encoder the {@link Encoder} used for data conversion.
* @param wrapper the {@link Wrapper} used to decorate the converted data.
* @return Object decoded and unwrapped.
*/
public static Object toStorage(Object toStore, Encoder encoder, Wrapper wrapper) {
if (encoder == null || wrapper == null) {
throw new IllegalArgumentException("Both Encoder and Wrapper must be provided!");
}
if (toStore == null) return null;
return wrapper.wrap(encoder.toStorage(toStore));
}
}
| 1,563
| 33
| 94
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/StandardConversions.java
|
package org.infinispan.commons.dataconversion;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Base64.getUrlDecoder;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_WWW_FORM_URLENCODED;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE;
import static org.infinispan.commons.logging.Log.CONTAINER;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.protostream.ImmutableSerializationContext;
import org.infinispan.protostream.ProtobufUtil;
/**
* Utilities to convert between text/plain, octet-stream, java-objects and url-encoded contents.
*
* @since 9.2
*/
public final class StandardConversions {
/**
* Convert text content to a different encoding.
*
* @param source The source content.
* @param sourceType MediaType for the source content.
* @param destinationType the MediaType of the converted content.
* @return content conforming to the destination MediaType.
*/
public static Object convertTextToText(Object source, MediaType sourceType, MediaType destinationType) {
if (source == null) return null;
if (sourceType == null) throw new NullPointerException("MediaType cannot be null!");
if (!sourceType.match(MediaType.TEXT_PLAIN))
throw CONTAINER.invalidMediaType(TEXT_PLAIN_TYPE, sourceType.toString());
boolean asString = destinationType.hasStringType();
Charset sourceCharset = sourceType.getCharset();
Charset destinationCharset = destinationType.getCharset();
if (sourceCharset.equals(destinationCharset)) return convertTextClass(source, destinationType, asString);
byte[] byteContent = source instanceof byte[] ? (byte[]) source : source.toString().getBytes(sourceCharset);
return convertTextClass(convertCharset(byteContent, sourceCharset, destinationCharset), destinationType, asString);
}
private static Object convertTextClass(Object text, MediaType destination, boolean asString) {
if (asString) {
return text instanceof byte[] ? new String((byte[]) text, destination.getCharset()) : text.toString();
}
return text instanceof byte[] ? text : text.toString().getBytes(destination.getCharset());
}
/**
* Converts text content to binary.
*
* @param source The source content.
* @param sourceType MediaType for the source content.
* @return content converted as octet-stream represented as byte[].
* @throws EncodingException if the source cannot be interpreted as plain text.
*
* @deprecated Since 13.0, without replacement.
*/
@Deprecated
public static byte[] convertTextToOctetStream(Object source, MediaType sourceType) {
if (source == null) return null;
if (sourceType == null) {
throw new NullPointerException("MediaType cannot be null!");
}
if (source instanceof byte[]) return (byte[]) source;
return source.toString().getBytes(sourceType.getCharset());
}
/**
* Converts text content to the Java representation (String).
*
* @param source The source content
* @param sourceType the MediaType of the source content.
* @return String representation of the text content.
* @throws EncodingException if the source cannot be interpreted as plain text.
*/
public static String convertTextToObject(Object source, MediaType sourceType) {
if (source == null) return null;
if (source instanceof String) return source.toString();
if (source instanceof byte[]) {
byte[] bytesSource = (byte[]) source;
return new String(bytesSource, sourceType.getCharset());
}
throw CONTAINER.invalidTextContent(source);
}
/**
* Convert text format to a URL safe format.
*
* @param source the source text/plain content.
* @param sourceType the MediaType of the source content.
* @return a String with the content URLEncoded.
* @throws EncodingException if the source format cannot be interpreted as plain/text.
*
* @deprecated Since 13.0, without replacement.
*/
@Deprecated
public static String convertTextToUrlEncoded(Object source, MediaType sourceType) {
return urlEncode(source, sourceType);
}
/**
* Converts generic byte[] to text.
*
* @param source byte[] to convert.
* @param destination MediaType of the desired text conversion.
* @return byte[] content interpreted as text, in the encoding specified by the destination MediaType.
*
* @deprecated Since 13.0, without replacment.
*/
@Deprecated
public static byte[] convertOctetStreamToText(byte[] source, MediaType destination) {
if (source == null) return null;
return convertCharset(source, UTF_8, destination.getCharset());
}
/**
* Converts an octet stream to a Java object
*
* @param source The source to convert
* @param destination The type of the converted object.
* @return an instance of a java object compatible with the supplied destination type.
*
* @deprecated Since 13.0, without replacement.
*/
@Deprecated
public static Object convertOctetStreamToJava(byte[] source, MediaType destination, Marshaller marshaller) {
if (source == null) return null;
if (!destination.match(MediaType.APPLICATION_OBJECT)) {
throw CONTAINER.invalidMediaType(APPLICATION_OBJECT_TYPE, destination.toString());
}
String classType = destination.getClassType();
if (classType == null) return source;
if (classType.equals("ByteArray")) {
return source;
}
if (destination.hasStringType()) {
return new String(source, UTF_8);
}
try {
return marshaller.objectFromByteBuffer(source);
} catch (IOException | IllegalStateException | ClassNotFoundException e) {
throw CONTAINER.conversionNotSupported(source, MediaType.APPLICATION_OCTET_STREAM_TYPE, destination.toString());
}
}
/**
* Converts a java object to a sequence of bytes applying standard java serialization.
*
* @param source source the java object to convert.
* @param sourceMediaType the MediaType matching application/x-application-object describing the source.
* @return byte[] representation of the java object.
* @throws EncodingException if the sourceMediaType is not a application/x-java-object or if the conversion is
* not supported.
*
* @deprecated Since 13.0, with no replacement.
*/
@Deprecated
public static byte[] convertJavaToOctetStream(Object source, MediaType sourceMediaType, Marshaller marshaller) throws IOException, InterruptedException {
if (source == null) return null;
if (!sourceMediaType.match(MediaType.APPLICATION_OBJECT)) {
throw new EncodingException("sourceMediaType not conforming to application/x-java-object!");
}
return marshaller.objectToByteBuffer(decodeObjectContent(source, sourceMediaType));
}
/**
* Converts a java object to a sequence of bytes using a ProtoStream {@link ImmutableSerializationContext}.
*
* @param source source the java object to convert.
* @param sourceMediaType the MediaType matching application/x-application-object describing the source.
* @return byte[] representation of the java object.
* @throws EncodingException if the sourceMediaType is not a application/x-java-object or if the conversion is
* not supported.
*/
public static byte[] convertJavaToProtoStream(Object source, MediaType sourceMediaType, ImmutableSerializationContext ctx) throws IOException, InterruptedException {
if (source == null) return null;
if (!sourceMediaType.match(MediaType.APPLICATION_OBJECT)) {
throw new EncodingException("sourceMediaType not conforming to application/x-java-object!");
}
Object decoded = decodeObjectContent(source, sourceMediaType);
if (decoded instanceof byte[]) return (byte[]) decoded;
if (decoded instanceof String && isJavaString(sourceMediaType))
return ((String) decoded).getBytes(StandardCharsets.UTF_8);
return ProtobufUtil.toWrappedByteArray(ctx, source);
}
private static boolean isJavaString(MediaType mediaType) {
return mediaType.match(MediaType.APPLICATION_OBJECT) && mediaType.hasStringType();
}
/**
* Converts a java object to a text/plain representation.
* @param source Object to convert.
* @param sourceMediaType The MediaType for the source object.
* @param destinationMediaType The required text/plain specification.
* @return byte[] with the text/plain representation of the object with the requested charset.
*
* @deprecated Since 13.0 without replacement.
*/
@Deprecated
public static byte[] convertJavaToText(Object source, MediaType sourceMediaType, MediaType destinationMediaType) {
if (source == null) return null;
if (sourceMediaType == null || destinationMediaType == null) {
throw new NullPointerException("sourceMediaType and destinationMediaType cannot be null!");
}
Object decoded = decodeObjectContent(source, sourceMediaType);
if (decoded instanceof byte[]) {
return convertCharset(source, StandardCharsets.UTF_8, destinationMediaType.getCharset());
} else {
String asString = decoded.toString();
return asString.getBytes(destinationMediaType.getCharset());
}
}
/**
* Decode UTF-8 as a java object. For this conversion, the "type" parameter is used in the supplied {@link MediaType}.
*
* Currently supported types are primitives and String, plus a special "ByteArray" to describe a sequence of bytes.
*
* @param content The content to decode.
* @param contentMediaType the {@link MediaType} describing the content.
* @return instance of Object according to the supplied MediaType "type" parameter, or if no type is present,
* the object itself.
* @throws EncodingException if the provided type is not supported.
*
* @deprecated Since 13.0, without replacement.
*/
@Deprecated
public static Object decodeObjectContent(Object content, MediaType contentMediaType) {
if (content == null) return null;
if (contentMediaType == null) {
throw new NullPointerException("contentMediaType cannot be null!");
}
String strContent;
String type = contentMediaType.getClassType();
if (type == null) return content;
if (type.equals("ByteArray")) {
if (content instanceof byte[]) return content;
if (content instanceof String) return hexToBytes(content.toString());
throw new EncodingException("Cannot read ByteArray!");
}
if (content instanceof byte[]) {
strContent = new String((byte[]) content, UTF_8);
} else {
strContent = content.toString();
}
switch (type) {
case "java.lang.String":
return strContent;
case "java.lang.Boolean":
return Boolean.parseBoolean(strContent);
case "java.lang.Short":
return Short.parseShort(strContent);
case "java.lang.Byte":
return Byte.parseByte(strContent);
case "java.lang.Integer":
return Integer.parseInt(strContent);
case "java.lang.Long":
return Long.parseLong(strContent);
case "java.lang.Float":
return Float.parseFloat(strContent);
case "java.lang.Double":
return Double.parseDouble(strContent);
}
return content;
}
/**
* Convert text content.
*
* @param content Object to convert.
* @param fromCharset Charset of the provided content.
* @param toCharset Charset to convert to.
* @return byte[] with the content in the desired charset.
*/
public static byte[] convertCharset(Object content, Charset fromCharset, Charset toCharset) {
if (content == null) return null;
if (fromCharset == null || toCharset == null) {
throw new NullPointerException("Charset cannot be null!");
}
byte[] bytes;
if (content instanceof String) {
bytes = content.toString().getBytes(fromCharset);
} else if (content instanceof byte[]) {
bytes = (byte[]) content;
} else {
bytes = content.toString().getBytes(fromCharset);
}
if (fromCharset.equals(toCharset)) return bytes;
CharBuffer inputContent = fromCharset.decode(ByteBuffer.wrap(bytes));
ByteBuffer result = toCharset.encode(inputContent);
return Arrays.copyOf(result.array(), result.limit());
}
/**
* Decode a octet-stream content that is not a byte[]. For this, it uses a special
* param called "encoding" in the "application/octet-stream" MediaType.
* The "encoding" param supports only the "hex" value that represents an octet-stream
* as a hexadecimal representation, for example "0xdeadbeef".
*
* In the absence of the "encoding" param, it will assume base64 encoding.
*
* @param input Object representing the binary content.
* @param octetStream The MediaType describing the input.
* @return a byte[] with the decoded content.
*
* @deprecated Since 13.0, without replacement.
*/
@Deprecated
public static byte[] decodeOctetStream(Object input, MediaType octetStream) {
if (input == null) {
throw new NullPointerException("input must not be null");
}
if (input instanceof byte[]) return (byte[]) input;
if (input instanceof String) {
String encoding = octetStream.getParameter("encoding").orElse("hex");
String src = input.toString();
return encoding.equals("hex") ? hexToBytes(src) : getUrlDecoder().decode(src);
}
throw new EncodingException("Cannot decode binary content " + input.getClass());
}
private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
/**
* @deprecated Use {@link Base16Codec#encode(byte[])}
*/
@Deprecated
public static String bytesToHex(byte[] bytes) {
if (bytes == null) return null;
if (bytes.length == 0) return "";
StringBuilder r = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
r.append(HEX_DIGITS[b >> 4 & 0x0f]);
r.append(HEX_DIGITS[b & 0x0f]);
}
return "0x" + r.toString();
}
private static int forDigit(char digit) {
if (digit >= '0' && digit <= '9') return digit - 48;
if (digit == 'a') return 10;
if (digit == 'b') return 11;
if (digit == 'c') return 12;
if (digit == 'd') return 13;
if (digit == 'e') return 14;
if (digit == 'f') return 15;
throw new EncodingException("Invalid digit found in hex format!");
}
/**
* @deprecated Use {@link Base16Codec#decode(String)} instead.
*/
@Deprecated
public static byte[] hexToBytes(String hex) {
if (hex == null) return null;
if (hex.isEmpty()) return new byte[]{};
if (!hex.startsWith("0x") || hex.length() % 2 != 0) {
throw new EncodingException("Illegal hex literal!");
}
byte[] result = new byte[(hex.length() - 2) / 2];
for (int i = 2; i < hex.length(); i += 2) {
int msb = forDigit(hex.charAt(i));
int lsb = forDigit(hex.charAt(i + 1));
byte b = (byte) (msb * 16 + lsb);
result[(i - 2) / 2] = b;
}
return result;
}
/**
* Handle x-www-form-urlencoded as single values for now.
* Ideally it should generate a Map<String, String>
*
* @deprecated since 13.0 without replacement.
*/
@Deprecated
public static Object convertUrlEncodedToObject(Object content) {
Object decoded = urlDecode(content);
return convertTextToObject(decoded, TEXT_PLAIN);
}
/**
* @deprecated Since 13.0 without replacement.
*/
@Deprecated
public static Object convertUrlEncodedToText(Object content, MediaType destinationType) {
return convertTextToText(urlDecode(content), TEXT_PLAIN, destinationType);
}
/**
* @deprecated Since 13.0 without replacement.
*/
@Deprecated
public static Object convertUrlEncodedToOctetStream(Object content) {
return convertTextToOctetStream(urlDecode(content), TEXT_PLAIN);
}
/**
* @deprecated Since 13.0 without replacement.
*/
@Deprecated
public static String urlEncode(Object content, MediaType mediaType) {
if (content == null) return null;
try {
String asString;
if (content instanceof byte[]) {
asString = new String((byte[]) content, UTF_8);
} else {
asString = content.toString();
}
return URLEncoder.encode(asString, mediaType.getCharset().toString());
} catch (UnsupportedEncodingException e) {
throw CONTAINER.errorEncoding(content, APPLICATION_WWW_FORM_URLENCODED);
}
}
/**
* @deprecated Since 13.0, without replacement.
*/
@Deprecated
public static Object urlDecode(Object content) {
try {
if (content == null) return null;
if (content instanceof byte[]) {
byte[] bytesSource = (byte[]) content;
return URLDecoder.decode(new String(bytesSource, UTF_8), UTF_8.toString());
}
return URLDecoder.decode(content.toString(), UTF_8.toString());
} catch (UnsupportedEncodingException e) {
throw CONTAINER.cannotDecodeFormURLContent(content);
}
}
/**
* @deprecated Since 13.0 without replacement.
*/
@Deprecated
public static Object convertOctetStreamToUrlEncoded(Object content, MediaType contentType) {
byte[] decoded = decodeOctetStream(content, contentType);
return urlEncode(decoded, MediaType.TEXT_PLAIN);
}
}
| 18,354
| 38.388412
| 168
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/TranscoderMarshallerAdapter.java
|
package org.infinispan.commons.dataconversion;
import static org.infinispan.commons.logging.Log.CONTAINER;
import java.io.IOException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.util.Util;
/**
* Base class for transcoder between application/x-java-object and byte[] produced by a marshaller.
*
* @since 9.3
*/
public class TranscoderMarshallerAdapter extends OneToManyTranscoder {
protected final static Log logger = LogFactory.getLog(TranscoderMarshallerAdapter.class, Log.class);
private final Marshaller marshaller;
public TranscoderMarshallerAdapter(Marshaller marshaller) {
super(marshaller.mediaType(), MediaType.APPLICATION_OBJECT, MediaType.APPLICATION_UNKNOWN);
this.marshaller = marshaller;
}
@Override
public Object doTranscode(Object content, MediaType contentType, MediaType destinationType) {
try {
if (destinationType.equals(MediaType.APPLICATION_UNKNOWN) || contentType.equals(MediaType.APPLICATION_UNKNOWN)) {
return content;
}
if (destinationType.match(marshaller.mediaType())) {
return contentType.equals(marshaller.mediaType()) ? content : marshaller.objectToByteBuffer(content);
}
if (destinationType.match(MediaType.APPLICATION_OBJECT)) {
return marshaller.objectFromByteBuffer((byte[]) content);
}
} catch (InterruptedException | IOException | ClassNotFoundException e) {
throw new CacheException(e);
}
throw CONTAINER.unsupportedConversion(Util.toStr(content), contentType, destinationType);
}
}
| 1,767
| 35.081633
| 122
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/UrlFormCodec.java
|
package org.infinispan.commons.dataconversion;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_WWW_FORM_URLENCODED;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* Codec to handle URLEncoded content.
*
* @since 13.0
*/
class UrlFormCodec implements MediaTypeCodec {
@Override
public Object decodeContent(Object content, MediaType contentType) throws UnsupportedEncodingException {
if (contentType.match(APPLICATION_WWW_FORM_URLENCODED)) {
if (content instanceof byte[]) {
content = URLDecoder.decode(new String((byte[]) content), contentType.getCharset().toString());
} else {
content = URLDecoder.decode(content.toString(), contentType.getCharset().toString());
}
return content.toString().getBytes(UTF_8);
}
return content;
}
@Override
public Object encodeContent(Object content, MediaType destinationType) throws UnsupportedEncodingException {
if (destinationType.match(APPLICATION_WWW_FORM_URLENCODED)) {
if (content instanceof String) {
content = URLEncoder.encode(content.toString(), destinationType.getCharset().toString()).getBytes(destinationType.getCharset());
} else {
content = URLEncoder.encode(new String((byte[]) content), destinationType.getCharset().toString()).getBytes(destinationType.getCharset());
}
}
return content;
}
}
| 1,556
| 36.97561
| 150
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/ByteArrayWrapper.java
|
package org.infinispan.commons.dataconversion;
import org.infinispan.commons.marshall.WrappedByteArray;
/**
* Wraps byte[] on a {@link WrappedByteArray} to provide equality and hashCode support, leaving other objects
* unchanged.
*
* @since 9.1
*/
public class ByteArrayWrapper implements Wrapper {
public static final ByteArrayWrapper INSTANCE = new ByteArrayWrapper();
@Override
public Object wrap(Object obj) {
if (obj instanceof byte[]) return new WrappedByteArray((byte[]) obj);
return obj;
}
@Override
public Object unwrap(Object obj) {
if (obj != null && obj.getClass().equals(WrappedByteArray.class))
return WrappedByteArray.class.cast(obj).getBytes();
return obj;
}
@Override
public byte id() {
return WrapperIds.BYTE_ARRAY_WRAPPER;
}
@Override
public boolean isFilterable() {
return false;
}
}
| 901
| 22.128205
| 109
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/Transcoder.java
|
package org.infinispan.commons.dataconversion;
import java.util.Set;
/**
* Converts content between two or more {@link MediaType}s.
*
* <p>Note: A transcoder must be symmetric: if it can convert from media type X to media type Y,
* it must also be able to convert from Y to X.</p>
*
* @since 9.2
*/
public interface Transcoder {
/**
* Transcodes content between two different {@link MediaType}.
*
* @param content Content to transcode.
* @param contentType The {@link MediaType} of the content.
* @param destinationType The target {@link MediaType} to convert.
* @return the transcoded content.
*/
Object transcode(Object content, MediaType contentType, MediaType destinationType);
/**
* @return all the {@link MediaType} handled by this Transcoder.
*/
Set<MediaType> getSupportedMediaTypes();
/**
* @return {@code true} if the transcoder supports the conversion between the supplied {@link MediaType}s.
*/
default boolean supportsConversion(MediaType mediaType, MediaType other) {
return !mediaType.match(other) && supports(mediaType) && supports(other);
}
/**
* @return {@code true} iff the transcoder supports the conversion to and from the given {@link MediaType}.
*/
default boolean supports(MediaType mediaType) {
return getSupportedMediaTypes().stream().anyMatch(m -> m.match(mediaType));
}
}
| 1,420
| 30.577778
| 110
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/MediaTypeResolver.java
|
package org.infinispan.commons.dataconversion;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.Util;
/**
* Resolve media types for files
*
* @since 10.1
*/
public final class MediaTypeResolver {
private static final Map<String, String> FILE_MAP = new HashMap<>();
private static final Log LOG = LogFactory.getLog(MediaTypeResolver.class);
private static final String MIME_TYPES = "mime.types";
static {
populateFileMap();
}
// This has to be a separate method so we can mark it as blocking via blockhound
private static void populateFileMap() {
InputStream in = null;
BufferedInputStream bis = null;
try {
in = MediaTypeResolver.class.getClassLoader().getResourceAsStream(MIME_TYPES);
if (in == null) {
LOG.cannotLoadMimeTypes(MIME_TYPES);
} else {
bis = new BufferedInputStream(in);
Scanner scanner = new Scanner(bis, StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (!line.startsWith("#")) {
String[] split = line.split("\\s+");
if (split.length > 1) {
String mediaType = split[0];
for (int i = 1; i < split.length; i++) FILE_MAP.put(split[i], mediaType);
}
}
}
}
} finally {
Util.close(in, bis);
LOG.debugf("Loaded %s with %d file types", MIME_TYPES, FILE_MAP.size());
}
}
private MediaTypeResolver() {
}
/**
* @param fileName The file name
* @return The media type based on the internal mime.types file, or null if not found.
*/
public static String getMediaType(String fileName) {
if (fileName == null) return null;
int idx = fileName.lastIndexOf(".");
if (idx == -1 || idx == fileName.length()) return null;
return FILE_MAP.get(fileName.toLowerCase().substring(idx + 1));
}
}
| 2,272
| 31.014085
| 94
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/JavaStringCodec.java
|
package org.infinispan.commons.dataconversion;
import static java.util.function.Function.identity;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @since 13.0
*/
enum JavaStringCodec {
BYTE_ARRAY("ByteArray") {
@Override
Object decode(String strContent) {
return Base16Codec.decode(strContent);
}
@Override
Object encode(Object content, MediaType destinationType) {
if (content instanceof byte[]) {
return Base16Codec.encode((byte[]) content);
}
if (content instanceof String) {
return content.toString().getBytes(destinationType.getCharset());
}
throw new EncodingException("Cannot encode " + content.getClass() + " as ByteArray");
}
},
INTEGER(Integer.class.getName()) {
@Override
Object decode(String strContent) {
return Integer.parseInt(strContent);
}
@Override
Object encode(Object content, MediaType destinationType) {
return Integer.valueOf(content.toString()).toString();
}
},
STRING(String.class.getName()) {
@Override
Object decode(String strContent) {
return strContent;
}
@Override
Object encode(Object content, MediaType destinationType) {
if (content instanceof byte[]) {
return new String((byte[]) content, destinationType.getCharset());
} else if (content instanceof String) {
return content;
}
throw new EncodingException("Cannot encode " + content.getClass() + " as String");
}
},
BOOLEAN(Boolean.class.getName()) {
@Override
Object decode(String strContent) {
return Boolean.parseBoolean(strContent);
}
@Override
Object encode(Object content, MediaType destinationType) {
return Boolean.valueOf(content.toString()).toString();
}
},
SHORT(Short.class.getName()) {
@Override
Object decode(String strContent) {
return Short.parseShort(strContent);
}
@Override
Object encode(Object content, MediaType destinationType) {
return Short.valueOf(content.toString()).toString();
}
},
BYTE(Byte.class.getName()) {
@Override
Object decode(String strContent) {
return Byte.parseByte(strContent);
}
@Override
Object encode(Object content, MediaType destinationType) {
return Byte.valueOf(content.toString()).toString();
}
},
LONG(Long.class.getName()) {
@Override
Object decode(String strContent) {
return Long.parseLong(strContent);
}
@Override
Object encode(Object content, MediaType destinationType) {
return Long.valueOf(content.toString()).toString();
}
},
FLOAT(Float.class.getName()) {
@Override
Object decode(String strContent) {
return Float.parseFloat(strContent);
}
@Override
Object encode(Object content, MediaType destinationType) {
return Float.valueOf(content.toString()).toString();
}
},
DOUBLE(Double.class.getName()) {
@Override
Object decode(String strContent) {
return Double.parseDouble(strContent);
}
@Override
Object encode(Object content, MediaType destinationType) {
return Double.valueOf(content.toString()).toString();
}
};
private final String name;
private static final Map<String, JavaStringCodec> CACHE = Arrays.stream(JavaStringCodec.values())
.collect(Collectors.toMap(JavaStringCodec::getName, identity()));
JavaStringCodec(String name) {
this.name = name;
}
public String getName() {
return name;
}
abstract Object decode(String str);
abstract Object encode(Object value, MediaType destinationType);
static JavaStringCodec forType(String type) {
return CACHE.get(type);
}
}
| 3,985
| 26.489655
| 100
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/MediaTypeCodec.java
|
package org.infinispan.commons.dataconversion;
import java.io.UnsupportedEncodingException;
/**
* MediaTypeCodecs handles extra content encoding and decoding specified as part of a {@link MediaType}.
*
* @since 13.0
*/
interface MediaTypeCodec {
Object decodeContent(Object content, MediaType contentType) throws UnsupportedEncodingException;
Object encodeContent(Object content, MediaType destinationType) throws UnsupportedEncodingException;
}
| 460
| 27.8125
| 104
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/UTF8Encoder.java
|
package org.infinispan.commons.dataconversion;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.infinispan.commons.logging.Log.CONTAINER;
import org.infinispan.commons.util.Util;
/**
* Encoder to/from UTF-8 content using the java string encoding mechanism.
*
* @since 9.1
* @deprecated Since 12.1, to be removed in a future version.
*/
@Deprecated
public class UTF8Encoder implements Encoder {
public static final UTF8Encoder INSTANCE = new UTF8Encoder();
private static final MediaType UTF8 = MediaType.fromString("text/plain; charset=utf-8");
@Override
public Object toStorage(Object content) {
if (content instanceof String) {
return String.class.cast(content).getBytes(UTF_8);
}
throw CONTAINER.unsupportedConversion(Util.toStr(content), UTF8);
}
@Override
public Object fromStorage(Object stored) {
return new String((byte[]) stored, UTF_8);
}
@Override
public boolean isStorageFormatFilterable() {
return false;
}
@Override
public MediaType getStorageFormat() {
return MediaType.TEXT_PLAIN;
}
@Override
public short id() {
return EncoderIds.UTF8;
}
}
| 1,198
| 23.469388
| 91
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/IdentityEncoder.java
|
package org.infinispan.commons.dataconversion;
/**
* Encoder that does not change the content.
*
* @since 9.1
* @deprecated since 12.1. to be removed in a future version.
*/
@Deprecated
public class IdentityEncoder implements Encoder {
public static final IdentityEncoder INSTANCE = new IdentityEncoder();
@Override
public Object toStorage(Object content) {
return content;
}
@Override
public Object fromStorage(Object content) {
return content;
}
@Override
public boolean isStorageFormatFilterable() {
return false;
}
@Override
public MediaType getStorageFormat() {
return null;
}
@Override
public short id() {
return EncoderIds.IDENTITY;
}
}
| 735
| 17.4
| 72
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/EncodingException.java
|
package org.infinispan.commons.dataconversion;
import org.infinispan.commons.CacheException;
/**
* @since 9.1
*/
public class EncodingException extends CacheException {
public EncodingException(String message) {
super(message);
}
public EncodingException(String message, Throwable cause) {
super(message, cause);
}
}
| 346
| 19.411765
| 62
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/GlobalMarshallerEncoder.java
|
package org.infinispan.commons.dataconversion;
import org.infinispan.commons.marshall.Marshaller;
/**
* Encoder that uses the GlobalMarshaller to encode/decode data.
*
* @since 9.2
* @deprecated Since 11.0, will be removed with ISPN-9622
*/
@Deprecated
public class GlobalMarshallerEncoder extends MarshallerEncoder {
public GlobalMarshallerEncoder(Marshaller globalMarshaller) {
super(globalMarshaller);
}
@Override
public MediaType getStorageFormat() {
return MediaType.APPLICATION_INFINISPAN_MARSHALLED;
}
@Override
public short id() {
return EncoderIds.GLOBAL_MARSHALLER;
}
}
| 632
| 21.607143
| 64
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/AbstractTranscoder.java
|
package org.infinispan.commons.dataconversion;
import static org.infinispan.commons.logging.Log.CONTAINER;
import java.io.UnsupportedEncodingException;
import java.util.Objects;
import org.infinispan.commons.util.Util;
/**
* Class to inherit when implementing transcoders, will handle pre and post processing of the content.
*
* @since 13.0
*/
public abstract class AbstractTranscoder implements Transcoder {
private static final MediaTypeCodec[] CODECS =
new MediaTypeCodec[] { new JavaMediaTypeCodec(), new UrlFormCodec(), new RFC4648Codec() };
/**
* Decodes content before doing the transcoding.
*
* @param content the content.
* @param contentType the {@link MediaType} describing the content.
* @return an Object with the content decoded or the content itself if no decoding needed.
* @throws UnsupportedEncodingException if an invalid encoding or type is provided.
*/
protected Object decodeContent(Object content, MediaType contentType) throws UnsupportedEncodingException {
if (content == null) return null;
Objects.requireNonNull(contentType, "contentType cannot be null!");
for (MediaTypeCodec coded : CODECS) {
content = coded.decodeContent(content, contentType);
}
return content;
}
/**
* Encode the content after transcoding if necessary.
*
* @param content The content to encode.
* @param destinationType The destination {@link MediaType}
* @return The value encoded or unchanged if no encoding is needed.
*/
protected Object encodeContent(Object content, MediaType destinationType) throws UnsupportedEncodingException {
if (content == null) return null;
for (MediaTypeCodec codec : CODECS) {
content = codec.encodeContent(content, destinationType);
}
return content;
}
@Override
public Object transcode(Object content, MediaType contentType, MediaType destinationType) {
try {
Object decoded = decodeContent(content, contentType);
Object result = doTranscode(decoded, contentType, destinationType);
return encodeContent(result, destinationType);
} catch (UnsupportedEncodingException e) {
throw CONTAINER.errorTranscoding(Util.toStr(content), contentType, destinationType, e);
}
}
protected abstract Object doTranscode(Object decoded, MediaType contentType, MediaType destinationType);
}
| 2,443
| 33.422535
| 114
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/RFC4648Codec.java
|
package org.infinispan.commons.dataconversion;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.infinispan.commons.dataconversion.JavaStringCodec.BYTE_ARRAY;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT;
import static org.infinispan.commons.dataconversion.MediaType.BASE_64;
import static org.infinispan.commons.dataconversion.MediaType.HEX;
import java.util.Base64;
import java.util.Optional;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* Handles base16 and base64 data encodings as specified in the <a href="https://www.ietf.org/rfc/rfc4648.txt">RFC 4648</a>.
*
* It used when the {@link MediaType} contains an <code>encoding</code> param, e.g.
* <br/>
* <code>application/octet-stream; encoding=hex</code>.
* <br>
* Valid encodings are "hex" (base16) and "base64".
*
* @since 13.0
*/
class RFC4648Codec implements MediaTypeCodec {
private static final Log log = LogFactory.getLog(RFC4648Codec.class);
@Override
public Object decodeContent(Object content, MediaType contentType) {
Optional<String> optionalEncoding = contentType.getParameter("encoding");
if (optionalEncoding.isPresent()) {
String enc = optionalEncoding.get();
if (content instanceof byte[]) {
return decode(new String((byte[]) content, contentType.getCharset()), enc);
} else if (content instanceof String) {
return decode(content.toString(), enc);
}
throw new EncodingException("Cannot decode binary content " + content);
} else {
if (content instanceof String && (contentType.match(MediaType.APPLICATION_OCTET_STREAM) || hasJavaByteArrayType(contentType))) {
return decode(content.toString(), HEX);
}
return content;
}
}
private boolean hasJavaByteArrayType(MediaType contentType) {
return contentType.match(APPLICATION_OBJECT) && contentType.getClassType() != null &&
contentType.getClassType().equals(BYTE_ARRAY.getName());
}
private Object decode(String content, String codec) {
switch (codec) {
case HEX:
return Base16Codec.decode(content);
case BASE_64:
return Base64.getDecoder().decode(content);
default:
throw log.encodingNotSupported(codec);
}
}
private Object encode(byte[] content, String codec) {
switch (codec) {
case HEX:
return Base16Codec.encode(content);
case BASE_64:
return Base64.getEncoder().encode(content);
default:
throw log.encodingNotSupported(codec);
}
}
@Override
public Object encodeContent(Object content, MediaType destinationType) {
Optional<String> optionalEncoding = destinationType.getParameter("encoding");
if (optionalEncoding.isPresent()) {
String enc = optionalEncoding.get();
if (content instanceof byte[]) {
content = encode((byte[]) content, enc);
} else if (content instanceof String) {
content = encode(content.toString().getBytes(UTF_8), enc);
}
return content;
}
boolean binaryTargetForString = destinationType.isBinary() && content instanceof String;
return binaryTargetForString ? content.toString().getBytes(UTF_8) : content;
}
}
| 3,423
| 35.817204
| 137
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/Encoder.java
|
package org.infinispan.commons.dataconversion;
/**
* Used to convert data between read/write format and storage format.
*
* @since 9.1
* @deprecated Since 12.1, without replacement. To be removed in a future version.
*/
@Deprecated
public interface Encoder {
/**
* Convert data in the read/write format to the storage format.
*
* @param content data to be converted, never null.
* @return Object in the storage format.
*/
Object toStorage(Object content);
/**
* Convert from storage format to the read/write format.
*
* @param content data as stored in the cache, never null.
* @return data in the read/write format
*/
Object fromStorage(Object content);
/**
* @return if true, will perform stream and related operation in the storage format.
*/
boolean isStorageFormatFilterable();
/**
* Returns the {@link MediaType} produced by this encoder or null if the storage format is not known.
*/
MediaType getStorageFormat();
/**
* Each encoder is associated with an unique id in order to optimize serialization. Known ids are kept in {@link
* EncoderIds}.
*
* @return unique identifier for this encoder
*/
short id();
}
| 1,234
| 25.276596
| 115
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/internal/Json.java
|
package org.infinispan.commons.dataconversion.internal;
/*
* Copyright (C) 2011 Miami-Dade County.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Note: this file incorporates source code from 3d party entities. Such code
* is copyrighted by those entities as indicated below.
*/
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
import org.infinispan.commons.dataconversion.MediaType;
/**
* <p>
* Represents a JSON (JavaScript Object Notation) entity. For more information about JSON, please see
* <a href="http://www.json.org" target="_">http://www.json.org</a>.
* </p>
*
* <p>
* A JSON entity can be one of several things: an object (set of name/Json entity pairs), an array (a list of other JSON
* entities), a string, a number, a boolean or null. All of those are represented as <code>Json</code> instances. Each
* of the different types of entities supports a different set of operations. However, this class unifies all operations
* into a single interface so in Java one is always dealing with a single object type: this class. The approach
* effectively amounts to dynamic typing where using an unsupported operation won't be detected at compile time, but
* will throw a runtime {@link UnsupportedOperationException}. It simplifies working with JSON structures considerably
* and it leads to shorter at cleaner Java code. It makes much easier to work with JSON structure without the need to
* convert to "proper" Java representation in the form of POJOs and the like. When traversing a JSON, there's no need to
* type-cast at each step because there's only one type: <code>Json</code>.
* </p>
*
* <p>
* One can examine the concrete type of a <code>Json</code> with one of the <code>isXXX</code> methods:
* {@link #isObject()}, {@link #isArray()},{@link #isNumber()},{@link #isBoolean()},{@link #isString()},
* {@link #isNull()}.
* </p>
*
* <p>
* The underlying representation of a given <code>Json</code> instance can be obtained by calling the generic
* {@link #getValue()} method or one of the <code>asXXX</code> methods such as {@link #asBoolean()} or
* {@link #asString()} etc. JSON objects are represented as Java {@link Map}s while JSON arrays are represented as Java
* {@link List}s. Because those are mutable aggregate structures, there are two versions of the corresponding
* <code>asXXX</code> methods: {@link #asMap()} which performs a deep copy of the underlying map, unwrapping every
* nested Json entity to its Java representation and {@link #asJsonMap()} which simply return the map reference.
* Similarly there are {@link #asList()} and {@link #asJsonList()}.
* </p>
*
* <h3>Constructing and Modifying JSON Structures</h3>
*
* <p>
* There are several static factory methods in this class that allow you to create new
* <code>Json</code> instances:
* </p>
*
* <table>
* <tr><td>{@link #read(String)}</td>
* <td>Parse a JSON string and return the resulting <code>Json</code> instance. The syntax
* recognized is as defined in <a href="http://www.json.org">http://www.json.org</a>.
* </td>
* </tr>
* <tr><td>{@link #make(Object)}</td>
* <td>Creates a Json instance based on the concrete type of the parameter. The types
* recognized are null, numbers, primitives, String, Map, Collection, Java arrays
* and <code>Json</code> itself.</td>
* </tr>
* <tr><td>{@link #nil()}</td>
* <td>Return a <code>Json</code> instance representing JSON <code>null</code>.</td>
* </tr>
* <tr><td>{@link #object()}</td>
* <td>Create and return an empty JSON object.</td>
* </tr>
* <tr><td>{@link #object(Object...)}</td>
* <td>Create and return a JSON object populated with the key/value pairs
* passed as an argument sequence. Each even parameter becomes a key (via
* <code>toString</code>) and each odd parameter is converted to a <code>Json</code>
* value.</td>
* </tr>
* <tr><td>{@link #array()}</td>
* <td>Create and return an empty JSON array.</td>
* </tr>
* <tr><td>{@link #array(Object...)}</td>
* <td>Create and return a JSON array from the list of arguments.</td>
* </tr>
* </table>
*
* <p>
* To customize how Json elements are represented and to provide your own version of the
* {@link #make(Object)} method, you create an implementation of the {@link Factory} interface
* and configure it either globally with the {@link #setGlobalFactory(Factory)} method or
* on a per-thread basis with the {@link #attachFactory(Factory)}/{@link #detachFactory()}
* methods.
* </p>
*
* <p>
* If a <code>Json</code> instance is an object, you can set its properties by
* calling the {@link #set(String, Object)} method which will add a new property or replace an existing one.
* Adding elements to an array <code>Json</code> is done with the {@link #add(Object)} method.
* Removing elements by their index (or key) is done with the {@link #delAt(int)} (or
* {@link #delAt(String)}) method. You can also remove an element from an array without
* knowing its index with the {@link #remove(Object)} method. All these methods return the
* <code>Json</code> instance being manipulated so that method calls can be chained.
* If you want to remove an element from an object or array and return the removed element
* as a result of the operation, call {@link #atDel(int)} or {@link #atDel(String)} instead.
* </p>
*
* <p>
* If you want to add properties to an object in bulk or append a sequence of elements to array,
* use the {@link #with(Json, Json...opts)} method. When used on an object, this method expects another
* object as its argument and it will copy all properties of that argument into itself. Similarly,
* when called on array, the method expects another array and it will append all elements of its
* argument to itself.
* </p>
*
* <p>
* To make a clone of a Json object, use the {@link #dup()} method. This method will create a new
* object even for the immutable primitive Json types. Objects and arrays are cloned
* (i.e. duplicated) recursively.
* </p>
*
* <h3>Navigating JSON Structures</h3>
*
* <p>
* The {@link #at(int)} method returns the array element at the specified index and the
* {@link #at(String)} method does the same for a property of an object instance. You can
* use the {@link #at(String, Object)} version to create an object property with a default
* value if it doesn't exist already.
* </p>
*
* <p>
* To test just whether a Json object has a given property, use the {@link #has(String)} method. To test
* whether a given object property or an array elements is equal to a particular value, use the
* {@link #is(String, Object)} and {@link #is(int, Object)} methods respectively. Those methods return
* true if the given named property (or indexed element) is equal to the passed in Object as the second
* parameter. They return false if an object doesn't have the specified property or an index array is out
* of bounds. For example is(name, value) is equivalent to 'has(name) && at(name).equals(make(value))'.
* </p>
*
* <p>
* To help in navigating JSON structures, instances of this class contain a reference to the
* enclosing JSON entity (object or array) if any. The enclosing entity can be accessed
* with {@link #up()} method.
* </p>
*
* <p>
* The combination of method chaining when modifying <code>Json</code> instances and
* the ability to navigate "inside" a structure and then go back to the enclosing
* element lets one accomplish a lot in a single Java statement, without the need
* of intermediary variables. Here for example how the following JSON structure can
* be created in one statement using chained calls:
* </p>
*
* <pre><code>
* {"menu": {
* "id": "file",
* "value": "File",
* "popup": {
* "menuitem": [
* {"value": "New", "onclick": "CreateNewDoc()"},
* {"value": "Open", "onclick": "OpenDoc()"},
* {"value": "Close", "onclick": "CloseDoc()"}
* ]
* }
* "position": 0
* }}
* </code></pre>
*
* <pre><code>
* import mjson.Json;
* import static mjson.Json.*;
* ...
* Json j = object()
* .at("menu", object())
* .set("id", "file")
* .set("value", "File")
* .at("popup", object())
* .at("menuitem", array())
* .add(object("value", "New", "onclick", "CreateNewDoc()"))
* .add(object("value", "Open", "onclick", "OpenDoc()"))
* .add(object("value", "Close", "onclick", "CloseDoc()"))
* .up()
* .up()
* .set("position", 0)
* .up();
* ...
* </code></pre>
*
* <p>
* If there's no danger of naming conflicts, a static import of the factory methods (<code>
* import static json.Json.*;</code>) would reduce typing even further and make the code more
* readable.
* </p>
*
* <h3>Converting to String</h3>
*
* <p>
* To get a compact string representation, simply use the {@link #toString()} method. If you
* want to wrap it in a JavaScript callback (for JSON with padding), use the {@link #pad(String)}
* method.
* </p>
*
* <h3>Validating with JSON Schema</h3>
*
* <p>
* Since version 1.3, mJson supports JSON Schema, draft 4. A schema is represented by the internal
* class {@link Json.Schema}. To perform a validation, you have a instantiate a <code>Json.Schema</code>
* using the factory method {@link Json.Schema} and then call its <code>validate</code> method
* on a JSON instance:
* </p>
*
* <pre><code>
* import mjson.Json;
* import static mjson.Json.*;
* ...
* Json inputJson = Json.read(inputString);
* Json schema = Json.schema(new URI("http://mycompany.com/schemas/model"));
* Json errors = schema.validate(inputJson);
* for (Json error : errors.asJsonList())
* System.out.println("Validation error " + err);
* </code></pre>
* <h2>
* Infinispan changes on top of 1.4.2:
* </h2>
* <p><ul>
* <li>Added support for pretty printing {@link Json#toPrettyString()}</li>
* <li>Added support for {@link RawJson} as a specialized {@link StringJson}</li>
* <li>Usage of {@link LinkedHashMap} internally for {@link ObjectJson} for predictable iteration</li>
* <li>Support for {@link Class}, {@link Properties}, {@link Enum} for {@link DefaultFactory#make(Object)}</li>
* <li>Support from internal Infinispan classes for {@link DefaultFactory#make(Object)}: {@link MediaType}, {@link JsonSerialization}, {@link ConfigurationInfo}</li>
* <li>Support for replacing objects</li>
* </ul></p>
*
* @author Borislav Iordanov
* @version 1.4.2
*/
public class Json implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* <p>
* This interface defines how <code>Json</code> instances are constructed. There is a default implementation for each
* kind of <code>Json</code> value, but you can provide your own implementation. For example, you might want a
* different representation of an object than a regular <code>HashMap</code>. Or you might want string comparison to
* be case insensitive.
* </p>
*
* <p>
* In addition, the {@link #make(Object)} method allows you plug-in your own mapping of arbitrary Java objects to
* <code>Json</code> instances. You might want to implement a Java Beans to JSON mapping or any other JSON
* serialization that makes sense in your project.
* </p>
*
* <p>
* To avoid implementing all methods in that interface, you can extend the {@link DefaultFactory} default
* implementation and simply overwrite the ones you're interested in.
* </p>
*
* <p>
* The factory implementation used by the <code>Json</code> classes is specified simply by calling the
* {@link #setGlobalFactory(Factory)} method. The factory is a static, global variable by default. If you need
* different factories in different areas of a single application, you may attach them to different threads of
* execution using the {@link #attachFactory(Factory)}. Recall a separate copy of static variables is made per
* ClassLoader, so for example in a web application context, that global factory can be different for each web
* application (as Java web servers usually use a separate class loader per application). Thread-local factories are
* really a provision for special cases.
* </p>
*
* @author Borislav Iordanov
*/
public interface Factory {
/**
* Construct and return an object representing JSON <code>null</code>. Implementations are free to cache a return
* the same instance. The resulting value must return
* <code>true</code> from <code>isNull()</code> and <code>null</code> from
* <code>getValue()</code>.
*
* @return The representation of a JSON <code>null</code> value.
*/
Json nil();
/**
* Construct and return a JSON boolean. The resulting value must return
* <code>true</code> from <code>isBoolean()</code> and the passed
* in parameter from <code>getValue()</code>.
*
* @param value The boolean value.
* @return A JSON with <code>isBoolean() == true</code>. Implementations are free to cache and return the same
* instance for true and false.
*/
Json bool(boolean value);
/**
* Construct and return a JSON string. The resulting value must return
* <code>true</code> from <code>isString()</code> and the passed
* in parameter from <code>getValue()</code>.
*
* @param value The string to wrap as a JSON value.
* @return A JSON element with the given string as a value.
*/
Json string(String value);
Json raw(String value);
/**
* Construct and return a JSON number. The resulting value must return
* <code>true</code> from <code>isNumber()</code> and the passed
* in parameter from <code>getValue()</code>.
*
* @param value The numeric value.
* @return Json instance representing that value.
*/
Json number(Number value);
/**
* Construct and return a JSON object. The resulting value must return
* <code>true</code> from <code>isObject()</code> and an implementation
* of <code>java.util.Map</code> from <code>getValue()</code>.
*
* @return An empty JSON object.
*/
Json object();
/**
* Construct and return a JSON object. The resulting value must return
* <code>true</code> from <code>isArray()</code> and an implementation
* of <code>java.util.List</code> from <code>getValue()</code>.
*
* @return An empty JSON array.
*/
Json array();
/**
* Construct and return a JSON object. The resulting value can be of any JSON type. The method is responsible for
* examining the type of its argument and performing an appropriate mapping to a <code>Json</code> instance.
*
* @param anything An arbitray Java object from which to construct a <code>Json</code> element.
* @return The newly constructed <code>Json</code> instance.
*/
Json make(Object anything);
}
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
/**
* <p>
* Represents JSON schema - a specific data format that a JSON entity must follow. The idea of a JSON schema is very
* similar to XML. Its main purpose is validating input.
* </p>
*
* <p>
* More information about the various JSON schema specifications can be found at http://json-schema.org. JSON Schema
* is an IETF draft (v4 currently) and our implementation follows this set of specifications. A JSON schema is
* specified as a JSON object that contains keywords defined by the specification. Here are a few introductory
* materials:
* <ul>
* <li>http://jsonary.com/documentation/json-schema/ -
* a very well-written tutorial covering the whole standard</li>
* <li>http://spacetelescope.github.io/understanding-json-schema/ -
* online book, tutorial (Python/Ruby based)</li>
* </ul>
* </p>
*
* @author Borislav Iordanov
*/
public interface Schema {
/**
* <p>
* Validate a JSON document according to this schema. The validations attempts to proceed even in the face of
* errors. The return value is always a <code>Json.object</code> containing the boolean property <code>ok</code>.
* When <code>ok</code> is <code>true</code>, the return object contains nothing else. When it is
* <code>false</code>, the return object contains a property <code>errors</code> which is an array of error
* messages for all detected schema violations.
* </p>
*
* @param document The input document.
* @return <code>{"ok":true}</code> or <code>{"ok":false, errors:["msg1", "msg2", ...]}</code>
*/
Json validate(Json document);
/**
* <p>Return the JSON representation of the schema.</p>
*/
Json toJson();
/**
* <p>Possible options are: <code>ignoreDefaults:true|false</code>.
* </p>
* @return A newly created <code>Json</code> conforming to this schema.
*/
//Json generate(Json options);
}
static String fetchContent(URL url) {
java.io.Reader reader = null;
try {
reader = new java.io.InputStreamReader((java.io.InputStream) url.getContent(), StandardCharsets.UTF_8);
StringBuilder content = new StringBuilder();
char[] buf = new char[1024];
for (int n = reader.read(buf); n > -1; n = reader.read(buf))
content.append(buf, 0, n);
return content.toString();
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
if (reader != null) try {
reader.close();
} catch (Throwable t) {
}
}
}
static Json resolvePointer(String pointerRepresentation, Json top) {
String[] parts = pointerRepresentation.split("/");
Json result = top;
for (String p : parts) {
// TODO: unescaping and decoding
if (p.length() == 0)
continue;
p = p.replace("~1", "/").replace("~0", "~");
if (result.isArray())
result = result.at(Integer.parseInt(p));
else if (result.isObject())
result = result.at(p);
else
throw new RuntimeException("Can't resolve pointer " + pointerRepresentation +
" on document " + top.toString(200));
}
return result;
}
static URI makeAbsolute(URI base, String ref) throws Exception {
URI refuri;
if (base != null && base.getAuthority() != null && !new URI(ref).isAbsolute()) {
StringBuilder sb = new StringBuilder();
if (base.getScheme() != null)
sb.append(base.getScheme()).append("://");
sb.append(base.getAuthority());
if (!ref.startsWith("/")) {
if (ref.startsWith("#"))
sb.append(base.getPath());
else {
int slashIdx = base.getPath().lastIndexOf('/');
sb.append(slashIdx == -1 ? base.getPath() : base.getPath().substring(0, slashIdx)).append("/");
}
}
refuri = new URI(sb.append(ref).toString());
} else if (base != null)
refuri = base.resolve(ref);
else
refuri = new URI(ref);
return refuri;
}
static Json resolveRef(URI base,
Json refdoc,
URI refuri,
Map<String, Json> resolved,
Map<Json, Json> expanded,
Function<URI, Json> uriResolver) throws Exception {
if (refuri.isAbsolute() &&
(base == null || !base.isAbsolute() ||
!base.getScheme().equals(refuri.getScheme()) ||
!Objects.equals(base.getHost(), refuri.getHost()) ||
base.getPort() != refuri.getPort() ||
!base.getPath().equals(refuri.getPath()))) {
URI docuri = null;
refuri = refuri.normalize();
if (refuri.getHost() == null)
docuri = new URI(refuri.getScheme() + ":" + refuri.getPath());
else
docuri = new URI(refuri.getScheme() + "://" + refuri.getHost() +
((refuri.getPort() > -1) ? ":" + refuri.getPort() : "") +
refuri.getPath());
refdoc = uriResolver.apply(docuri);
refdoc = expandReferences(refdoc, refdoc, docuri, resolved, expanded, uriResolver);
}
if (refuri.getFragment() == null)
return refdoc;
else
return resolvePointer(refuri.getFragment(), refdoc);
}
/**
* <p>
* Replace all JSON references, as per the http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 specification, by
* their referants.
* </p>
*
* @param json
* @param duplicate
* @param done
* @return
*/
static Json expandReferences(Json json,
Json topdoc,
URI base,
Map<String, Json> resolved,
Map<Json, Json> expanded,
Function<URI, Json> uriResolver) throws Exception {
if (expanded.containsKey(json)) return json;
if (json.isObject()) {
if (json.has("id") && json.at("id").isString()) // change scope of nest references
{
base = base.resolve(json.at("id").asString());
}
if (json.has("$ref")) {
URI refuri = makeAbsolute(base, json.at("$ref").asString()); // base.resolve(json.at("$ref").asString());
Json ref = resolved.get(refuri.toString());
if (ref == null) {
ref = Json.object();
resolved.put(refuri.toString(), ref);
ref.with(resolveRef(base, topdoc, refuri, resolved, expanded, uriResolver));
}
json = ref;
} else {
for (Map.Entry<String, Json> e : json.asJsonMap().entrySet())
json.set(e.getKey(), expandReferences(e.getValue(), topdoc, base, resolved, expanded, uriResolver));
}
} else if (json.isArray()) {
for (int i = 0; i < json.asJsonList().size(); i++)
json.set(i,
expandReferences(json.at(i), topdoc, base, resolved, expanded, uriResolver));
}
expanded.put(json, json);
return json;
}
static class DefaultSchema implements Schema {
interface Instruction extends Function<Json, Json> {
}
static Json maybeError(Json errors, Json E) {
return E == null ? errors : (errors == null ? Json.array() : errors).with(E, new Json[0]);
}
// Anything is valid schema
static Instruction any = new Instruction() {
public Json apply(Json param) {
return null;
}
};
// Type validation
class IsObject implements Instruction {
public Json apply(Json param) {
return param.isObject() ? null : Json.make(param.toString(maxchars));
}
}
class IsArray implements Instruction {
public Json apply(Json param) {
return param.isArray() ? null : Json.make(param.toString(maxchars));
}
}
class IsString implements Instruction {
public Json apply(Json param) {
return param.isString() ? null : Json.make(param.toString(maxchars));
}
}
class IsBoolean implements Instruction {
public Json apply(Json param) {
return param.isBoolean() ? null : Json.make(param.toString(maxchars));
}
}
class IsNull implements Instruction {
public Json apply(Json param) {
return param.isNull() ? null : Json.make(param.toString(maxchars));
}
}
class IsNumber implements Instruction {
public Json apply(Json param) {
return param.isNumber() ? null : Json.make(param.toString(maxchars));
}
}
class IsInteger implements Instruction {
public Json apply(Json param) {
return param.isNumber() && ((Number) param.getValue()) instanceof Integer ? null : Json.make(param.toString(maxchars));
}
}
class CheckString implements Instruction {
int min = 0, max = Integer.MAX_VALUE;
Pattern pattern;
public Json apply(Json param) {
Json errors = null;
if (!param.isString()) return errors;
String s = param.asString();
final int size = s.codePointCount(0, s.length());
if (size < min || size > max)
errors = maybeError(errors, Json.make("String " + param.toString(maxchars) +
" has length outside of the permitted range [" + min + "," + max + "]."));
if (pattern != null && !pattern.matcher(s).matches())
errors = maybeError(errors, Json.make("String " + param.toString(maxchars) +
" does not match regex " + pattern.toString()));
return errors;
}
}
static class CheckNumber implements Instruction {
double min = Double.NaN, max = Double.NaN, multipleOf = Double.NaN;
boolean exclusiveMin = false, exclusiveMax = false;
public Json apply(Json param) {
Json errors = null;
if (!param.isNumber()) return errors;
double value = param.asDouble();
if (!Double.isNaN(min) && (value < min || exclusiveMin && value == min))
errors = maybeError(errors, Json.make("Number " + param + " is below allowed minimum " + min));
if (!Double.isNaN(max) && (value > max || exclusiveMax && value == max))
errors = maybeError(errors, Json.make("Number " + param + " is above allowed maximum " + max));
if (!Double.isNaN(multipleOf) && (value / multipleOf) % 1 != 0)
errors = maybeError(errors, Json.make("Number " + param + " is not a multiple of " + multipleOf));
return errors;
}
}
class CheckArray implements Instruction {
int min = 0, max = Integer.MAX_VALUE;
Boolean uniqueitems = null;
Instruction additionalSchema = any;
Instruction schema;
ArrayList<Instruction> schemas;
public Json apply(Json param) {
Json errors = null;
if (!param.isArray()) return errors;
if (schema == null && schemas == null && additionalSchema == null) // no schema specified
return errors;
int size = param.asJsonList().size();
for (int i = 0; i < size; i++) {
Instruction S = schema != null ? schema
: (schemas != null && i < schemas.size()) ? schemas.get(i) : additionalSchema;
if (S == null)
errors = maybeError(errors, Json.make("Additional items are not permitted: " +
param.at(i) + " in " + param.toString(maxchars)));
else
errors = maybeError(errors, S.apply(param.at(i)));
if (uniqueitems != null && uniqueitems && param.asJsonList().lastIndexOf(param.at(i)) > i)
errors = maybeError(errors, Json.make("Element " + param.at(i) + " is duplicate in array."));
if (errors != null && !errors.asJsonList().isEmpty())
break;
}
if (size < min || size > max)
errors = maybeError(errors, Json.make("Array " + param.toString(maxchars) +
" has number of elements outside of the permitted range [" + min + "," + max + "]."));
return errors;
}
}
class CheckPropertyPresent implements Instruction {
String propname;
public CheckPropertyPresent(String propname) {
this.propname = propname;
}
public Json apply(Json param) {
if (!param.isObject()) return null;
if (param.has(propname)) return null;
else return Json.array().add(Json.make("Required property " + propname +
" missing from object " + param.toString(maxchars)));
}
}
class CheckObject implements Instruction {
int min = 0, max = Integer.MAX_VALUE;
Instruction additionalSchema = any;
ArrayList<CheckProperty> props = new ArrayList<CheckProperty>();
ArrayList<CheckPatternProperty> patternProps = new ArrayList<CheckPatternProperty>();
// Object validation
class CheckProperty implements Instruction {
String name;
Instruction schema;
public CheckProperty(String name, Instruction schema) {
this.name = name;
this.schema = schema;
}
public Json apply(Json param) {
Json value = param.at(name);
if (value == null)
return null;
else
return schema.apply(param.at(name));
}
}
class CheckPatternProperty // implements Instruction
{
Pattern pattern;
Instruction schema;
public CheckPatternProperty(String pattern, Instruction schema) {
this.pattern = Pattern.compile(pattern);
this.schema = schema;
}
public Json apply(Json param, Set<String> found) {
Json errors = null;
for (Map.Entry<String, Json> e : param.asJsonMap().entrySet())
if (pattern.matcher(e.getKey()).find()) {
found.add(e.getKey());
errors = maybeError(errors, schema.apply(e.getValue()));
}
return errors;
}
}
public Json apply(Json param) {
Json errors = null;
if (!param.isObject()) return errors;
HashSet<String> checked = new HashSet<String>();
for (CheckProperty I : props) {
if (param.has(I.name)) checked.add(I.name);
errors = maybeError(errors, I.apply(param));
}
for (CheckPatternProperty I : patternProps) {
errors = maybeError(errors, I.apply(param, checked));
}
if (additionalSchema != any) for (Map.Entry<String, Json> e : param.asJsonMap().entrySet())
if (!checked.contains(e.getKey()))
errors = maybeError(errors, additionalSchema == null ?
Json.make("Extra property '" + e.getKey() +
"', schema doesn't allow any properties not explicitly defined:" +
param.toString(maxchars))
: additionalSchema.apply(e.getValue()));
if (param.asJsonMap().size() < min)
errors = maybeError(errors, Json.make("Object " + param.toString(maxchars) +
" has fewer than the permitted " + min + " number of properties."));
if (param.asJsonMap().size() > max)
errors = maybeError(errors, Json.make("Object " + param.toString(maxchars) +
" has more than the permitted " + min + " number of properties."));
return errors;
}
}
static class Sequence implements Instruction {
ArrayList<Instruction> seq = new ArrayList<Instruction>();
public Json apply(Json param) {
Json errors = null;
for (Instruction I : seq)
errors = maybeError(errors, I.apply(param));
return errors;
}
public Sequence add(Instruction I) {
seq.add(I);
return this;
}
}
class CheckType implements Instruction {
Json types;
public CheckType(Json types) {
this.types = types;
}
public Json apply(Json param) {
String ptype = param.isString() ? "string" :
param.isObject() ? "object" :
param.isArray() ? "array" :
param.isNumber() ? "number" :
param.isNull() ? "null" : "boolean";
for (Json type : types.asJsonList())
if (type.asString().equals(ptype))
return null;
else if (type.asString().equals("integer") &&
param.isNumber() &&
param.asDouble() % 1 == 0)
return null;
return Json.array().add(Json.make("Type mistmatch for " + param.toString(maxchars) +
", allowed types: " + types));
}
}
class CheckEnum implements Instruction {
Json theenum;
public CheckEnum(Json theenum) {
this.theenum = theenum;
}
public Json apply(Json param) {
for (Json option : theenum.asJsonList())
if (param.equals(option))
return null;
return Json.array().add("Element " + param.toString(maxchars) +
" doesn't match any of enumerated possibilities " + theenum);
}
}
class CheckAny implements Instruction {
ArrayList<Instruction> alternates = new ArrayList<Instruction>();
Json schema;
public Json apply(Json param) {
for (Instruction I : alternates)
if (I.apply(param) == null)
return null;
return Json.array().add("Element " + param.toString(maxchars) +
" must conform to at least one of available sub-schemas " +
schema.toString(maxchars));
}
}
class CheckOne implements Instruction {
ArrayList<Instruction> alternates = new ArrayList<Instruction>();
Json schema;
public Json apply(Json param) {
int matches = 0;
Json errors = Json.array();
for (Instruction I : alternates) {
Json result = I.apply(param);
if (result == null)
matches++;
else
errors.add(result);
}
if (matches != 1) {
return Json.array().add("Element " + param.toString(maxchars) +
" must conform to exactly one of available sub-schemas, but not more " +
schema.toString(maxchars)).add(errors);
} else
return null;
}
}
class CheckNot implements Instruction {
Instruction I;
Json schema;
public CheckNot(Instruction I, Json schema) {
this.I = I;
this.schema = schema;
}
public Json apply(Json param) {
if (I.apply(param) != null)
return null;
else
return Json.array().add("Element " + param.toString(maxchars) +
" must NOT conform to the schema " + schema.toString(maxchars));
}
}
static class CheckSchemaDependency implements Instruction {
Instruction schema;
String property;
public CheckSchemaDependency(String property, Instruction schema) {
this.property = property;
this.schema = schema;
}
public Json apply(Json param) {
if (!param.isObject()) return null;
else if (!param.has(property)) return null;
else return (schema.apply(param));
}
}
class CheckPropertyDependency implements Instruction {
Json required;
String property;
public CheckPropertyDependency(String property, Json required) {
this.property = property;
this.required = required;
}
public Json apply(Json param) {
if (!param.isObject()) return null;
if (!param.has(property)) return null;
else {
Json errors = null;
for (Json p : required.asJsonList())
if (!param.has(p.asString()))
errors = maybeError(errors, Json.make("Conditionally required property " + p +
" missing from object " + param.toString(maxchars)));
return errors;
}
}
}
Instruction compile(Json S, Map<Json, Instruction> compiled) {
Instruction result = compiled.get(S);
if (result != null)
return result;
Sequence seq = new Sequence();
compiled.put(S, seq);
if (S.has("type") && !S.is("type", "any"))
seq.add(new CheckType(S.at("type").isString() ?
Json.array().add(S.at("type")) : S.at("type")));
if (S.has("enum"))
seq.add(new CheckEnum(S.at("enum")));
if (S.has("allOf")) {
Sequence sub = new Sequence();
for (Json x : S.at("allOf").asJsonList())
sub.add(compile(x, compiled));
seq.add(sub);
}
if (S.has("anyOf")) {
CheckAny any = new CheckAny();
any.schema = S.at("anyOf");
for (Json x : any.schema.asJsonList())
any.alternates.add(compile(x, compiled));
seq.add(any);
}
if (S.has("oneOf")) {
CheckOne any = new CheckOne();
any.schema = S.at("oneOf");
for (Json x : any.schema.asJsonList())
any.alternates.add(compile(x, compiled));
seq.add(any);
}
if (S.has("not"))
seq.add(new CheckNot(compile(S.at("not"), compiled), S.at("not")));
if (S.has("required") && S.at("required").isArray()) {
for (Json p : S.at("required").asJsonList())
seq.add(new CheckPropertyPresent(p.asString()));
}
CheckObject objectCheck = new CheckObject();
if (S.has("properties"))
for (Map.Entry<String, Json> p : S.at("properties").asJsonMap().entrySet())
objectCheck.props.add(objectCheck.new CheckProperty(
p.getKey(), compile(p.getValue(), compiled)));
if (S.has("patternProperties"))
for (Map.Entry<String, Json> p : S.at("patternProperties").asJsonMap().entrySet())
objectCheck.patternProps.add(objectCheck.new CheckPatternProperty(p.getKey(),
compile(p.getValue(), compiled)));
if (S.has("additionalProperties")) {
if (S.at("additionalProperties").isObject())
objectCheck.additionalSchema = compile(S.at("additionalProperties"), compiled);
else if (!S.at("additionalProperties").asBoolean())
objectCheck.additionalSchema = null; // means no additional properties allowed
}
if (S.has("minProperties"))
objectCheck.min = S.at("minProperties").asInteger();
if (S.has("maxProperties"))
objectCheck.max = S.at("maxProperties").asInteger();
if (!objectCheck.props.isEmpty() || !objectCheck.patternProps.isEmpty() ||
objectCheck.additionalSchema != any ||
objectCheck.min > 0 || objectCheck.max < Integer.MAX_VALUE)
seq.add(objectCheck);
CheckArray arrayCheck = new CheckArray();
if (S.has("items"))
if (S.at("items").isObject())
arrayCheck.schema = compile(S.at("items"), compiled);
else {
arrayCheck.schemas = new ArrayList<Instruction>();
for (Json s : S.at("items").asJsonList())
arrayCheck.schemas.add(compile(s, compiled));
}
if (S.has("additionalItems"))
if (S.at("additionalItems").isObject())
arrayCheck.additionalSchema = compile(S.at("additionalItems"), compiled);
else if (!S.at("additionalItems").asBoolean())
arrayCheck.additionalSchema = null;
if (S.has("uniqueItems"))
arrayCheck.uniqueitems = S.at("uniqueItems").asBoolean();
if (S.has("minItems"))
arrayCheck.min = S.at("minItems").asInteger();
if (S.has("maxItems"))
arrayCheck.max = S.at("maxItems").asInteger();
if (arrayCheck.schema != null || arrayCheck.schemas != null ||
arrayCheck.additionalSchema != any ||
arrayCheck.uniqueitems != null ||
arrayCheck.max < Integer.MAX_VALUE || arrayCheck.min > 0)
seq.add(arrayCheck);
CheckNumber numberCheck = new CheckNumber();
if (S.has("minimum"))
numberCheck.min = S.at("minimum").asDouble();
if (S.has("maximum"))
numberCheck.max = S.at("maximum").asDouble();
if (S.has("multipleOf"))
numberCheck.multipleOf = S.at("multipleOf").asDouble();
if (S.has("exclusiveMinimum"))
numberCheck.exclusiveMin = S.at("exclusiveMinimum").asBoolean();
if (S.has("exclusiveMaximum"))
numberCheck.exclusiveMax = S.at("exclusiveMaximum").asBoolean();
if (!Double.isNaN(numberCheck.min) || !Double.isNaN(numberCheck.max) || !Double.isNaN(numberCheck.multipleOf))
seq.add(numberCheck);
CheckString stringCheck = new CheckString();
if (S.has("minLength"))
stringCheck.min = S.at("minLength").asInteger();
if (S.has("maxLength"))
stringCheck.max = S.at("maxLength").asInteger();
if (S.has("pattern"))
stringCheck.pattern = Pattern.compile(S.at("pattern").asString());
if (stringCheck.min > 0 || stringCheck.max < Integer.MAX_VALUE || stringCheck.pattern != null)
seq.add(stringCheck);
if (S.has("dependencies"))
for (Map.Entry<String, Json> e : S.at("dependencies").asJsonMap().entrySet())
if (e.getValue().isObject())
seq.add(new CheckSchemaDependency(e.getKey(), compile(e.getValue(), compiled)));
else if (e.getValue().isArray())
seq.add(new CheckPropertyDependency(e.getKey(), e.getValue()));
else
seq.add(new CheckPropertyDependency(e.getKey(), Json.array(e.getValue())));
result = seq.seq.size() == 1 ? seq.seq.get(0) : seq;
compiled.put(S, result);
return result;
}
int maxchars = 50;
URI uri;
Json theschema;
Instruction start;
DefaultSchema(URI uri, Json theschema, Function<URI, Json> relativeReferenceResolver) {
try {
this.uri = uri == null ? new URI("") : uri;
if (relativeReferenceResolver == null)
relativeReferenceResolver = new Function<URI, Json>() {
public Json apply(URI docuri) {
try {
return Json.read(fetchContent(docuri.toURL()));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
};
this.theschema = theschema.dup();
this.theschema = expandReferences(this.theschema,
this.theschema,
this.uri,
new HashMap<String, Json>(),
new IdentityHashMap<Json, Json>(),
relativeReferenceResolver);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
this.start = compile(this.theschema, new IdentityHashMap<Json, Instruction>());
}
public Json validate(Json document) {
Json result = Json.object("ok", true);
Json errors = start.apply(document);
return errors == null ? result : result.set("errors", errors).set("ok", false);
}
public Json toJson() {
return theschema;
}
public Json generate(Json options) {
// TODO...
return Json.nil();
}
}
public static Schema schema(Json S) {
return new DefaultSchema(null, S, null);
}
public static Schema schema(URI uri) {
return schema(uri, null);
}
public static Schema schema(URI uri, Function<URI, Json> relativeReferenceResolver) {
try {
return new DefaultSchema(uri, Json.read(Json.fetchContent(uri.toURL())), relativeReferenceResolver);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static Schema schema(Json S, URI uri) {
return new DefaultSchema(uri, S, null);
}
public static class DefaultFactory implements Factory {
public Json nil() {
return new NullJson();
}
public Json bool(boolean x) {
return new BooleanJson(x ? Boolean.TRUE : Boolean.FALSE, null);
}
public Json string(String x) {
return new StringJson(x, null);
}
public Json raw(String x) {
return new RawJson(x, null);
}
public Json number(Number x) {
return new NumberJson(x, null);
}
public Json array() {
return new ArrayJson();
}
public Json object() {
return new ObjectJson();
}
public Json make(Object anything) {
if (anything == null)
return nil();
else if (anything instanceof Properties) {
Properties properties = (Properties) anything;
Json O = object();
for (Map.Entry<?, ?> x : properties.entrySet())
O.set(x.getKey().toString(), factory().make(x.getValue()));
return O;
} else if (anything instanceof Json)
return (Json) anything;
else if (anything instanceof String)
return factory().string((String) anything);
else if (anything instanceof JsonSerialization)
return ((JsonSerialization) anything).toJson();
else if (anything instanceof Class<?>)
return factory().string(((Class<?>) anything).getName());
else if (anything instanceof Collection<?>) {
Json L = array();
for (Object x : (Collection<?>) anything)
L.add(factory().make(x));
return L;
} else if (anything instanceof Map<?, ?>) {
Json O = object();
for (Map.Entry<?, ?> x : ((Map<?, ?>) anything).entrySet())
O.set(x.getKey().toString(), factory().make(x.getValue()));
return O;
} else if (anything instanceof Boolean)
return factory().bool((Boolean) anything);
else if (anything instanceof Number)
return factory().number((Number) anything);
else if (anything instanceof Enum) {
return factory().string(anything.toString());
} else if (anything instanceof MediaType) {
return factory().string(anything.toString());
} else if (anything instanceof Instant) {
return factory().string(anything.toString());
} else if (anything.getClass().isArray()) {
Class<?> comp = anything.getClass().getComponentType();
if (!comp.isPrimitive())
return Json.array((Object[]) anything);
Json A = array();
if (boolean.class == comp)
for (boolean b : (boolean[]) anything) A.add(b);
else if (byte.class == comp)
for (byte b : (byte[]) anything) A.add(b);
else if (char.class == comp)
for (char b : (char[]) anything) A.add(b);
else if (short.class == comp)
for (short b : (short[]) anything) A.add(b);
else if (int.class == comp)
for (int b : (int[]) anything) A.add(b);
else if (long.class == comp)
for (long b : (long[]) anything) A.add(b);
else if (float.class == comp)
for (float b : (float[]) anything) A.add(b);
else if (double.class == comp)
for (double b : (double[]) anything) A.add(b);
return A;
} else if (anything instanceof Principal) {
return factory().string(((Principal) anything).getName());
} else
throw new IllegalArgumentException("Don't know how to convert to Json : " + anything);
}
}
public static final Factory defaultFactory = new DefaultFactory();
private static Factory globalFactory = defaultFactory;
// TODO: maybe use initialValue thread-local method to attach global factory by default here...
private static ThreadLocal<Factory> threadFactory = new ThreadLocal<Factory>();
/**
* <p>Return the {@link Factory} currently in effect. This is the factory that the {@link #make(Object)} method
* will dispatch on upon determining the type of its argument. If you already know the type of element to construct,
* you can avoid the type introspection implicit to the make method and call the factory directly. This will result
* in an optimization. </p>
*
* @return the factory
*/
public static Factory factory() {
Factory f = threadFactory.get();
return f != null ? f : globalFactory;
}
public static void escape(CharSequence sequence, Appendable out) throws IOException {
escaper.escapeJsonString(sequence, out);
}
/**
* <p>
* Specify a global Json {@link Factory} to be used by all threads that don't have a specific thread-local factory
* attached to them.
* </p>
*
* @param factory The new global factory
*/
public static void setGlobalFactory(Factory factory) {
globalFactory = factory;
}
/**
* <p>
* Attach a thread-local Json {@link Factory} to be used specifically by this thread. Thread-local Json factories are
* the only means to have different {@link Factory} implementations used simultaneously in the same application
* (well, more accurately, the same ClassLoader).
* </p>
*
* @param factory the new thread local factory
*/
public static void attachFactory(Factory factory) {
threadFactory.set(factory);
}
/**
* <p>
* Clear the thread-local factory previously attached to this thread via the {@link #attachFactory(Factory)} method.
* The global factory takes effect after a call to this method.
* </p>
*/
public static void detachFactory() {
threadFactory.remove();
}
/**
* <p>
* Parse a JSON entity from its string representation.
* </p>
*
* @param jsonAsString A valid JSON representation as per the <a href="http://www.json.org">json.org</a> grammar.
* Cannot be <code>null</code>.
* @return The JSON entity parsed: an object, array, string, number or boolean, or null. Note that this method will
* never return the actual Java <code>null</code>.
*/
public static Json read(String jsonAsString) {
return (Json) new Reader().read(jsonAsString);
}
/**
* <p>
* Parse a JSON entity from a <code>URL</code>.
* </p>
*
* @param location A valid URL where to load a JSON document from. Cannot be <code>null</code>.
* @return The JSON entity parsed: an object, array, string, number or boolean, or null. Note that this method will
* never return the actual Java <code>null</code>.
*/
public static Json read(URL location) {
return (Json) new Reader().read(fetchContent(location));
}
/**
* <p>
* Parse a JSON entity from a {@link CharacterIterator}.
* </p>
*
* @param it A character iterator.
* @return the parsed JSON element
* @see #read(String)
*/
public static Json read(CharacterIterator it) {
return (Json) new Reader().read(it);
}
/**
* @return the <code>null Json</code> instance.
*/
public static Json nil() {
return factory().nil();
}
/**
* @return a newly constructed, empty JSON object.
*/
public static Json object() {
return factory().object();
}
/**
* <p>Return a new JSON object initialized from the passed list of
* name/value pairs. The number of arguments must be even. Each argument at an even position is taken to be a name
* for the following value. The name arguments are normally of type Java String, but they can be of any other type
* having an appropriate
* <code>toString</code> method. Each value is first converted
* to a <code>Json</code> instance using the {@link #make(Object)} method.
* </p>
*
* @param args A sequence of name value pairs.
* @return the new JSON object.
*/
public static Json object(Object... args) {
Json j = object();
if (args.length % 2 != 0)
throw new IllegalArgumentException("An even number of arguments is expected.");
for (int i = 0; i < args.length; i++)
j.set(args[i].toString(), factory().make(args[++i]));
return j;
}
/**
* @return a new constructed, empty JSON array.
*/
public static Json array() {
return factory().array();
}
/**
* <p>Return a new JSON array filled up with the list of arguments.</p>
*
* @param args The initial content of the array.
* @return the new JSON array
*/
public static Json array(Object... args) {
Json A = array();
for (Object x : args)
A.add(factory().make(x));
return A;
}
/**
* <p>
* Exposes some internal methods that are useful for {@link Json.Factory} implementations or other extension/layers
* of the library.
* </p>
*
* @author Borislav Iordanov
*/
public static class help {
/**
* <p>
* Perform JSON escaping so that ", <, >, etc. characters are properly encoded in the JSON string representation
* before returning to the client code. This is useful when serializing property names or string values.
* </p>
*/
public static String escape(String string) {
return escaper.escapeJsonString(string);
}
/**
* <p>
* Given a JSON Pointer, as per RFC 6901, return the nested JSON value within the <code>element</code> parameter.
* </p>
*/
public static Json resolvePointer(String pointer, Json element) {
return Json.resolvePointer(pointer, element);
}
}
/**
* <p>
* Convert an arbitrary Java instance to a {@link Json} instance.
* </p>
*
* <p>
* Maps, Collections and arrays are recursively copied where each of their elements concerted into <code>Json</code>
* instances as well. The keys of a {@link Map} parameter are normally strings, but anything with a meaningful
* <code>toString</code> implementation will work as well.
* </p>
*
* @param anything Any Java object that the current JSON factory in effect is capable of handling.
* @return The <code>Json</code>. This method will never return <code>null</code>. It will throw an
* {@link IllegalArgumentException} if it doesn't know how to convert the argument to a <code>Json</code> instance.
* @throws IllegalArgumentException when the concrete type of the parameter is unknown.
*/
public static Json make(Object anything) {
return factory().make(anything);
}
// end of static utility method section
Json enclosing = null;
int line;
int column;
protected Json() {
}
protected Json(Json enclosing) {
this.enclosing = enclosing;
}
public Json location(int line, int column) {
this.line = line;
this.column = column;
return this;
}
public int getLine() {
return line;
}
public int getColumn() {
return column;
}
/**
* <p>Return a string representation of <code>this</code> that does
* not exceed a certain maximum length. This is useful in constructing error messages or any other place where only a
* "preview" of the JSON element should be displayed. Some JSON structures can get very large and this method will
* help avoid string serializing the whole of them. </p>
*
* @param maxCharacters The maximum number of characters for the string representation.
* @return The string representation of this object.
*/
public String toString(int maxCharacters) {
return toString();
}
public String toPrettyString() {
return toString();
}
/**
* <p>Explicitly set the parent of this element. The parent is presumably an array
* or an object. Normally, there's no need to call this method as the parent is automatically set by the framework.
* You may need to call it however, if you implement your own {@link Factory} with your own implementations of the
* Json types.
* </p>
*
* @param enclosing The parent element.
*/
public void attachTo(Json enclosing) {
this.enclosing = enclosing;
}
/**
* @return the <code>Json</code> entity, if any, enclosing this
* <code>Json</code>. The returned value can be <code>null</code> or
* a <code>Json</code> object or list, but not one of the primitive types.
*/
public final Json up() {
return enclosing;
}
/**
* @return a clone (a duplicate) of this <code>Json</code> entity. Note that cloning is deep if array and objects.
* Primitives are also cloned, even though their values are immutable because the new enclosing entity (the result of
* the {@link #up()} method) may be different. since they are immutable.
*/
public Json dup() {
return this;
}
/**
* <p>Return the <code>Json</code> element at the specified index of this
* <code>Json</code> array. This method applies only to Json arrays.
* </p>
*
* @param index The index of the desired element.
* @return The JSON element at the specified index in this array.
*/
public Json at(int index) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Return the specified property of a <code>Json</code> object or <code>null</code> if there's no such property. This
* method applies only to Json objects.
* </p>
*
* @param property the property name.
* @return The JSON element that is the value of that property.
*/
public Json at(String property) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Return the specified property of a <code>Json</code> object if it exists. If it doesn't, then create a new
* property with value the <code>def</code> parameter and return that parameter.
* </p>
*
* @param property The property to return.
* @param def The default value to set and return in case the property doesn't exist.
*/
public final Json at(String property, Json def) {
Json x = at(property);
if (x == null) {
return def;
} else
return x;
}
/**
* <p>
* Return the specified property of a <code>Json</code> object if it exists. If it doesn't, then create a new
* property with value the <code>def</code> parameter and return that parameter.
* </p>
*
* @param property The property to return.
* @param def The default value to set and return in case the property doesn't exist.
*/
public final Json at(String property, Object def) {
return at(property, make(def));
}
/**
* <p>
* Return true if this <code>Json</code> object has the specified property and false otherwise.
* </p>
*
* @param property The name of the property.
*/
public boolean has(String property) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Return <code>true</code> if and only if this <code>Json</code> object has a property with the specified value. In
* particular, if the object has no such property <code>false</code> is returned.
* </p>
*
* @param property The property name.
* @param value The value to compare with. Comparison is done via the equals method. If the value is not an
* instance of <code>Json</code>, it is first converted to such an instance.
* @return
*/
public boolean is(String property, Object value) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Return <code>true</code> if and only if this <code>Json</code> array has an element with the specified value at
* the specified index. In particular, if the array has no element at this index, <code>false</code> is returned.
* </p>
*
* @param index The 0-based index of the element in a JSON array.
* @param value The value to compare with. Comparison is done via the equals method. If the value is not an instance
* of <code>Json</code>, it is first converted to such an instance.
* @return
*/
public boolean is(int index, Object value) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Add the specified <code>Json</code> element to this array.
* </p>
*
* @return this
*/
public Json add(Json el) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Add an arbitrary Java object to this <code>Json</code> array. The object is first converted to a <code>Json</code>
* instance by calling the static {@link #make} method.
* </p>
*
* @param anything Any Java object that can be converted to a Json instance.
* @return this
*/
public final Json add(Object anything) {
return add(make(anything));
}
/**
* <p>
* Remove the specified property from a <code>Json</code> object and return that property.
* </p>
*
* @param property The property to be removed.
* @return The property value or <code>null</code> if the object didn't have such a property to begin with.
*/
public Json atDel(String property) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Remove the element at the specified index from a <code>Json</code> array and return that element.
* </p>
*
* @param index The index of the element to delete.
* @return The element value.
*/
public Json atDel(int index) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Delete the specified property from a <code>Json</code> object.
* </p>
*
* @param property The property to be removed.
* @return this
*/
public Json delAt(String property) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Remove the element at the specified index from a <code>Json</code> array.
* </p>
*
* @param index The index of the element to delete.
* @return this
*/
public Json delAt(int index) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Remove the specified element from a <code>Json</code> array.
* </p>
*
* @param el The element to delete.
* @return this
*/
public Json remove(Json el) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Remove the specified Java object (converted to a Json instance) from a <code>Json</code> array. This is equivalent
* to
* <code>remove({@link #make(Object)})</code>.
* </p>
*
* @param anything The object to delete.
* @return this
*/
public final Json remove(Object anything) {
return remove(make(anything));
}
/**
* <p>
* Set a <code>Json</code> objects's property.
* </p>
*
* @param property The property name.
* @param value The value of the property.
* @return this
*/
public Json set(String property, Json value) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Set a <code>Json</code> objects's property.
* </p>
*
* @param property The property name.
* @param value The value of the property, converted to a <code>Json</code> representation with {@link #make}.
* @return this
*/
public final Json set(String property, Object value) {
return set(property, make(value));
}
/**
* <p>
* Change the value of a JSON array element. This must be an array.
* </p>
*
* @param index 0-based index of the element in the array.
* @param value the new value of the element
* @return this
*/
public Json set(int index, Object value) {
throw new UnsupportedOperationException();
}
/**
* <p>
* Combine this object or array with the passed in object or array. The types of
* <code>this</code> and the <code>object</code> argument must match. If both are
* <code>Json</code> objects, all properties of the parameter are added to <code>this</code>.
* If both are arrays, all elements of the parameter are appended to <code>this</code>
* </p>
*
* @param object The object or array whose properties or elements must be added to this Json object or array.
* @param options A sequence of options that governs the merging process.
* @return this
*/
public Json with(Json object, Json[] options) {
throw new UnsupportedOperationException();
}
/**
* Same as <code>{}@link #with(Json,Json...options)}</code> with each option argument converted to <code>Json</code>
* first.
*/
public Json with(Json object, Object... options) {
Json[] jopts = new Json[options.length];
for (int i = 0; i < jopts.length; i++)
jopts[i] = make(options[i]);
return with(object, jopts);
}
public Json replace(Json oldJson, Json newJson) {
if (this.isObject()) {
for (Map.Entry<String, Json> entry : this.asJsonMap().entrySet()) {
if (entry.getValue() == oldJson) {
entry.setValue(newJson);
return newJson;
}
}
throw new IllegalArgumentException();
} else {
throw new UnsupportedOperationException();
}
}
/**
* @return the underlying value of this <code>Json</code> entity. The actual value will be a Java Boolean, String,
* Number, Map, List or null. For complex entities (objects or arrays), the method will perform a deep copy and extra
* underlying values recursively for all nested elements.
*/
public Object getValue() {
throw new UnsupportedOperationException();
}
/**
* @return the boolean value of a boolean <code>Json</code> instance. Call {@link #isBoolean()} first if you're not
* sure this instance is indeed a boolean.
*/
public boolean asBoolean() {
throw new UnsupportedOperationException();
}
/**
* @return the string value of a string <code>Json</code> instance. Call {@link #isString()} first if you're not sure
* this instance is indeed a string.
*/
public String asString() {
throw new UnsupportedOperationException();
}
/**
* @return the integer value of a number <code>Json</code> instance. Call {@link #isNumber()} first if you're not
* sure this instance is indeed a number.
*/
public int asInteger() {
throw new UnsupportedOperationException();
}
/**
* @return the float value of a float <code>Json</code> instance. Call {@link #isNumber()} first if you're not sure
* this instance is indeed a number.
*/
public float asFloat() {
throw new UnsupportedOperationException();
}
/**
* @return the double value of a number <code>Json</code> instance. Call {@link #isNumber()} first if you're not sure
* this instance is indeed a number.
*/
public double asDouble() {
throw new UnsupportedOperationException();
}
/**
* @return the long value of a number <code>Json</code> instance. Call {@link #isNumber()} first if you're not sure
* this instance is indeed a number.
*/
public long asLong() {
throw new UnsupportedOperationException();
}
/**
* @return the short value of a number <code>Json</code> instance. Call {@link #isNumber()} first if you're not sure
* this instance is indeed a number.
*/
public short asShort() {
throw new UnsupportedOperationException();
}
/**
* @return the byte value of a number <code>Json</code> instance. Call {@link #isNumber()} first if you're not sure
* this instance is indeed a number.
*/
public byte asByte() {
throw new UnsupportedOperationException();
}
/**
* @return the first character of a string <code>Json</code> instance. Call {@link #isString()} first if you're not
* sure this instance is indeed a string.
*/
public char asChar() {
throw new UnsupportedOperationException();
}
/**
* @return a map of the properties of an object <code>Json</code> instance. The map is a clone of the object and can
* be modified safely without affecting it. Call {@link #isObject()} first if you're not sure this instance is indeed
* a
* <code>Json</code> object.
*/
public Map<String, Object> asMap() {
throw new UnsupportedOperationException();
}
/**
* @return the underlying map of properties of a <code>Json</code> object. The returned map is the actual object
* representation so any modifications to it are modifications of the <code>Json</code> object itself. Call
* {@link #isObject()} first if you're not sure this instance is indeed a
* <code>Json</code> object.
*/
public Map<String, Json> asJsonMap() {
throw new UnsupportedOperationException();
}
/**
* @return a list of the elements of a <code>Json</code> array. The list is a clone of the array and can be modified
* safely without affecting it. Call {@link #isArray()} first if you're not sure this instance is indeed a
* <code>Json</code> array.
*/
public List<Object> asList() {
throw new UnsupportedOperationException();
}
/**
* @return the underlying {@link List} representation of a <code>Json</code> array. The returned list is the actual
* array representation so any modifications to it are modifications of the <code>Json</code> array itself. Call
* {@link #isArray()} first if you're not sure this instance is indeed a
* <code>Json</code> array.
*/
public List<Json> asJsonList() {
throw new UnsupportedOperationException();
}
/**
* @return <code>true</code> if this is a <code>Json</code> null entity
* and <code>false</code> otherwise.
*/
public boolean isNull() {
return false;
}
/**
* @return <code>true</code> if this is a <code>Json</code> string entity
* and <code>false</code> otherwise.
*/
public boolean isString() {
return false;
}
/**
* @return <code>true</code> if this is a <code>Json</code> number entity
* and <code>false</code> otherwise.
*/
public boolean isNumber() {
return false;
}
/**
* @return <code>true</code> if this is a <code>Json</code> boolean entity
* and <code>false</code> otherwise.
*/
public boolean isBoolean() {
return false;
}
/**
* @return <code>true</code> if this is a <code>Json</code> array (i.e. list) entity
* and <code>false</code> otherwise.
*/
public boolean isArray() {
return false;
}
public boolean isRaw() {
return false;
}
/**
* @return <code>true</code> if this is a <code>Json</code> object entity
* and <code>false</code> otherwise.
*/
public boolean isObject() {
return false;
}
/**
* @return <code>true</code> if this is a <code>Json</code> primitive entity
* (one of string, number or boolean) and <code>false</code> otherwise.
*/
public boolean isPrimitive() {
return isString() || isNumber() || isBoolean();
}
/**
* <p>
* Json-pad this object as an argument to a callback function.
* </p>
*
* @param callback The name of the callback function. Can be null or empty, in which case no padding is done.
* @return The jsonpadded, stringified version of this object if the <code>callback</code> is not null or empty, or
* just the stringified version of the object.
*/
public String pad(String callback) {
return (callback != null && callback.length() > 0)
? callback + "(" + toString() + ");"
: toString();
}
//-------------------------------------------------------------------------
// END OF PUBLIC INTERFACE
//-------------------------------------------------------------------------
/**
* Return an object representing the complete configuration of a merge. The properties of the object represent paths
* of the JSON structure being merged and the values represent the set of options that apply to each path.
*
* @param options the configuration options
* @return the configuration object
*/
protected Json collectWithOptions(Json... options) {
Json result = object();
for (Json opt : options) {
if (opt.isString()) {
if (!result.has(""))
result.set("", object());
result.at("").set(opt.asString(), true);
} else {
if (!opt.has("for"))
opt.set("for", array(""));
Json forPaths = opt.at("for");
if (!forPaths.isArray())
forPaths = array(forPaths);
for (Json path : forPaths.asJsonList()) {
if (!result.has(path.asString()))
result.set(path.asString(), object());
Json at_path = result.at(path.asString());
at_path.set("merge", opt.is("merge", true));
at_path.set("dup", opt.is("dup", true));
at_path.set("sort", opt.is("sort", true));
at_path.set("compareBy", opt.at("compareBy", nil()));
}
}
}
return result;
}
static class NullJson extends Json {
private static final long serialVersionUID = 1L;
NullJson() {
}
NullJson(Json e) {
super(e);
}
public Object getValue() {
return null;
}
public Json dup() {
return new NullJson();
}
public boolean isNull() {
return true;
}
public String toString() {
return "null";
}
public List<Object> asList() {
return (List<Object>) Collections.singletonList(null);
}
public int hashCode() {
return 0;
}
public boolean equals(Object x) {
return x instanceof NullJson;
}
}
/**
* <p>
* Set the parent (i.e. enclosing element) of Json element.
* </p>
*
* @param el
* @param parent
*/
static void setParent(Json el, Json parent) {
if (el.enclosing == null)
el.enclosing = parent;
else if (el.enclosing instanceof ParentArrayJson)
((ParentArrayJson) el.enclosing).L.add(parent);
else {
ParentArrayJson A = new ParentArrayJson();
A.L.add(el.enclosing);
A.L.add(parent);
el.enclosing = A;
}
}
/**
* <p>
* Remove/unset the parent (i.e. enclosing element) of Json element.
* </p>
*
* @param el
* @param parent
*/
static void removeParent(Json el, Json parent) {
if (el.enclosing == parent)
el.enclosing = null;
else if (el.enclosing.isArray()) {
ArrayJson A = (ArrayJson) el.enclosing;
int idx = 0;
while (A.L.get(idx) != parent && idx < A.L.size()) idx++;
if (idx < A.L.size())
A.L.remove(idx);
}
}
static class BooleanJson extends Json {
private static final long serialVersionUID = 1L;
boolean val;
BooleanJson() {
}
BooleanJson(Json e) {
super(e);
}
BooleanJson(Boolean val, Json e) {
super(e);
this.val = val;
}
public Object getValue() {
return val;
}
public Json dup() {
return new BooleanJson(val, null);
}
public boolean asBoolean() {
return val;
}
public boolean isBoolean() {
return true;
}
public String toString() {
return val ? "true" : "false";
}
@SuppressWarnings("unchecked")
public List<Object> asList() {
return (List<Object>) (List<?>) Collections.singletonList(val);
}
public int hashCode() {
return val ? 1 : 0;
}
public boolean equals(Object x) {
return x instanceof BooleanJson && ((BooleanJson) x).val == val;
}
}
static class StringJson extends Json {
private static final long serialVersionUID = 1L;
String val;
StringJson() {
}
StringJson(Json e) {
super(e);
}
StringJson(String val, Json e) {
super(e);
this.val = val;
}
public Json dup() {
return new StringJson(val, null);
}
public boolean isString() {
return true;
}
public Object getValue() {
return val;
}
public String asString() {
return val;
}
public int asInteger() {
return Integer.parseInt(val);
}
public float asFloat() {
return Float.parseFloat(val);
}
public double asDouble() {
return Double.parseDouble(val);
}
public long asLong() {
return Long.parseLong(val);
}
public short asShort() {
return Short.parseShort(val);
}
public byte asByte() {
return Byte.parseByte(val);
}
public char asChar() {
return val.charAt(0);
}
@SuppressWarnings("unchecked")
public List<Object> asList() {
return (List<Object>) (List<?>) Collections.singletonList(val);
}
public String toString() {
return '"' + escaper.escapeJsonString(val) + '"';
}
public String toString(int maxCharacters) {
if (val.length() <= maxCharacters)
return toString();
else
return '"' + escaper.escapeJsonString(val.subSequence(0, maxCharacters)) + "...\"";
}
public int hashCode() {
return val.hashCode();
}
public boolean equals(Object x) {
return x instanceof StringJson && ((StringJson) x).val.equals(val);
}
}
static class RawJson extends StringJson {
public RawJson(String val, Json e) {
super(val, e);
}
public String toString() {
return val;
}
@Override
public String toPrettyString() {
return toPrettyStringImpl(1);
}
String toPrettyStringImpl(int ident) {
return val;
}
@Override
public boolean isRaw() {
return true;
}
}
static class NumberJson extends Json {
private static final long serialVersionUID = 1L;
Number val;
NumberJson() {
}
NumberJson(Json e) {
super(e);
}
NumberJson(Number val, Json e) {
super(e);
this.val = val;
}
public Json dup() {
return new NumberJson(val, null);
}
public boolean isNumber() {
return true;
}
public Object getValue() {
return val;
}
public String asString() {
return val.toString();
}
public int asInteger() {
return val.intValue();
}
public float asFloat() {
return val.floatValue();
}
public double asDouble() {
return val.doubleValue();
}
public long asLong() {
return val.longValue();
}
public short asShort() {
return val.shortValue();
}
public byte asByte() {
return val.byteValue();
}
@SuppressWarnings("unchecked")
public List<Object> asList() {
return (List<Object>) (List<?>) Collections.singletonList(val);
}
public String toString() {
return val.toString();
}
public int hashCode() {
return val.hashCode();
}
public boolean equals(Object x) {
return x instanceof NumberJson && val.doubleValue() == ((NumberJson) x).val.doubleValue();
}
}
static class ArrayJson extends Json {
private static final long serialVersionUID = 1L;
List<Json> L = new ArrayList<Json>();
ArrayJson() {
}
ArrayJson(Json e) {
super(e);
}
public Json dup() {
ArrayJson j = new ArrayJson();
for (Json e : L) {
Json v = e.dup();
v.enclosing = j;
j.L.add(v);
}
return j;
}
public Json set(int index, Object value) {
Json jvalue = make(value);
L.set(index, jvalue);
setParent(jvalue, this);
return this;
}
public List<Json> asJsonList() {
return L;
}
public List<Object> asList() {
ArrayList<Object> A = new ArrayList<Object>();
for (Json x : L)
A.add(x.getValue());
return A;
}
public boolean is(int index, Object value) {
if (index < 0 || index >= L.size())
return false;
else
return L.get(index).equals(make(value));
}
public Object getValue() {
return asList();
}
public boolean isArray() {
return true;
}
public Json at(int index) {
return L.get(index);
}
public Json add(Json el) {
L.add(el);
setParent(el, this);
return this;
}
public Json remove(Json el) {
L.remove(el);
el.enclosing = null;
return this;
}
boolean isEqualJson(Json left, Json right) {
if (left == null)
return right == null;
else
return left.equals(right);
}
boolean isEqualJson(Json left, Json right, Json fields) {
if (fields.isNull())
return left.equals(right);
else if (fields.isString())
return isEqualJson(resolvePointer(fields.asString(), left),
resolvePointer(fields.asString(), right));
else if (fields.isArray()) {
for (Json field : fields.asJsonList())
if (!isEqualJson(resolvePointer(field.asString(), left),
resolvePointer(field.asString(), right)))
return false;
return true;
} else
throw new IllegalArgumentException("Compare by options should be either a property name or an array of property names: " + fields);
}
@SuppressWarnings({"unchecked", "rawtypes"})
int compareJson(Json left, Json right, Json fields) {
if (fields.isNull())
return ((Comparable) left.getValue()).compareTo(right.getValue());
else if (fields.isString()) {
Json leftProperty = resolvePointer(fields.asString(), left);
Json rightProperty = resolvePointer(fields.asString(), right);
return ((Comparable) leftProperty).compareTo(rightProperty);
} else if (fields.isArray()) {
for (Json field : fields.asJsonList()) {
Json leftProperty = resolvePointer(field.asString(), left);
Json rightProperty = resolvePointer(field.asString(), right);
int result = ((Comparable) leftProperty).compareTo(rightProperty);
if (result != 0)
return result;
}
return 0;
} else
throw new IllegalArgumentException("Compare by options should be either a property name or an array of property names: " + fields);
}
Json withOptions(Json array, Json allOptions, String path) {
Json opts = allOptions.at(path, object());
boolean dup = opts.is("dup", true);
Json compareBy = opts.at("compareBy", nil());
if (opts.is("sort", true)) {
int thisIndex = 0, thatIndex = 0;
while (thatIndex < array.asJsonList().size()) {
Json thatElement = array.at(thatIndex);
if (thisIndex == L.size()) {
L.add(dup ? thatElement.dup() : thatElement);
thisIndex++;
thatIndex++;
continue;
}
int compared = compareJson(at(thisIndex), thatElement, compareBy);
if (compared < 0) // this < that
thisIndex++;
else if (compared > 0) // this > that
{
L.add(thisIndex, dup ? thatElement.dup() : thatElement);
thatIndex++;
} else { // equal, ignore
thatIndex++;
}
}
} else {
for (Json thatElement : array.asJsonList()) {
boolean present = false;
for (Json thisElement : L)
if (isEqualJson(thisElement, thatElement, compareBy)) {
present = true;
break;
}
if (!present)
L.add(dup ? thatElement.dup() : thatElement);
}
}
return this;
}
public Json with(Json object, Json... options) {
if (object == null) return this;
if (!object.isArray())
add(object);
else if (options.length > 0) {
Json O = collectWithOptions(options);
return withOptions(object, O, "");
} else
// what about "enclosing" here? we don't have a provision where a Json
// element belongs to more than one enclosing elements...
L.addAll(((ArrayJson) object).L);
return this;
}
public Json atDel(int index) {
Json el = L.remove(index);
if (el != null)
el.enclosing = null;
return el;
}
public Json delAt(int index) {
Json el = L.remove(index);
if (el != null)
el.enclosing = null;
return this;
}
public String toString() {
return toString(Integer.MAX_VALUE);
}
public String toString(int maxCharacters) {
return toStringImpl(maxCharacters, new IdentityHashMap<Json, Json>());
}
String toPrettyStringImpl(int ident) {
StringBuilder sb = new StringBuilder("[ ");
for (Iterator<Json> i = L.iterator(); i.hasNext(); ) {
Json value = i.next();
String s = value.isObject() ? ((ObjectJson) value).toPrettyStringImpl(ident)
: value.isArray() ? ((ArrayJson) value).toPrettyStringImpl(ident)
: value.toString();
sb.append(s);
if (i.hasNext())
sb.append(",");
}
sb.append(" ]");
return sb.toString();
}
String toStringImpl(int maxCharacters, Map<Json, Json> done) {
StringBuilder sb = new StringBuilder("[");
for (Iterator<Json> i = L.iterator(); i.hasNext(); ) {
Json value = i.next();
String s = value.isObject() ? ((ObjectJson) value).toStringImpl(maxCharacters, done)
: value.isArray() ? ((ArrayJson) value).toStringImpl(maxCharacters, done)
: value.toString(maxCharacters);
if (sb.length() + s.length() > maxCharacters)
s = s.substring(0, Math.max(0, maxCharacters - sb.length()));
else
sb.append(s);
if (i.hasNext())
sb.append(",");
if (sb.length() >= maxCharacters) {
sb.append("...");
break;
}
}
sb.append("]");
return sb.toString();
}
public int hashCode() {
return L.hashCode();
}
public boolean equals(Object x) {
return x instanceof ArrayJson && ((ArrayJson) x).L.equals(L);
}
}
static class ParentArrayJson extends ArrayJson {
/**
*
*/
private static final long serialVersionUID = 1L;
}
static class ObjectJson extends Json {
private static final long serialVersionUID = 1L;
Map<String, Json> object = new LinkedHashMap<>();
ObjectJson() {
}
ObjectJson(Json e) {
super(e);
}
public Json dup() {
ObjectJson j = new ObjectJson();
for (Map.Entry<String, Json> e : object.entrySet()) {
Json v = e.getValue().dup();
v.enclosing = j;
j.object.put(e.getKey(), v);
}
return j;
}
public boolean has(String property) {
return object.containsKey(property);
}
public boolean is(String property, Object value) {
Json p = object.get(property);
if (p == null)
return false;
else
return p.equals(make(value));
}
public Json at(String property) {
return object.get(property);
}
protected Json withOptions(Json other, Json allOptions, String path) {
if (!allOptions.has(path))
allOptions.set(path, object());
Json options = allOptions.at(path, object());
boolean duplicate = options.is("dup", true);
if (options.is("merge", true)) {
for (Map.Entry<String, Json> e : other.asJsonMap().entrySet()) {
Json local = object.get(e.getKey());
if (local instanceof ObjectJson)
((ObjectJson) local).withOptions(e.getValue(), allOptions, path + "/" + e.getKey());
else if (local instanceof ArrayJson)
((ArrayJson) local).withOptions(e.getValue(), allOptions, path + "/" + e.getKey());
else
set(e.getKey(), duplicate ? e.getValue().dup() : e.getValue());
}
} else if (duplicate)
for (Map.Entry<String, Json> e : other.asJsonMap().entrySet())
set(e.getKey(), e.getValue().dup());
else
for (Map.Entry<String, Json> e : other.asJsonMap().entrySet())
set(e.getKey(), e.getValue());
return this;
}
public Json with(Json x, Json... options) {
if (x == null) return this;
if (!x.isObject())
throw new UnsupportedOperationException();
if (options.length > 0) {
Json O = collectWithOptions(options);
return withOptions(x, O, "");
} else for (Map.Entry<String, Json> e : x.asJsonMap().entrySet())
set(e.getKey(), e.getValue());
return this;
}
public Json set(String property, Json el) {
if (property == null)
throw new IllegalArgumentException("Null property names are not allowed, value is " + el);
if (el == null)
el = nil();
setParent(el, this);
object.put(property, el);
return this;
}
public Json atDel(String property) {
Json el = object.remove(property);
removeParent(el, this);
return el;
}
public Json delAt(String property) {
Json el = object.remove(property);
removeParent(el, this);
return this;
}
public Object getValue() {
return asMap();
}
public boolean isObject() {
return true;
}
public Map<String, Object> asMap() {
HashMap<String, Object> m = new HashMap<String, Object>();
for (Map.Entry<String, Json> e : object.entrySet())
m.put(e.getKey(), e.getValue().getValue());
return m;
}
@Override
public Map<String, Json> asJsonMap() {
return object;
}
public String toString() {
return toString(Integer.MAX_VALUE);
}
public String toString(int maxCharacters) {
return toStringImpl(maxCharacters, new IdentityHashMap<Json, Json>());
}
public String toPrettyString() {
return toPrettyStringImpl(1);
}
String toPrettyStringImpl(int ident) {
StringBuilder sb = new StringBuilder("{");
sb.append("\n");
for (Iterator<Map.Entry<String, Json>> i = object.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<String, Json> x = i.next();
for (int j = 0; j < ident; j++) sb.append(" ");
sb.append('"');
sb.append(escaper.escapeJsonString(x.getKey()));
sb.append('"');
sb.append(" : ");
String s = x.getValue().isObject() ? ((ObjectJson) x.getValue()).toPrettyStringImpl(ident + 1)
: x.getValue().isArray() ? ((ArrayJson) x.getValue()).toPrettyStringImpl(ident + 1)
: x.getValue().isRaw() ? ((RawJson) x.getValue()).toPrettyStringImpl(ident + 1)
: x.getValue().toString();
sb.append(s);
if (i.hasNext()) {
sb.append(",");
sb.append("\n");
}
}
sb.append("\n");
ident -= 1;
for (int j = 0; j < ident; j++) sb.append(" ");
sb.append("}");
return sb.toString();
}
String toStringImpl(int maxCharacters, Map<Json, Json> done) {
StringBuilder sb = new StringBuilder("{");
if (done.containsKey(this))
return sb.append("...}").toString();
done.put(this, this);
for (Iterator<Map.Entry<String, Json>> i = object.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<String, Json> x = i.next();
sb.append('"');
sb.append(escaper.escapeJsonString(x.getKey()));
sb.append('"');
sb.append(":");
String s = x.getValue().isObject() ? ((ObjectJson) x.getValue()).toStringImpl(maxCharacters, done)
: x.getValue().isArray() ? ((ArrayJson) x.getValue()).toStringImpl(maxCharacters, done)
: x.getValue().toString(maxCharacters);
if (sb.length() + s.length() > maxCharacters)
s = s.substring(0, Math.max(0, maxCharacters - sb.length()));
sb.append(s);
if (i.hasNext())
sb.append(",");
if (sb.length() >= maxCharacters) {
sb.append("...");
break;
}
}
sb.append("}");
return sb.toString();
}
public int hashCode() {
return object.hashCode();
}
public boolean equals(Object x) {
return x instanceof ObjectJson && ((ObjectJson) x).object.equals(object);
}
}
// ------------------------------------------------------------------------
// Extra utilities, taken from around the internet:
// ------------------------------------------------------------------------
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A utility class that is used to perform JSON escaping so that ", <, >, etc. characters are properly encoded in the
* JSON string representation before returning to the client code.
*
* <p>This class contains a single method to escape a passed in string value:
* <pre>
* String jsonStringValue = "beforeQuote\"afterQuote";
* String escapedValue = Escaper.escapeJsonString(jsonStringValue);
* </pre></p>
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
static Escaper escaper = new Escaper();
final static class Escaper {
private static final char[] HEX_CHARS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
public String escapeJsonString(CharSequence plainText) {
StringBuilder escapedString = new StringBuilder(plainText.length() + 20);
try {
escapeJsonString(plainText, escapedString);
} catch (IOException e) {
throw new RuntimeException(e);
}
return escapedString.toString();
}
private void escapeJsonString(CharSequence plainText, Appendable out) throws IOException {
int pos = 0; // Index just past the last char in plainText written to out.
int len = plainText.length();
for (int charCount, i = 0; i < len; i += charCount) {
int codePoint = Character.codePointAt(plainText, i);
charCount = Character.charCount(codePoint);
if (!isControlCharacter(codePoint) && !mustEscapeCharInJsString(codePoint)) {
continue;
}
out.append(plainText, pos, i);
pos = i + charCount;
switch (codePoint) {
case '\b':
out.append("\\b");
break;
case '\t':
out.append("\\t");
break;
case '\n':
out.append("\\n");
break;
case '\f':
out.append("\\f");
break;
case '\r':
out.append("\\r");
break;
case '\\':
out.append("\\\\");
break;
case '/':
out.append("\\/");
break;
case '"':
out.append("\\\"");
break;
default:
appendHexJavaScriptRepresentation(codePoint, out);
break;
}
}
out.append(plainText, pos, len);
}
private boolean mustEscapeCharInJsString(int codepoint) {
char c = (char) codepoint;
return c == '"' || c == '\\';
}
private static boolean isControlCharacter(int codePoint) {
// JSON spec defines these code points as control characters, so they must be escaped
return codePoint < 0x20
|| codePoint == 0x2028 // Line separator
|| codePoint == 0x2029 // Paragraph separator
|| (codePoint >= 0x7f && codePoint <= 0x9f);
}
private static void appendHexJavaScriptRepresentation(int codePoint, Appendable out)
throws IOException {
if (Character.isSupplementaryCodePoint(codePoint)) {
// Handle supplementary unicode values which are not representable in
// javascript. We deal with these by escaping them as two 4B sequences
// so that they will round-trip properly when sent from java to javascript
// and back.
char[] surrogates = Character.toChars(codePoint);
appendHexJavaScriptRepresentation(surrogates[0], out);
appendHexJavaScriptRepresentation(surrogates[1], out);
return;
}
out.append("\\u")
.append(HEX_CHARS[(codePoint >>> 12) & 0xf])
.append(HEX_CHARS[(codePoint >>> 8) & 0xf])
.append(HEX_CHARS[(codePoint >>> 4) & 0xf])
.append(HEX_CHARS[codePoint & 0xf]);
}
}
public static class MalformedJsonException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final int row;
private final int column;
public MalformedJsonException(String msg, int row, int column) {
super(msg + " at [" + row + "," + column + "]");
this.row = row;
this.column = column;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
}
private static class Reader {
private static final Object OBJECT_END = "}";
private static final Object ARRAY_END = "]";
private static final Object OBJECT_START = "{";
private static final Object ARRAY_START = "[";
private static final Object COLON = ":";
private static final Object COMMA = ",";
private static final HashSet<Object> PUNCTUATION = new HashSet<Object>(
Arrays.asList(OBJECT_END, OBJECT_START, ARRAY_END, ARRAY_START, COLON, COMMA));
public static final int FIRST = 0;
public static final int CURRENT = 1;
public static final int NEXT = 2;
private static final Map<Character, Character> escapes = new HashMap<>();
static {
escapes.put('"', '"');
escapes.put('\\', '\\');
escapes.put('/', '/');
escapes.put('b', '\b');
escapes.put('f', '\f');
escapes.put('n', '\n');
escapes.put('r', '\r');
escapes.put('t', '\t');
}
private CharacterIterator it;
private char c;
private Object token;
private final StringBuilder buf = new StringBuilder();
private int line = 1;
private int col = 1;
private char next() {
if (it.getIndex() == it.getEndIndex())
throw new MalformedJsonException("Reached end of input", line, col);
c = it.next();
if (c == '\n') {
line++;
col = 1;
} else {
col++;
}
return c;
}
private void previous() {
c = it.previous();
col--; // The parser doesn't backtrack through line-feeds, so we can avoid updating the row
}
private void skipWhiteSpace() {
do {
if (c == '/') {
next();
if (c == '*') {
// skip multiline comments
while (c != CharacterIterator.DONE)
if (next() == '*' && next() == '/')
break;
if (c == CharacterIterator.DONE)
throw new MalformedJsonException("Unterminated comment while parsing JSON string.", line, col);
} else if (c == '/')
while (c != '\n' && c != CharacterIterator.DONE)
next();
else {
previous();
break;
}
} else if (!Character.isWhitespace(c))
break;
} while (next() != CharacterIterator.DONE);
}
public Object read(CharacterIterator ci, int start) {
it = ci;
switch (start) {
case FIRST:
c = it.first();
break;
case CURRENT:
c = it.current();
break;
case NEXT:
c = it.next();
break;
}
return read();
}
public Object read(CharacterIterator it) {
return read(it, NEXT);
}
public Object read(String string) {
return read(new StringCharacterIterator(string), FIRST);
}
private void expected(Object expectedToken, Object actual) {
if (expectedToken != actual)
throw new MalformedJsonException("Expected " + expectedToken + ", but got " + actual + " instead", line, col);
}
@SuppressWarnings("unchecked")
private <T> T read() {
skipWhiteSpace();
char ch = c;
// We save the current location before reading the next token
int oLine = line;
int oCol = col;
next();
switch (ch) {
case '"':
token = readString();
break;
case '[':
token = readArray();
break;
case ']':
token = ARRAY_END;
break;
case ',':
token = COMMA;
break;
case '{':
token = readObject(oLine, oCol);
break;
case '}':
token = OBJECT_END;
break;
case ':':
token = COLON;
break;
case 't':
if (c != 'r' || next() != 'u' || next() != 'e')
throw new MalformedJsonException("Invalid JSON token: expected 'true' keyword.", line, col);
next();
token = factory().bool(Boolean.TRUE);
break;
case 'f':
if (c != 'a' || next() != 'l' || next() != 's' || next() != 'e')
throw new MalformedJsonException("Invalid JSON token: expected 'false' keyword.", line, col);
next();
token = factory().bool(Boolean.FALSE);
break;
case 'n':
if (c != 'u' || next() != 'l' || next() != 'l')
throw new MalformedJsonException("Invalid JSON token: expected 'null' keyword.", line, col);
next();
token = nil();
break;
default:
c = it.previous();
if (Character.isDigit(c) || c == '-') {
token = readNumber();
} else throw new MalformedJsonException("Invalid JSON", line, col);
}
return (T) token;
}
private Json readObjectKey() {
Object key = read();
if (key == null)
throw new MalformedJsonException("Missing object key (don't forget to put quotes!).", line, col);
else if (key == OBJECT_END)
return null;
else if (PUNCTUATION.contains(key))
throw new MalformedJsonException("Missing object key, found: " + key, line, col);
else
return (Json) key;
}
private Json readObject(int oLine, int oCol) {
Json ret = object().location(oLine, oCol);
Json key = readObjectKey();
while (token != OBJECT_END) {
expected(COLON, read()); // should be a colon
if (token != OBJECT_END) {
Json value = read();
// We set the location of the value to that of the key
value.location(key.getLine(), key.getColumn());
ret.set(key.asString(), value);
if (read() == COMMA) {
key = readObjectKey();
if (key == null || PUNCTUATION.contains(key.asString()))
throw new MalformedJsonException("Expected a property name, but found: " + key, line, col);
} else
expected(OBJECT_END, token);
}
}
return ret;
}
private Json readArray() {
Json ret = array().location(line, col);
Object value = read();
while (token != ARRAY_END) {
if (PUNCTUATION.contains(value))
throw new MalformedJsonException("Expected array element, but found: " + value, line, col);
ret.add((Json) value);
if (read() == COMMA) {
value = read();
if (value == ARRAY_END)
throw new MalformedJsonException("Expected array element, but found end of array after command.", line, col);
} else
expected(ARRAY_END, token);
}
return ret;
}
private Json readNumber() {
int nLine = line;
int nCol = col;
int length = 0;
boolean isFloatingPoint = false;
buf.setLength(0);
if (c == '-') {
add();
}
length += addDigits();
if (c == '.') {
add();
length += addDigits();
isFloatingPoint = true;
}
if (c == 'e' || c == 'E') {
add();
if (c == '+' || c == '-') {
add();
}
addDigits();
isFloatingPoint = true;
}
String s = buf.toString();
Number n = isFloatingPoint
? (length < 17) ? Double.valueOf(s) : new BigDecimal(s)
: (length < 20) ? Long.valueOf(s) : new BigInteger(s);
return factory().number(n).location(nLine, nCol);
}
private int addDigits() {
int ret;
for (ret = 0; Character.isDigit(c); ++ret) {
add();
}
return ret;
}
private Json readString() {
int nLine = line;
int nCol = col;
buf.setLength(0);
while (c != '"') {
if (c == '\\') {
next();
if (c == 'u') {
add(unicode());
} else {
Character value = escapes.get(c);
if (value != null) {
add(value);
}
}
} else {
add();
}
}
next();
return factory().string(buf.toString()).location(nLine, nCol);
}
private void add(char cc) {
buf.append(cc);
next();
}
private void add() {
add(c);
}
private char unicode() {
int value = 0;
for (int i = 0; i < 4; ++i) {
switch (next()) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + c - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + (c - 'a') + 10;
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + (c - 'A') + 10;
break;
}
}
return (char) value;
}
}
// END Reader
public static void main(String[] argv) {
try {
URI assetUri = new URI("https://raw.githubusercontent.com/pudo/aleph/master/aleph/schema/entity/asset.json");
URI schemaRoot = new URI("https://raw.githubusercontent.com/pudo/aleph/master/aleph/schema/");
// This fails
Json.schema(assetUri);
// And so does this
Json asset = Json.read(assetUri.toURL());
Json.schema(asset, schemaRoot);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
| 112,630
| 33.496478
| 165
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/internal/JsonSerialization.java
|
package org.infinispan.commons.dataconversion.internal;
/**
* @since 12.0
*/
public interface JsonSerialization {
Json toJson();
}
| 139
| 11.727273
| 55
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/internal/JsonUtils.java
|
package org.infinispan.commons.dataconversion.internal;
import java.util.Collection;
import java.util.function.Function;
import java.util.stream.Stream;
/**
* Utility function for {@link Json}
*
* @author Pedro Ruivo
* @since 13.0
*/
public final class JsonUtils {
private JsonUtils() {
}
public static <T> Json createJsonArray(Collection<T> collection) {
return createJsonArray(collection, Json::make);
}
public static <T> Json createJsonArray(Stream<T> stream) {
return createJsonArray(stream, Json::make);
}
public static <T> Json createJsonArray(Collection<T> collection, Function<T, Json> jsonFactory) {
return createJsonArray(collection.stream(), jsonFactory);
}
public static <T> Json createJsonArray(Stream<T> stream, Function<T, Json> jsonFactory) {
return stream.map(jsonFactory).collect(new JsonArrayCollector());
}
}
| 896
| 24.628571
| 100
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/dataconversion/internal/JsonArrayCollector.java
|
package org.infinispan.commons.dataconversion.internal;
import java.util.Collections;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
/**
* A {@link Collector} implementation that create a {@link Json} array.
*
* @author Pedro Ruivo
* @since 13.0
*/
public class JsonArrayCollector implements Collector<Json, JsonArrayCollector, Json> {
private final Json array;
public JsonArrayCollector() {
this.array = Json.array();
}
@Override
public Supplier<JsonArrayCollector> supplier() {
return () -> this;
}
@Override
public BiConsumer<JsonArrayCollector, Json> accumulator() {
return JsonArrayCollector::add;
}
@Override
public BinaryOperator<JsonArrayCollector> combiner() {
return JsonArrayCollector::combine;
}
@Override
public Function<JsonArrayCollector, Json> finisher() {
return JsonArrayCollector::getArray;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
public void add(Json json) {
this.array.add(json);
}
public JsonArrayCollector combine(JsonArrayCollector collector) {
collector.array.asJsonList().forEach(this::add);
return this;
}
public Json getArray() {
return array;
}
}
| 1,440
| 21.873016
| 86
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/stat/SimpleStateWithTimer.java
|
package org.infinispan.commons.stat;
import java.util.concurrent.TimeUnit;
/**
* A {@link SimpleStat} implementation that also updates a {@link TimerTracker} object.
*
* @author Pedro Ruivo
* @since 13.0
*/
public class SimpleStateWithTimer extends DefaultSimpleStat {
private volatile TimerTracker timerTracker;
@Override
public void record(long value) {
super.record(value);
TimerTracker local = this.timerTracker;
if (local != null) {
local.update(value, TimeUnit.NANOSECONDS);
}
}
@Override
public void setTimer(TimerTracker timer) {
this.timerTracker = timer;
}
}
| 639
| 21.068966
| 87
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/stat/DefaultSimpleStat.java
|
package org.infinispan.commons.stat;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
/**
* A default {@link SimpleStat} implementation.
*
* @author Pedro Ruivo
* @since 10.0
*/
public class DefaultSimpleStat implements SimpleStat {
private volatile Data data;
public DefaultSimpleStat() {
this.data = new Data();
}
@Override
public void record(long value) {
data.record(value);
}
@Override
public long getMin(long defaultValue) {
return data.getMin(defaultValue);
}
@Override
public long getMax(long defaultValue) {
return data.getMax(defaultValue);
}
@Override
public long getAverage(long defaultValue) {
return data.getAvg(defaultValue);
}
@Override
public long count() {
return data.count();
}
@Override
public void setTimer(TimerTracker timer) {
throw new UnsupportedOperationException();
}
@Override
public void reset() {
this.data = new Data();
}
private static class Data {
private final LongAdder count;
private final LongAdder sum;
private final AtomicLong min;
private final AtomicLong max;
private Data() {
count = new LongAdder();
sum = new LongAdder();
min = new AtomicLong(Long.MAX_VALUE);
max = new AtomicLong(Long.MIN_VALUE);
}
void record(long value) {
updateMin(value);
updateMax(value);
sum.add(value);
count.increment();
}
long getMin(long defaultValue) {
return count() == 0 ? defaultValue : min.get();
}
long getMax(long defaultValue) {
return count() == 0 ? defaultValue : max.get();
}
long getAvg(long defaultValue) {
long c = count();
return c == 0 ? defaultValue : sum.sum() / c;
}
long count() {
return count.sum();
}
private void updateMin(long value) {
long tmp = min.get();
while (value < tmp) {
if (min.compareAndSet(tmp, value)) {
return;
}
tmp = min.get();
}
}
private void updateMax(long value) {
long tmp = max.get();
while (value > tmp) {
if (max.compareAndSet(tmp, value)) {
return;
}
tmp = max.get();
}
}
}
}
| 2,437
| 20.385965
| 56
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/stat/SimpleStat.java
|
package org.infinispan.commons.stat;
/**
* A simple statistic recorder that computes the average, minimum and maximum value observed.
*
* @author Pedro Ruivo
* @since 10.0
*/
public interface SimpleStat {
SimpleStat EMPTY = new SimpleStat() {
};
default void record(long value) {
}
default long getMin(long defaultValue) {
return defaultValue;
}
default long getMax(long defaultValue) {
return defaultValue;
}
default long getAverage(long defaultValue) {
return defaultValue;
}
default long count() {
return 0;
}
default boolean isEmpty() {
return count() == 0;
}
default void setTimer(TimerTracker timer) {
}
default void reset() {
}
}
| 738
| 15.422222
| 93
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/stat/TimerTracker.java
|
package org.infinispan.commons.stat;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
/**
* Tracks a timer metric.
*
* @author Pedro Ruivo
* @since 13.0
*/
public interface TimerTracker {
/**
* Adds a record.
*
* @param duration The duration value.
*/
void update(Duration duration);
/**
* Adds a record.
*
* @param value The value.
* @param timeUnit The {@link TimeUnit} of the value.
*/
void update(long value, TimeUnit timeUnit);
}
| 512
| 16.1
| 56
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/tx/TransactionManagerImpl.java
|
package org.infinispan.commons.tx;
import java.util.UUID;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.InvalidTransactionException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.Util;
/**
* A simple {@link TransactionManager} implementation.
* <p>
* It provides the basic to handle {@link Transaction}s and supports any {@link javax.transaction.xa.XAResource}.
* <p>
* Implementation notes: <ul> <li>The state is kept in memory only.</li> <li>Does not support recover.</li> <li>Does not
* support multi-thread transactions. Although it is possible to execute the transactions in multiple threads, this
* transaction manager does not wait for them to complete. It is the application responsibility to wait before invoking
* {@link #commit()} or {@link #rollback()}</li> <li>The transaction should not block. It is no possible to {@link
* #setTransactionTimeout(int)} and this transaction manager won't rollback the transaction if it takes too long.</li>
* </ul>
* <p>
* If you need any of the requirements above, please consider use another implementation.
* <p>
* Also, it does not implement any 1-phase-commit optimization.
*
* @author Bela Ban
* @author Pedro Ruivo
* @since 9.1
*/
public abstract class TransactionManagerImpl implements TransactionManager {
private static final Log log = LogFactory.getLog(TransactionManagerImpl.class);
private static final ThreadLocal<Transaction> CURRENT_TRANSACTION = new ThreadLocal<>();
protected final UUID transactionManagerId = Util.threadLocalRandomUUID();
public static void dissociateTransaction() {
CURRENT_TRANSACTION.remove();
}
static void associateTransaction(Transaction tx) {
CURRENT_TRANSACTION.set(tx);
}
@Override
public Transaction getTransaction() {
return CURRENT_TRANSACTION.get();
}
@Override
public void begin() throws NotSupportedException, SystemException {
Transaction currentTx = getTransaction();
if (currentTx != null) {
throw new NotSupportedException(
Thread.currentThread() + " is already associated with a transaction (" + currentTx + ")");
}
associateTransaction(createTransaction());
}
@Override
public void commit() throws RollbackException, HeuristicMixedException,
HeuristicRollbackException, SecurityException,
IllegalStateException, SystemException {
try {
getTransactionAndFailIfNone().commit();
} finally {
dissociateTransaction();
}
}
@Override
public void rollback() throws IllegalStateException, SecurityException,
SystemException {
try {
getTransactionAndFailIfNone().rollback();
} finally {
dissociateTransaction();
}
}
@Override
public void setRollbackOnly() throws IllegalStateException, SystemException {
getTransactionAndFailIfNone().setRollbackOnly();
}
@Override
public int getStatus() throws SystemException {
Transaction tx = getTransaction();
return tx != null ? tx.getStatus() : Status.STATUS_NO_TRANSACTION;
}
@Override
public void setTransactionTimeout(int seconds) throws SystemException {
throw new SystemException("not supported");
}
@Override
public Transaction suspend() throws SystemException {
Transaction tx = getTransaction();
dissociateTransaction();
if (log.isTraceEnabled()) {
log.tracef("Suspending tx %s", tx);
}
return tx;
}
@Override
public void resume(Transaction tx) throws InvalidTransactionException, IllegalStateException, SystemException {
if (log.isTraceEnabled()) {
log.tracef("Resuming tx %s", tx);
}
associateTransaction(tx);
}
protected abstract Transaction createTransaction();
/**
* @return the current transaction (not null!)
*/
private Transaction getTransactionAndFailIfNone() {
Transaction transaction = CURRENT_TRANSACTION.get();
if (transaction == null) {
throw new IllegalStateException("no transaction associated with calling thread");
}
return transaction;
}
}
| 4,581
| 32.445255
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/tx/TransactionImpl.java
|
package org.infinispan.commons.tx;
import static java.lang.String.format;
import static org.infinispan.commons.util.concurrent.CompletableFutures.asCompletionException;
import static org.infinispan.commons.util.concurrent.CompletableFutures.completedFalse;
import static org.infinispan.commons.util.concurrent.CompletableFutures.completedNull;
import static org.infinispan.commons.util.concurrent.CompletableFutures.completedTrue;
import static org.infinispan.commons.util.concurrent.CompletableFutures.extractException;
import static org.infinispan.commons.util.concurrent.CompletableFutures.identity;
import static org.infinispan.commons.util.concurrent.CompletableFutures.rethrowExceptionIfPresent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.stream.Collectors;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* A basic {@link Transaction} implementation.
*
* @author Bela Ban
* @author Pedro Ruivo
* @since 9.1
*/
public class TransactionImpl implements Transaction {
/*
* Developer notes:
*
* => prepare() XA_RDONLY: the resource is finished and we shouldn't invoke the commit() or rollback().
* => prepare() XA_RB*: the resource is rolled back and we shouldn't invoke the rollback().
* //note// for both cases above, the commit() or rollback() will return XA_NOTA that we will ignore.
*
* => 1PC optimization: if we have a single XaResource, we can skip the prepare() and invoke commit(1PC).
* => Last Resource Commit optimization: if all the resources (except last) vote XA_OK or XA_RDONLY, we can skip the
* prepare() on the last resource and invoke commit(1PC).
* //note// both optimization not supported since we split the commit in 2 phases for debugging
*/
private static final Log log = LogFactory.getLog(TransactionImpl.class);
private static final String FORCE_ROLLBACK_MESSAGE = "Force rollback invoked. (debug mode)";
private final List<Synchronization> syncs;
private final List<XaResourceData> resources;
private final Object xidLock = new Object();
private volatile XidImpl xid;
private volatile int status;
private RollbackException firstRollbackException;
protected TransactionImpl() {
status = Status.STATUS_ACTIVE;
syncs = new ArrayList<>(2);
resources = new ArrayList<>(2);
}
private static boolean isRollbackCode(XAException ex) {
/*
XA_RBBASE the inclusive lower bound of the rollback codes
XA_RBROLLBACK the rollback was caused by an unspecified reason
XA_RBCOMMFAIL the rollback was caused by a communication failure
XA_RBDEADLOCK a deadlock was detected
XA_RBINTEGRITY a condition that violates the integrity of the resources was detected
XA_RBOTHER the resource manager rolled back the transaction branch for a reason not on this list
XA_RBPROTO a protocol error occurred in the resource manager
XA_RBTIMEOUT a transaction branch took too long
XA_RBTRANSIENT may retry the transaction branch
XA_RBEND the inclusive upper bound of the rollback codes
*/
return ex.errorCode >= XAException.XA_RBBASE && ex.errorCode <= XAException.XA_RBEND;
}
private static RollbackException newRollbackException(String message, Throwable cause) {
RollbackException exception = new RollbackException(message);
exception.initCause(cause);
return exception;
}
private static Throwable throwChecked(Throwable throwable) throws RollbackException, HeuristicMixedException, HeuristicRollbackException {
throwable = extractException(throwable);
if (throwable instanceof HeuristicMixedException) {
throw (HeuristicMixedException) throwable;
} else if (throwable instanceof HeuristicRollbackException) {
throw (HeuristicRollbackException) throwable;
} else if (throwable instanceof RollbackException) {
throw (RollbackException) throwable;
} else if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
}
return throwable;
}
private static void throwRuntimeException(Throwable throwable) {
if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
} else {
throw new RuntimeException(throwable);
}
}
private static Void checkThrowableForRollback(Throwable t) {
t = extractException(t);
if (t instanceof HeuristicMixedException || t instanceof HeuristicRollbackException) {
log.errorRollingBack(t);
SystemException systemException = new SystemException("Unable to rollback transaction");
systemException.initCause(t);
throw asCompletionException(systemException);
} else if (t instanceof RollbackException) {
//ignored
if (log.isTraceEnabled()) {
log.trace("RollbackException thrown while rolling back", t);
}
}
return null;
}
/**
* Attempt to commit this transaction.
*
* @throws RollbackException If the transaction was marked for rollback only, the transaction is rolled back
* and this exception is thrown.
* @throws HeuristicMixedException If a heuristic decision was made and some some parts of the transaction have
* been committed while other parts have been rolled back.
* @throws HeuristicRollbackException If a heuristic decision to roll back the transaction was made.
* @throws SecurityException If the caller is not allowed to commit this transaction.
*/
@Override
public void commit()
throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException {
try {
commitAsync(DefaultResourceConverter.INSTANCE).toCompletableFuture().get();
} catch (ExecutionException e) {
Throwable cause = throwChecked(e.getCause());
if (cause instanceof SecurityException) {
throw (SecurityException) cause;
}
throwRuntimeException(cause);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public CompletionStage<Void> commitAsync(TransactionResourceConverter converter) {
if (log.isTraceEnabled()) {
log.tracef("Transaction.commit() invoked in transaction with Xid=%s", xid);
}
if (isDone()) {
return CompletableFuture.failedFuture(new IllegalStateException("Transaction is done. Cannot commit transaction."));
}
return runPrepareAsync(converter)
.handle((____, ___) -> runCommitAsync(false, converter))
.thenCompose(Function.identity());
}
/**
* Rolls back this transaction.
*
* @throws IllegalStateException If the transaction is in a state where it cannot be rolled back. This could be
* because the transaction is no longer active, or because it is in the {@link
* Status#STATUS_PREPARED prepared state}.
* @throws SystemException If the transaction service fails in an unexpected way.
*/
@Override
public void rollback() throws IllegalStateException, SystemException {
try {
rollbackAsync(DefaultResourceConverter.INSTANCE).toCompletableFuture().get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
Throwable cause = extractException(e.getCause());
if (cause instanceof IllegalStateException) {
throw (IllegalStateException) cause;
} else if (cause instanceof SystemException) {
throw (SystemException) cause;
}
throwRuntimeException(cause);
}
}
public CompletionStage<Void> rollbackAsync(TransactionResourceConverter converter) {
if (log.isTraceEnabled()) {
log.tracef("Transaction.commit() invoked in transaction with Xid=%s", xid);
}
if (isDone()) {
return CompletableFuture.failedFuture(new IllegalStateException("Transaction is done. Cannot commit transaction."));
}
status = Status.STATUS_MARKED_ROLLBACK;
return asyncEndXaResources(converter)
.thenCompose(unused -> runCommitAsync(false, converter))
.exceptionally(TransactionImpl::checkThrowableForRollback);
}
/**
* Mark the transaction so that the only possible outcome is a rollback.
*
* @throws IllegalStateException If the transaction is not in an active state.
*/
@Override
public void setRollbackOnly() throws IllegalStateException {
if (log.isTraceEnabled()) {
log.tracef("Transaction.setRollbackOnly() invoked in transaction with Xid=%s", xid);
}
if (isDone()) {
throw new IllegalStateException("Transaction is done. Cannot change status");
}
markRollbackOnly(new RollbackException("Transaction marked as rollback only."));
}
/**
* Get the status of the transaction.
*
* @return The status of the transaction. This is one of the {@link Status} constants.
*/
@Override
public int getStatus() {
return status;
}
/**
* Enlist an XA resource with this transaction.
*
* @return <code>true</code> if the resource could be enlisted with this transaction, otherwise <code>false</code>.
* @throws RollbackException If the transaction is marked for rollback only.
* @throws IllegalStateException If the transaction is in a state where resources cannot be enlisted. This could be
* because the transaction is no longer active, or because it is in the {@link
* Status#STATUS_PREPARED prepared state}.
* @throws SystemException If the transaction service fails in an unexpected way.
*/
@Override
public boolean enlistResource(XAResource resource) throws RollbackException, IllegalStateException, SystemException {
if (log.isTraceEnabled()) {
log.tracef("Transaction.enlistResource(%s) invoked in transaction with Xid=%s", resource, xid);
}
checkStatusBeforeRegister("resource");
//avoid duplicates
for (XaResourceData other : resources) {
try {
if (other.xaResource.isSameRM(resource)) {
log.debug("Ignoring resource. It is already there.");
return true;
}
} catch (XAException e) {
//ignored
}
}
synchronized (xidLock) {
resources.add(new XaResourceData(resource));
}
try {
if (log.isTraceEnabled()) {
log.tracef("XaResource.start() invoked in transaction with Xid=%s", xid);
}
resource.start(xid, XAResource.TMNOFLAGS);
} catch (XAException e) {
if (isRollbackCode(e)) {
RollbackException exception = newRollbackException(
format("Resource %s rolled back the transaction while XaResource.start()", resource), e);
markRollbackOnly(exception);
log.errorEnlistingResource(e);
throw exception;
}
log.errorEnlistingResource(e);
throw new SystemException(e.getMessage());
}
return true;
}
/**
* De-list an XA resource from this transaction.
*
* @return <code>true</code> if the resource could be de-listed from this transaction, otherwise <code>false</code>.
* @throws IllegalStateException If the transaction is in a state where resources cannot be de-listed. This could be
* because the transaction is no longer active.
* @throws SystemException If the transaction service fails in an unexpected way.
*/
@Override
public boolean delistResource(XAResource xaRes, int flag)
throws IllegalStateException, SystemException {
throw new SystemException("not supported");
}
/**
* Register a {@link Synchronization} callback with this transaction.
*
* @throws RollbackException If the transaction is marked for rollback only.
* @throws IllegalStateException If the transaction is in a state where {@link Synchronization} callbacks cannot be
* registered. This could be because the transaction is no longer active, or because it
* is in the {@link Status#STATUS_PREPARED prepared state}.
*/
@Override
public void registerSynchronization(Synchronization sync) throws RollbackException, IllegalStateException {
if (log.isTraceEnabled()) {
log.tracef("Transaction.registerSynchronization(%s) invoked in transaction with Xid=%s", sync, xid);
}
checkStatusBeforeRegister("synchronization");
if (log.isTraceEnabled()) {
log.tracef("Registering synchronization handler %s", sync);
}
synchronized (xidLock) {
syncs.add(sync);
}
}
public Collection<XAResource> getEnlistedResources() {
return resources.stream().map(xaResourceData -> xaResourceData.xaResource).collect(Collectors.toUnmodifiableList());
}
public boolean runPrepare() {
return runPrepareAsync(DefaultResourceConverter.INSTANCE).toCompletableFuture().join();
}
public CompletionStage<Boolean> runPrepareAsync(TransactionResourceConverter resourceConverter) {
TransactionResourceConverter converter = resourceConverter == null ? DefaultResourceConverter.INSTANCE : resourceConverter;
if (log.isTraceEnabled()) {
log.tracef("asyncPrepare() invoked in transaction with Xid=%s", xid);
}
// notify Synchronizations
CompletionStage<Void> cf = asyncBeforeCompletion(converter);
// XaResource.end()
cf = cf.thenCompose(unused -> asyncEndXaResources(converter));
// XaResource.prepare()
return cf.thenCompose(unused -> {
if (status == Status.STATUS_MARKED_ROLLBACK) {
//no need for prepare since we are going to rollback
return completedFalse();
}
status = Status.STATUS_PREPARING;
return asyncPrepareXaResources(converter);
});
}
/**
* Runs the second phase of two-phase-commit protocol.
* <p>
* If {@code forceRollback} is {@code true}, then a {@link RollbackException} is thrown with the message {@link
* #FORCE_ROLLBACK_MESSAGE}.
*
* @param forceRollback force the transaction to rollback.
*/
public synchronized void runCommit(boolean forceRollback) //synchronized because of client transactions
throws HeuristicMixedException, HeuristicRollbackException, RollbackException {
try {
runCommitAsync(forceRollback, DefaultResourceConverter.INSTANCE).toCompletableFuture().get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
Throwable cause = throwChecked(e.getCause());
throwRuntimeException(cause);
}
}
public CompletionStage<Void> runCommitAsync(boolean forceRollback, TransactionResourceConverter resourceConverter) {
TransactionResourceConverter converter = resourceConverter == null ? DefaultResourceConverter.INSTANCE : resourceConverter;
if (log.isTraceEnabled()) {
log.tracef("runCommit(forceRollback=%b) invoked in transaction with Xid=%s", forceRollback, xid);
}
if (forceRollback) {
markRollbackOnly(new RollbackException(FORCE_ROLLBACK_MESSAGE));
}
boolean commit = status != Status.STATUS_MARKED_ROLLBACK;
CompletionStage<Void> stage = asyncFinishXaResources(commit, converter);
//notify Synchronizations
stage = stage.handle((__, t) -> {
CompletionStage<Void> s = asyncAfterCompletion(commit ? Status.STATUS_COMMITTED : Status.STATUS_ROLLEDBACK, converter);
if (t != null) {
return s.thenAccept(___ -> {
throw asCompletionException(t);
});
} else {
return s.thenAccept(___ -> rethrowExceptionIfPresent(hasRollbackException(forceRollback)));
}
}).thenCompose(identity());
TransactionManagerImpl.dissociateTransaction();
resources.clear();
return stage;
}
@Override
public String toString() {
return "TransactionImpl{" +
"xid=" + xid +
", status=" + Util.transactionStatusToString(status) +
'}';
}
public XidImpl getXid() {
return xid;
}
public void setXid(XidImpl xid) {
synchronized (xidLock) {
if (syncs.isEmpty() && resources.isEmpty()) {
this.xid = xid;
}
}
}
public Collection<Synchronization> getEnlistedSynchronization() {
return Collections.unmodifiableList(syncs);
}
/**
* Must be defined for increased performance
*/
@Override
public final int hashCode() {
return xid.hashCode();
}
@Override
public final boolean equals(Object obj) {
return this == obj;
}
private RollbackException hasRollbackException(boolean forceRollback) {
if (firstRollbackException != null) {
if (forceRollback && FORCE_ROLLBACK_MESSAGE.equals(firstRollbackException.getMessage())) {
//force rollback set. don't throw it.
return null;
}
return firstRollbackException;
}
return null;
}
private void markRollbackOnly(RollbackException e) {
if (status == Status.STATUS_MARKED_ROLLBACK) {
return;
}
status = Status.STATUS_MARKED_ROLLBACK;
if (firstRollbackException == null) {
firstRollbackException = e;
}
}
private CompletionStage<Void> asyncBeforeCompletion(TransactionResourceConverter converter) {
Iterator<Synchronization> iterator = syncs.iterator();
if (!iterator.hasNext()) {
return completedNull();
}
CompletionStage<Void> cf = beforeCompletion(iterator.next(), converter);
while (iterator.hasNext()) {
Synchronization synchronization = iterator.next();
cf = cf.thenCompose(unused -> beforeCompletion(synchronization, converter));
}
return cf;
}
private CompletionStage<Void> beforeCompletion(Synchronization s, TransactionResourceConverter converter) {
if (log.isTraceEnabled()) {
log.tracef("Synchronization.beforeCompletion() for %s", s);
}
return converter.convertSynchronization(s).asyncBeforeCompletion().exceptionally(t -> {
beforeCompletionFailed(s, t);
return null;
});
}
private void beforeCompletionFailed(Synchronization s, Throwable t) {
t = extractException(t);
markRollbackOnly(newRollbackException(format("Synchronization.beforeCompletion() for %s wants to rollback.", s), t));
log.beforeCompletionFailed(s.toString(), t);
}
private CompletionStage<Void> asyncAfterCompletion(int status, TransactionResourceConverter converter) {
Iterator<Synchronization> iterator = syncs.iterator();
if (!iterator.hasNext()) {
return completedNull();
}
CompletionStage<Void> cf = afterCompletion(iterator.next(), status, converter);
while (iterator.hasNext()) {
Synchronization synchronization = iterator.next();
cf = cf.thenCompose(unused -> afterCompletion(synchronization, status, converter));
}
syncs.clear();
return cf;
}
private static CompletionStage<Void> afterCompletion(Synchronization s, int status, TransactionResourceConverter converter) {
if (log.isTraceEnabled()) {
log.tracef("Synchronization.afterCompletion() for %s", s);
}
return converter.convertSynchronization(s).asyncAfterCompletion(status).exceptionally(t -> {
log.afterCompletionFailed(s.toString(), extractException(t));
return null;
});
}
private CompletionStage<Void> asyncEndXaResources(TransactionResourceConverter converter) {
Iterator<XaResourceData> iterator = resources.iterator();
if (!iterator.hasNext()) {
return completedNull();
}
CompletionStage<Void> cf = endXaResource(iterator.next().xaResource, converter);
while (iterator.hasNext()) {
XAResource resource = iterator.next().xaResource;
cf = cf.thenCompose(unused -> endXaResource(resource, converter));
}
return cf;
}
private CompletionStage<Void> endXaResource(XAResource resource, TransactionResourceConverter converter) {
if (log.isTraceEnabled()) {
log.tracef("XAResource.end() for %s", resource);
}
return converter.convertXaResource(resource).asyncEnd(xid, XAResource.TMSUCCESS).exceptionally(t -> {
endXaResourceFailed(resource, t);
return null;
});
}
private void endXaResourceFailed(XAResource resource, Throwable t) {
t = extractException(t);
String msg = t instanceof XAException ?
format("XaResource.end() for %s wants to rollback.", resource) :
format("Unexpected error in XaResource.end() for %s. Marked as rollback", resource);
markRollbackOnly(newRollbackException(msg, t));
log.xaResourceEndFailed(resource.toString(), t);
}
private CompletionStage<Boolean> asyncPrepareXaResources(TransactionResourceConverter converter) {
status = Status.STATUS_PREPARING;
Iterator<XaResourceData> iterator = resources.iterator();
if (!iterator.hasNext()) {
status = Status.STATUS_PREPARED;
return completedTrue();
}
CompletionStage<Boolean> cf = prepareXaResource(iterator.next(), converter);
while (iterator.hasNext()) {
XaResourceData data = iterator.next();
cf = cf.thenCompose(prepared -> prepared ? prepareXaResource(data, converter) : completedFalse());
}
return cf.whenComplete((prepared, ___) -> {
if (prepared) {
status = Status.STATUS_PREPARED;
}
});
}
private CompletionStage<Boolean> prepareXaResource(XaResourceData data, TransactionResourceConverter converter) {
if (log.isTraceEnabled()) {
log.tracef("XaResource.prepare() for %s", data.xaResource);
}
return converter.convertXaResource(data.xaResource).asyncPrepare(xid)
.thenApply(status -> {
data.status = status;
return true;
}).exceptionally(t -> {
prepareXaResourceFailed(data.xaResource, t);
return false;
});
}
private void prepareXaResourceFailed(XAResource resource, Throwable t) {
t = extractException(t);
String msg;
if (t instanceof XAException) {
if (log.isTraceEnabled()) {
log.tracef(t, "XaResource.prepare() for %s wants to rollback.", resource);
}
msg = format("XaResource.prepare() for %s wants to rollback.", resource);
} else {
msg = format("Unexpected error in XaResource.prepare() for %s. Rollback transaction.", resource);
log.unexpectedErrorFromResourceManager(t);
}
markRollbackOnly(newRollbackException(msg, t));
}
private CompletionStage<Void> asyncFinishXaResources(boolean commit, TransactionResourceConverter converter) {
Iterator<XaResourceData> iterator = resources.iterator();
if (!iterator.hasNext()) {
status = commit ? Status.STATUS_COMMITTED : Status.STATUS_ROLLEDBACK;
return completedNull();
}
XaResultCollector collector = new XaResultCollector(resources.size(), commit);
CompletionStage<Void> cf = commit ?
commitXaResource(iterator.next(), converter, collector) :
rollbackXaResource(iterator.next(), converter, collector);
while (iterator.hasNext()) {
XaResourceData data = iterator.next();
cf = cf.thenCompose(unused -> commit ?
commitXaResource(data, converter, collector) :
rollbackXaResource(data, converter, collector));
}
return cf.thenApply(unused -> {
checkCollector(collector, commit);
return null;
});
}
private CompletionStage<Void> commitXaResource(XaResourceData data, TransactionResourceConverter converter, XaResultCollector collector) {
if (data.status == XAResource.XA_RDONLY) {
log.tracef("Skipping XaResource.commit() since prepare status was XA_RDONLY for %s", data.xaResource);
return completedNull();
}
if (log.isTraceEnabled()) {
log.tracef("XaResource.commit() for %s", data.xaResource);
}
return converter.convertXaResource(data.xaResource).asyncCommit(xid, false)
.thenRun(collector)
.exceptionally(collector);
}
private CompletionStage<Void> rollbackXaResource(XaResourceData data, TransactionResourceConverter converter, XaResultCollector collector) {
if (data.status == XAResource.XA_RDONLY) {
log.tracef("Skipping XaResource.rollback() since prepare status was XA_RDONLY for %s", data.xaResource);
return completedNull();
}
if (log.isTraceEnabled()) {
log.tracef("XaResource.rollback() for %s", data.xaResource);
}
return converter.convertXaResource(data.xaResource).asyncRollback(xid)
.thenRun(collector)
.exceptionally(collector);
}
private void checkCollector(XaResultCollector collector, boolean commit) {
switch (collector.status()) {
case ERROR:
case HEURISTIC_MIXED:
status = Status.STATUS_UNKNOWN;
//some resources commits, other rollbacks and others we don't know...
HeuristicMixedException exception = new HeuristicMixedException();
collector.addSuppressedTo(exception);
status = Status.STATUS_UNKNOWN;
throw asCompletionException(exception);
case HEURISTIC_ROLLBACK:
HeuristicRollbackException e = new HeuristicRollbackException();
collector.addSuppressedTo(e);
status = Status.STATUS_UNKNOWN;
throw asCompletionException(e);
default:
break;
}
status = commit ? Status.STATUS_COMMITTED : Status.STATUS_ROLLEDBACK;
}
private void checkStatusBeforeRegister(String component) throws RollbackException, IllegalStateException {
if (status == Status.STATUS_MARKED_ROLLBACK) {
throw new RollbackException("Transaction has been marked as rollback only");
}
if (isDone()) {
throw new IllegalStateException(format("Transaction is done. Cannot register any more %s", component));
}
}
private boolean isDone() {
switch (status) {
case Status.STATUS_PREPARING:
case Status.STATUS_PREPARED:
case Status.STATUS_COMMITTING:
case Status.STATUS_COMMITTED:
case Status.STATUS_ROLLING_BACK:
case Status.STATUS_ROLLEDBACK:
case Status.STATUS_UNKNOWN:
return true;
}
return false;
}
private static class XaResourceData {
final XAResource xaResource;
volatile int status;
private XaResourceData(XAResource xaResource) {
this.xaResource = Objects.requireNonNull(xaResource);
}
}
private enum TxCompletableStatus {
NONE,
OK,
HEURISTIC_ROLLBACK,
HEURISTIC_MIXED,
ERROR
}
private static class XaResultCollector implements Runnable, Function<Throwable, Void> {
private TxCompletableStatus status = TxCompletableStatus.NONE;
private final List<Throwable> exceptions;
private final boolean commit;
XaResultCollector(int capacity, boolean commit) {
exceptions = new ArrayList<>(capacity);
this.commit = commit;
}
@Override
public synchronized void run() {
if (status == TxCompletableStatus.NONE) {
status = TxCompletableStatus.OK;
} else if (status == TxCompletableStatus.HEURISTIC_ROLLBACK) {
status = TxCompletableStatus.HEURISTIC_MIXED;
}
}
@Override
public synchronized Void apply(Throwable throwable) {
throwable = extractException(throwable);
log.errorCommittingTx(throwable);
exceptions.add(throwable);
if (throwable instanceof XAException) {
XAException e = (XAException) throwable;
switch (e.errorCode) {
case XAException.XA_HEURCOM:
case XAException.XA_HEURRB:
case XAException.XA_HEURMIX:
if (status == TxCompletableStatus.NONE) {
status = TxCompletableStatus.HEURISTIC_ROLLBACK;
} else if (status == TxCompletableStatus.OK) {
status = TxCompletableStatus.HEURISTIC_MIXED;
}
break;
case XAException.XAER_NOTA:
if (commit) {
if (status == TxCompletableStatus.NONE) {
status = TxCompletableStatus.HEURISTIC_ROLLBACK;
} else if (status == TxCompletableStatus.OK) {
status = TxCompletableStatus.HEURISTIC_MIXED;
}
} else {
// we are rolling back the transaction but the transaction does no exist.
// just ignore it
if (status == TxCompletableStatus.NONE) {
status = TxCompletableStatus.OK;
}
}
break;
default:
status = TxCompletableStatus.ERROR;
break;
}
} else {
status = TxCompletableStatus.ERROR;
}
return null;
}
synchronized TxCompletableStatus status() {
return status;
}
synchronized void addSuppressedTo(Throwable t) {
exceptions.forEach(t::addSuppressed);
}
}
}
| 30,942
| 38.772494
| 143
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/tx/XidImpl.java
|
package org.infinispan.commons.tx;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import javax.transaction.xa.Xid;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.marshall.Ids;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.commons.util.Util;
/**
* A {@link Xid} implementation.
* <p>
* If need to be serialized, use the methods {@link #writeTo(ObjectOutput, XidImpl)} and {@link #readFrom(ObjectInput)}
* or the {@link AdvancedExternalizer} in {@link #EXTERNALIZER}.
*
* @author Pedro Ruivo
* @since 9.1
*/
public class XidImpl implements Xid {
public static final AdvancedExternalizer<XidImpl> EXTERNALIZER = new Externalizer();
private final int formatId;
//first byte is the first byte of branch id.
//The rest of the array is the GlobalId + BranchId
private final byte[] rawId;
private transient int cachedHashCode;
protected XidImpl(int formatId, byte[] globalTransactionId, byte[] branchQualifier) {
this.formatId = formatId;
rawId = new byte[globalTransactionId.length + branchQualifier.length + 1];
rawId[0] = (byte) ((globalTransactionId.length + 1) & 0xFF); //first byte of branch id.
System.arraycopy(globalTransactionId, 0, rawId, 1, globalTransactionId.length);
System.arraycopy(branchQualifier, 0, rawId, globalTransactionId.length + 1, branchQualifier.length);
}
private XidImpl(int formatId, byte[] rawId) {
this.formatId = formatId;
this.rawId = rawId;
}
private static void validateArray(String name, byte[] array, int maxLength) {
if (array.length < 1 || array.length > maxLength) {
throw new IllegalArgumentException(name + " length should be between 1 and " + maxLength);
}
}
public static XidImpl create(int formatId, byte[] globalTransactionId, byte[] branchQualifier) {
validateArray("GlobalTransactionId", globalTransactionId, MAXGTRIDSIZE);
validateArray("BranchQualifier", branchQualifier, MAXBQUALSIZE);
return new XidImpl(formatId, globalTransactionId, branchQualifier);
}
public static void writeTo(ObjectOutput output, XidImpl xid) throws IOException {
output.writeInt(xid.formatId);
MarshallUtil.marshallByteArray(xid.rawId, output);
}
public static XidImpl readFrom(ObjectInput input) throws IOException {
return new XidImpl(input.readInt(), MarshallUtil.unmarshallByteArray(input));
}
public static XidImpl copy(Xid externalXid) {
return externalXid instanceof XidImpl ?
(XidImpl) externalXid :
new XidImpl(externalXid.getFormatId(), externalXid.getGlobalTransactionId(),
externalXid.getBranchQualifier());
}
public static String printXid(int formatId, byte[] globalTransaction, byte[] branchQualifier) {
return "Xid{formatId=" + formatId +
", globalTransactionId=" + Util.toHexString(globalTransaction) +
",branchQualifier=" + Util.toHexString(branchQualifier) +
"}";
}
@Override
public int getFormatId() {
return formatId;
}
@Override
public byte[] getGlobalTransactionId() {
return Arrays.copyOfRange(rawId, globalIdOffset(), branchQualifierOffset());
}
public ByteBuffer getGlobalTransactionIdAsByteBuffer() {
return ByteBuffer.wrap(rawId, globalIdOffset(), globalIdLength());
}
@Override
public byte[] getBranchQualifier() {
return Arrays.copyOfRange(rawId, branchQualifierOffset(), rawId.length);
}
public ByteBuffer getBranchQualifierAsByteBuffer() {
return ByteBuffer.wrap(rawId, branchQualifierOffset(), branchQualifierLength());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (o instanceof XidImpl) {
return formatId == ((XidImpl) o).formatId && Arrays.equals(rawId, ((XidImpl) o).rawId);
}
if (o instanceof Xid) {
if (formatId != ((Xid) o).getFormatId()) {
return false;
}
int firstByteOfBranch = rawId[0] & 0xFF;
return arraysEquals(((Xid) o).getGlobalTransactionId(), 1, firstByteOfBranch, firstByteOfBranch - 1) &&
arraysEquals(((Xid) o).getBranchQualifier(), firstByteOfBranch, rawId.length,
rawId.length - firstByteOfBranch);
}
return false;
}
@Override
public int hashCode() {
if (cachedHashCode == 0) {
int result = formatId;
//skip the control byte and use only the global transaction and branch qualifier
for (int i = 1; i < rawId.length; ++i) {
result = 37 * result + rawId[i];
}
cachedHashCode = result;
}
return cachedHashCode;
}
@Override
public String toString() {
int firstByteOfBranch = rawId[0] & 0xFF;
return "Xid{formatId=" + formatId +
", globalTransactionId=" + Util.toHexString(rawId, 1, firstByteOfBranch) +
",branchQualifier=" + Util.toHexString(rawId, firstByteOfBranch, rawId.length) +
"}";
}
protected int globalIdOffset() {
return 1;
}
protected int globalIdLength() {
return branchQualifierOffset() - 1; //we need to remove the control byte
}
protected int branchQualifierOffset() {
return (rawId[0] & 0xFF);
}
protected int branchQualifierLength() {
return rawId.length - branchQualifierOffset();
}
protected byte[] rawData() {
return rawId;
}
private boolean arraysEquals(byte[] other, int start, int end, int length) {
if (other.length != length) {
return false;
}
for (int i = start, j = 0; i < end; ++i, ++j) {
if (rawId[i] != other[j]) {
return false;
}
}
return true;
}
private static class Externalizer implements AdvancedExternalizer<XidImpl> {
@Override
public Set<Class<? extends XidImpl>> getTypeClasses() {
return Collections.singleton(XidImpl.class);
}
@Override
public Integer getId() {
return Ids.XID_IMPL;
}
@Override
public void writeObject(ObjectOutput output, XidImpl object) throws IOException {
writeTo(output, object);
}
@Override
public XidImpl readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return readFrom(input);
}
}
}
| 6,661
| 30.72381
| 119
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/tx/DefaultResourceConverter.java
|
package org.infinispan.commons.tx;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import jakarta.transaction.Synchronization;
import javax.transaction.xa.XAResource;
/**
* A default blocking implementation of {@link TransactionResourceConverter}.
* <p>
* It blocks the invocation thread, so it is not recommended to use.
*
* @since 14.0
*/
public enum DefaultResourceConverter implements TransactionResourceConverter {
INSTANCE;
@Override
public AsyncSynchronization convertSynchronization(Synchronization synchronization) {
return synchronization instanceof AsyncSynchronization ?
(AsyncSynchronization) synchronization :
new Sync(synchronization);
}
@Override
public AsyncXaResource convertXaResource(XAResource resource) {
return resource instanceof AsyncXaResource ?
(AsyncXaResource) resource :
new Xa(resource);
}
private static class Sync implements AsyncSynchronization {
private final Synchronization synchronization;
private Sync(Synchronization synchronization) {
this.synchronization = synchronization;
}
@Override
public CompletionStage<Void> asyncBeforeCompletion() {
CompletableFuture<Void> cf = new CompletableFuture<>();
try {
synchronization.beforeCompletion();
cf.complete(null);
} catch (Throwable t) {
cf.completeExceptionally(t);
}
return cf;
}
@Override
public CompletionStage<Void> asyncAfterCompletion(int status) {
CompletableFuture<Void> cf = new CompletableFuture<>();
try {
synchronization.afterCompletion(status);
cf.complete(null);
} catch (Throwable t) {
cf.completeExceptionally(t);
}
return cf;
}
}
private static class Xa implements AsyncXaResource {
private final XAResource resource;
private Xa(XAResource resource) {
this.resource = resource;
}
@Override
public CompletionStage<Void> asyncEnd(XidImpl xid, int flags) {
CompletableFuture<Void> cf = new CompletableFuture<>();
try {
resource.end(xid, flags);
cf.complete(null);
} catch (Throwable t) {
cf.completeExceptionally(t);
}
return cf;
}
@Override
public CompletionStage<Integer> asyncPrepare(XidImpl xid) {
CompletableFuture<Integer> cf = new CompletableFuture<>();
try {
cf.complete(resource.prepare(xid));
} catch (Throwable t) {
cf.completeExceptionally(t);
}
return cf;
}
@Override
public CompletionStage<Void> asyncCommit(XidImpl xid, boolean onePhase) {
CompletableFuture<Void> cf = new CompletableFuture<>();
try {
resource.commit(xid, onePhase);
cf.complete(null);
} catch (Throwable t) {
cf.completeExceptionally(t);
}
return cf;
}
@Override
public CompletionStage<Void> asyncRollback(XidImpl xid) {
CompletableFuture<Void> cf = new CompletableFuture<>();
try {
resource.rollback(xid);
cf.complete(null);
} catch (Throwable t) {
cf.completeExceptionally(t);
}
return cf;
}
}
}
| 3,478
| 27.516393
| 88
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/tx/AsyncSynchronization.java
|
package org.infinispan.commons.tx;
import java.util.concurrent.CompletionStage;
import jakarta.transaction.Synchronization;
/**
* Non-blocking {@link javax.transaction.Synchronization}.
*
* @since 14.0
*/
public interface AsyncSynchronization {
/**
* @return A {@link CompletionStage} which is completed with the result of {@link Synchronization#beforeCompletion()}.
* @see Synchronization#beforeCompletion()
*/
CompletionStage<Void> asyncBeforeCompletion();
/**
* @return A {@link CompletionStage} which is completed with the result of {@link Synchronization#afterCompletion(int)}.
* @see Synchronization#afterCompletion(int)
*/
CompletionStage<Void> asyncAfterCompletion(int status);
}
| 734
| 26.222222
| 123
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/tx/AsyncXaResource.java
|
package org.infinispan.commons.tx;
import java.util.concurrent.CompletionStage;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
* Non-blocking {@link XAResource}.
*
* @since 14.0
*/
public interface AsyncXaResource {
/**
* @return A {@link CompletionStage} which is completed with the result of {@link XAResource#end(Xid, int)}.
* @see XAResource#end(Xid, int)
*/
CompletionStage<Void> asyncEnd(XidImpl xid, int flags);
/**
* @return A {@link CompletionStage} which is completed with the result of {@link XAResource#prepare(Xid)}.
* @see XAResource#prepare(Xid)
*/
CompletionStage<Integer> asyncPrepare(XidImpl xid);
/**
* @return A {@link CompletionStage} which is completed with the result of {@link XAResource#commit(Xid, boolean)}
* @see XAResource#commit(Xid, boolean)
*/
CompletionStage<Void> asyncCommit(XidImpl xid, boolean onePhase);
/**
* @return A {@link CompletionStage} which is completed with the result of {@link XAResource#rollback(Xid)}
* @see XAResource#rollback(Xid)
*/
CompletionStage<Void> asyncRollback(XidImpl xid);
}
| 1,154
| 27.875
| 117
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/tx/TransactionResourceConverter.java
|
package org.infinispan.commons.tx;
import jakarta.transaction.Synchronization;
import javax.transaction.xa.XAResource;
/**
* Converts {@link Synchronization} and {@link XAResource} to {@link AsyncSynchronization} and {@link AsyncXaResource}.
*
* @since 14.0
*/
public interface TransactionResourceConverter {
/**
* @param synchronization The {@link Synchronization} to convert.
* @return An {@link AsyncSynchronization} instance of {@code synchronization}.
*/
AsyncSynchronization convertSynchronization(Synchronization synchronization);
/**
* @param resource The {@link XAResource} to convert.
* @return An {@link AsyncXaResource} instance of {@code resource}.
*/
AsyncXaResource convertXaResource(XAResource resource);
}
| 768
| 28.576923
| 119
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/tx/Util.java
|
package org.infinispan.commons.tx;
import jakarta.transaction.Status;
/**
* Transaction related util class.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class Util {
private Util() {
}
public static String transactionStatusToString(int status) {
switch (status) {
case Status.STATUS_ACTIVE:
return "ACTIVE";
case Status.STATUS_MARKED_ROLLBACK:
return "MARKED_ROLLBACK";
case Status.STATUS_PREPARED:
return "PREPARED";
case Status.STATUS_COMMITTED:
return "COMMITTED";
case Status.STATUS_ROLLEDBACK:
return "ROLLED_BACK";
case Status.STATUS_UNKNOWN:
return "UNKNOWN";
case Status.STATUS_NO_TRANSACTION:
return "NO_TRANSACTION";
case Status.STATUS_PREPARING:
return "PREPARING";
case Status.STATUS_COMMITTING:
return "COMMITTING";
case Status.STATUS_ROLLING_BACK:
return "ROLLING_BACK";
default:
return "unknown status (" + status + ")";
}
}
}
| 1,109
| 24.227273
| 63
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/tx/lookup/TransactionManagerLookup.java
|
package org.infinispan.commons.tx.lookup;
import jakarta.transaction.TransactionManager;
/**
* Factory interface, allows Cache or RemoteCache to use different transactional systems.
* Thread safety: it is possible for the same instance of this class to be used by multiple caches at the same time e.g.
* when the same instance is passed to multiple configurations.
* As infinispan supports parallel test startup, it might be possible for multiple threads to invoke the
* getTransactionManager() method concurrently, so it is highly recommended for instances of this class to be thread safe.
*
* @author Bela Ban, Aug 26 2003
* @since 4.0
*/
public interface TransactionManagerLookup {
/**
* Returns a new TransactionManager.
*
* @throws Exception if lookup failed
*/
TransactionManager getTransactionManager() throws Exception;
}
| 865
| 33.64
| 122
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/tx/lookup/LookupNames.java
|
package org.infinispan.commons.tx.lookup;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import jakarta.transaction.TransactionManager;
import org.infinispan.commons.util.Util;
/**
* The JDNI and {@link TransactionManager} factories we know of.
*
* @author Pedro Ruivo
* @since 9.3
*/
public final class LookupNames {
private LookupNames() {
}
/**
* JNDI locations for TransactionManagers we know of.
*/
public enum JndiTransactionManager {
JBOSS_AS_7("java:jboss/TransactionManager", "JBoss AS 7"),
JBOSS_AS_4_6("java:/TransactionManager", "JBoss AS 4 ~ 6, JRun4"),
RESIN_3("java:comp/TransactionManager", "Resin 3.x"),
GLASSFISH("java:appserver/TransactionManager", "Sun Glassfish"),
BORLAND_SUN("java:pm/TransactionManager", "Borland, Sun"),
WEBLOGIC("javax.transaction.TransactionManager", "BEA WebLogic"),
RESIN_ORION_JONAS("java:comp/UserTransaction", "Resin, Orion, JOnAS (JOTM)");
private final String jndiLookup;
private final String prettyName;
JndiTransactionManager(String jndiLookup, String prettyName) {
this.jndiLookup = jndiLookup;
this.prettyName = prettyName;
}
public String getJndiLookup() {
return jndiLookup;
}
public String getPrettyName() {
return prettyName;
}
}
/**
* TransactionManager factories we know of.
*/
public enum TransactionManagerFactory {
WEBSPHERE_51_6("com.ibm.ws.Transaction.TransactionManagerFactory", "WebSphere 5.1 and 6.0",
"getTransactionManager"),
WEBSPHERE_6("com.ibm.ejs.jts.jta.TransactionManagerFactory", "WebSphere 5.0", "getTransactionManager"),
WEBSPHERE_4("com.ibm.ejs.jts.jta.JTSXA", "WebSphere 4.0", "getTransactionManager"),
WILDFLY("org.wildfly.transaction.client.ContextTransactionManager", "Wildfly 11 and later", "getInstance"),
JBOSS_TM("com.arjuna.ats.jta.TransactionManager", "JBoss Standalone TM", "transactionManager");
private final String factoryClazz;
private final String prettyName;
private final String factoryMethod;
TransactionManagerFactory(String factoryClazz, String prettyName, String factoryMethod) {
this.factoryClazz = factoryClazz;
this.prettyName = prettyName;
this.factoryMethod = factoryMethod;
}
public String getFactoryClazz() {
return factoryClazz;
}
public String getPrettyName() {
return prettyName;
}
public TransactionManager tryLookup(ClassLoader classLoader) {
Class<?> clazz;
try {
clazz = Util.loadClassStrict(factoryClazz, classLoader);
Method method = clazz.getMethod(factoryMethod);
return (TransactionManager) method.invoke(null);
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
return null;
}
}
}
}
| 3,038
| 31.677419
| 128
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/maven/AbstractArtifact.java
|
package org.infinispan.commons.maven;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
/**
* @since 14.0
**/
public abstract class AbstractArtifact implements Artifact {
protected boolean verbose;
protected boolean force;
@Override
public Artifact verbose(boolean verbose) {
this.verbose = verbose;
return this;
}
@Override
public Artifact force(boolean force) {
this.force = force;
return this;
}
public static Path downloadFile(URL url, Path dest, boolean verbose, boolean force) throws IOException {
if (Files.exists(dest)) {
if (force) {
Files.delete(dest);
if (verbose) {
System.out.printf("Deleting previously downloaded '%s' for '%s'%n", dest, url);
}
} else {
if (verbose) {
System.out.printf("Using previously downloaded '%s' for '%s'%n", dest, url);
}
return dest;
}
}
HttpURLConnection connection = (HttpURLConnection) MavenSettings.init().openConnection(url);
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) {
if (verbose) {
System.out.printf("'%s' not found%n", url);
}
return null;
}
if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
|| statusCode == HttpURLConnection.HTTP_MOVED_PERM) {
url = new URL(connection.getHeaderField("Location"));
dest = dest.resolveSibling(getFilenameFromURL(url));
connection = (HttpURLConnection) url.openConnection();
}
try (InputStream bis = connection.getInputStream()) {
Files.createDirectories(dest.getParent());
Files.copy(bis, dest, StandardCopyOption.REPLACE_EXISTING);
if (verbose) {
System.out.printf("Downloaded '%s' to '%s'%n", url, dest);
}
return dest;
}
}
public static String getFilenameFromURL(URL url) {
String urlPath = url.getPath();
return urlPath.substring(urlPath.lastIndexOf('/') + 1);
}
}
| 2,277
| 29.373333
| 107
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/maven/Artifact.java
|
package org.infinispan.commons.maven;
import java.io.IOException;
import java.nio.file.Path;
/**
* @since 14.0
**/
public interface Artifact {
static Artifact fromString(String name) {
if ((name.startsWith("http://")) || name.startsWith("https://") || name.startsWith("file://") || name.startsWith("ftp://")) {
return new URLArtifact(name);
} else if (MavenArtifact.isMavenArtifact(name)) {
return MavenArtifact.fromString(name);
} else {
return new LocalArtifact(name);
}
}
Path resolveArtifact() throws IOException;
Artifact verbose(boolean verbose);
Artifact force(boolean force);
}
| 660
| 23.481481
| 131
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/maven/MavenSettings.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.infinispan.commons.maven;
import static org.infinispan.commons.configuration.io.xml.XmlPullParser.END_DOCUMENT;
import static org.infinispan.commons.configuration.io.xml.XmlPullParser.END_TAG;
import static org.infinispan.commons.configuration.io.xml.XmlPullParser.FEATURE_PROCESS_NAMESPACES;
import static org.infinispan.commons.configuration.io.xml.XmlPullParser.START_TAG;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import org.infinispan.commons.configuration.io.xml.MXParser;
import org.infinispan.commons.configuration.io.xml.XmlPullParser;
import org.infinispan.commons.configuration.io.xml.XmlPullParserException;
/**
* @author Tomaz Cerar (c) 2014 Red Hat Inc.
*/
public final class MavenSettings {
private static MavenSettings mavenSettings;
private Path settingsPath;
private Path localRepository = null;
private final List<String> remoteRepositories = new LinkedList<>();
private final Map<String, Profile> profiles = new HashMap<>();
private final List<String> activeProfileNames = new LinkedList<>();
private final List<Proxy> proxies = new ArrayList<>();
MavenSettings() {
configureDefaults();
}
public static MavenSettings init() throws IOException {
return init(null);
}
public static MavenSettings init(Path settingsPath) throws IOException {
if (mavenSettings != null && Objects.equals(mavenSettings.settingsPath, settingsPath)) {
return mavenSettings;
}
mavenSettings = new MavenSettings();
Path m2 = Paths.get(System.getProperty("user.home"), ".m2");
if (settingsPath == null) {
settingsPath = m2.resolve("settings.xml");
}
if (Files.notExists(settingsPath)) {
String mavenHome = System.getenv("M2_HOME");
if (mavenHome != null) {
settingsPath = Paths.get(mavenHome, "conf", "settings.xml");
}
}
mavenSettings.settingsPath = settingsPath;
if (Files.exists(settingsPath)) {
parseSettingsXml(settingsPath, mavenSettings);
}
if (mavenSettings.getLocalRepository() == null) {
Path repository = m2.resolve("repository");
mavenSettings.setLocalRepository(repository);
}
mavenSettings.resolveActiveSettings();
return mavenSettings;
}
static MavenSettings parseSettingsXml(Path settings, MavenSettings mavenSettings) throws IOException {
try {
final MXParser reader = new MXParser();
reader.setFeature(FEATURE_PROCESS_NAMESPACES, false);
InputStream source = Files.newInputStream(settings, StandardOpenOption.READ);
reader.setInput(source, null);
int eventType;
while ((eventType = reader.next()) != END_DOCUMENT) {
switch (eventType) {
case START_TAG: {
switch (reader.getName()) {
case "settings": {
parseSettings(reader, mavenSettings);
break;
}
}
}
default: {
break;
}
}
}
return mavenSettings;
} catch (XmlPullParserException e) {
throw new IOException("Could not parse maven settings.xml");
}
}
static void parseSettings(final XmlPullParser reader, MavenSettings mavenSettings) throws XmlPullParserException, IOException {
int eventType;
while ((eventType = reader.nextTag()) != END_DOCUMENT) {
switch (eventType) {
case END_TAG: {
return;
}
case START_TAG: {
switch (reader.getName()) {
case "localRepository": {
String localRepository = reader.nextText();
boolean localRepositoryNotDefinedViaProperty = mavenSettings.getLocalRepository() == null;
if (localRepositoryNotDefinedViaProperty && localRepository != null && !localRepository.trim().isEmpty()) {
mavenSettings.setLocalRepository(Paths.get(interpolateVariables(localRepository)));
}
break;
}
case "proxies": {
while ((eventType = reader.nextTag()) != END_DOCUMENT) {
if (eventType == START_TAG) {
switch (reader.getName()) {
case "proxy": {
parseProxy(reader, mavenSettings);
break;
}
}
} else {
break;
}
}
break;
}
case "profiles": {
while ((eventType = reader.nextTag()) != END_DOCUMENT) {
if (eventType == START_TAG) {
switch (reader.getName()) {
case "profile": {
parseProfile(reader, mavenSettings);
break;
}
}
} else {
break;
}
}
break;
}
case "activeProfiles": {
while ((eventType = reader.nextTag()) != END_DOCUMENT) {
if (eventType == START_TAG) {
switch (reader.getName()) {
case "activeProfile": {
mavenSettings.addActiveProfile(reader.nextText());
break;
}
}
} else {
break;
}
}
break;
}
default: {
skip(reader);
}
}
break;
}
default: {
throw new IOException("Unexpected content");
}
}
}
throw new IOException("Unexpected end of document");
}
static void parseProxy(final XmlPullParser reader, MavenSettings mavenSettings) throws XmlPullParserException, IOException {
int eventType;
Proxy proxy = new Proxy();
while ((eventType = reader.nextTag()) != END_DOCUMENT) {
if (eventType == START_TAG) {
switch (reader.getName()) {
case "id": {
proxy.setId(reader.nextText());
break;
}
case "active": {
proxy.setActive(Boolean.parseBoolean(reader.nextText()));
break;
}
case "protocol": {
proxy.setProtocol(reader.nextText());
break;
}
case "host": {
proxy.setHost(reader.nextText());
break;
}
case "port": {
proxy.setPort(Integer.parseInt(reader.nextText()));
break;
}
case "username": {
proxy.setUsername(reader.nextText());
break;
}
case "password": {
proxy.setPassword(reader.nextText());
break;
}
case "nonProxyHosts": {
proxy.setNonProxyHosts(reader.nextText());
break;
}
default: {
skip(reader);
}
}
} else {
break;
}
}
mavenSettings.addProxy(proxy);
}
static void parseProfile(final XmlPullParser reader, MavenSettings mavenSettings) throws XmlPullParserException, IOException {
int eventType;
Profile profile = new Profile();
while ((eventType = reader.nextTag()) != END_DOCUMENT) {
if (eventType == START_TAG) {
switch (reader.getName()) {
case "id": {
profile.setId(reader.nextText());
break;
}
case "repositories": {
while ((eventType = reader.nextTag()) != END_DOCUMENT) {
if (eventType == START_TAG) {
switch (reader.getName()) {
case "repository": {
parseRepository(reader, profile);
break;
}
}
} else {
break;
}
}
break;
}
default: {
skip(reader);
}
}
} else {
break;
}
}
mavenSettings.addProfile(profile);
}
static void parseRepository(final XmlPullParser reader, Profile profile) throws XmlPullParserException, IOException {
int eventType;
while ((eventType = reader.nextTag()) != END_DOCUMENT) {
if (eventType == START_TAG) {
switch (reader.getName()) {
case "url": {
profile.addRepository(reader.nextText());
break;
}
default: {
skip(reader);
}
}
} else {
break;
}
}
}
static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
void configureDefaults() {
//always add maven central
remoteRepositories.add("https://repo1.maven.org/maven2/");
String localRepositoryPath = System.getProperty("local.maven.repo.path");
if (localRepositoryPath != null && !localRepositoryPath.trim().isEmpty()) {
System.out.println("Please use 'maven.repo.local' instead of 'local.maven.repo.path'");
localRepository = Paths.get(localRepositoryPath.split(File.pathSeparator)[0]);
}
localRepositoryPath = System.getProperty("maven.repo.local");
if (localRepositoryPath != null && !localRepositoryPath.trim().isEmpty()) {
localRepository = Paths.get(localRepositoryPath);
}
String remoteRepository = System.getProperty("remote.maven.repo");
if (remoteRepository != null) {
for (String repo : remoteRepository.split(",")) {
if (!repo.endsWith("/")) {
repo += "/";
}
remoteRepositories.add(repo);
}
}
}
public void setLocalRepository(Path localRepository) {
this.localRepository = localRepository;
}
public Path getLocalRepository() {
return localRepository;
}
public List<String> getRemoteRepositories() {
return remoteRepositories;
}
public void addProfile(Profile profile) {
this.profiles.put(profile.getId(), profile);
}
public void addActiveProfile(String profileName) {
activeProfileNames.add(profileName);
}
public void addProxy(Proxy proxy) {
this.proxies.add(proxy);
}
public List<Proxy> getProxies() {
return this.proxies;
}
public Proxy getProxyFor(URL url) {
for (Proxy proxy : this.proxies) {
if (proxy.canProxyFor(url)) {
return proxy;
}
}
return null;
}
/**
* Opens a connection with appropriate proxy and credentials, if required.
*
* @param url The URL to open.
* @return The opened connection.
* @throws IOException If an error occurs establishing the connection.
*/
public URLConnection openConnection(URL url) throws IOException {
Proxy proxy = getProxyFor(url);
URLConnection conn = null;
if (proxy != null) {
conn = url.openConnection(proxy.getProxy());
proxy.authenticate(conn);
} else {
conn = url.openConnection();
}
return conn;
}
void resolveActiveSettings() {
for (String name : activeProfileNames) {
Profile p = profiles.get(name);
if (p != null) {
remoteRepositories.addAll(p.getRepositories());
}
}
}
static String interpolateVariables(String in) {
StringBuilder out = new StringBuilder();
int cur = 0;
int startLoc = -1;
while ((startLoc = in.indexOf("${", cur)) >= 0) {
out.append(in.substring(cur, startLoc));
int endLoc = in.indexOf("}", startLoc);
if (endLoc > 0) {
String name = in.substring(startLoc + 2, endLoc);
String value = null;
if (name.startsWith("env.")) {
value = System.getenv(name.substring(4));
} else {
value = System.getProperty(name);
}
if (value == null) {
value = "";
}
out.append(value);
} else {
out.append(in.substring(startLoc));
cur = in.length();
break;
}
cur = endLoc + 1;
}
out.append(in.substring(cur));
return out.toString();
}
static final class Proxy {
private String id;
private boolean active = true;
private String protocol = "http";
private String host;
private int port;
private String username;
private String password;
private Set<NonProxyHost> nonProxyHosts = new HashSet<>();
private AtomicReference<java.net.Proxy> netProxy = new AtomicReference<>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setNonProxyHosts(String nonProxyHosts) {
String[] specs = nonProxyHosts.split("\\|");
this.nonProxyHosts.clear();
for (String spec : specs) {
this.nonProxyHosts.add(new NonProxyHost(spec));
}
}
public boolean canProxyFor(URL url) {
for (NonProxyHost nonProxyHost : this.nonProxyHosts) {
if (nonProxyHost.matches(url)) {
return false;
}
}
return true;
}
public java.net.Proxy getProxy() {
return this.netProxy.updateAndGet(proxy -> {
if (proxy == null) {
proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP,
new InetSocketAddress(getHost(), getPort()));
}
return proxy;
});
}
public String getCredentialsBase64() {
Base64.Encoder encoder = Base64.getEncoder();
return encoder.encodeToString((this.username + ":" + this.password).getBytes());
}
public void authenticate(URLConnection conn) {
if (this.username == null && this.password == null) {
return;
}
String authz = "Basic " + getCredentialsBase64();
conn.addRequestProperty("Proxy-Authorization", authz);
}
}
static final class NonProxyHost {
private final Pattern pattern;
NonProxyHost(String spec) {
spec = spec.replace(".", "\\.");
spec = spec.replace("*", ".*");
spec = "^" + spec + "$";
this.pattern = Pattern.compile(spec);
}
boolean matches(URL url) {
return this.pattern.matcher(url.getHost()).matches();
}
}
static final class Profile {
private String id;
final List<String> repositories = new LinkedList<>();
Profile() {
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void addRepository(String url) {
if (!url.endsWith("/")) {
url += "/";
}
repositories.add(url);
}
public List<String> getRepositories() {
return repositories;
}
}
}
| 18,759
| 29.306947
| 130
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/maven/LocalArtifact.java
|
package org.infinispan.commons.maven;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Represents a local artifact.
*
* @since 14.0
**/
public class LocalArtifact extends AbstractArtifact {
final Path path;
public LocalArtifact(String path) {
this.path = Paths.get(path);
}
@Override
public Path resolveArtifact() {
if (Files.exists(path)) {
return path;
} else {
return null;
}
}
}
| 491
| 16.571429
| 53
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/maven/URLArtifact.java
|
package org.infinispan.commons.maven;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.infinispan.commons.util.Version;
/**
* Represents a generic URL artifact.
*
* @since 14.0
**/
public class URLArtifact extends AbstractArtifact {
final URL url;
public URLArtifact(String path) {
try {
url = new URL(path);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
@Override
public Path resolveArtifact() throws IOException {
Path tmpDir = Paths.get(System.getProperty("java.io.tmpdir"), Version.getBrandName().toLowerCase().replace(' ', '_'), "cache");
Files.createDirectories(tmpDir);
Path dest = tmpDir.resolve(getFilenameFromURL(url));
return downloadFile(url, dest, verbose, force);
}
}
| 927
| 24.777778
| 133
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/maven/MavenArtifact.java
|
package org.infinispan.commons.maven;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Maven artifact coordinate specification.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public final class MavenArtifact extends AbstractArtifact {
static final Pattern snapshotPattern = Pattern.compile("-\\d{8}\\.\\d{6}-\\d+$");
private static final Pattern VALID_PATTERN = Pattern.compile("^([-_a-zA-Z0-9.]+):([-_a-zA-Z0-9.]+):([-_a-zA-Z0-9.]+)(?::([-_a-zA-Z0-9.]+))?$");
private final String groupId;
private final String artifactId;
private final String version;
private final String classifier;
private String toString;
/**
* Construct a new instance.
*
* @param groupId the group ID (must not be {@code null})
* @param artifactId the artifact ID (must not be {@code null})
* @param version the version string (must not be {@code null})
* @param classifier the classifier string (must not be {@code null}, may be empty)
*/
public MavenArtifact(final String groupId, final String artifactId, final String version, final String classifier) {
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
this.classifier = classifier;
}
/**
* Construct a new instance with an empty classifier.
*
* @param groupId the group ID (must not be {@code null})
* @param artifactId the artifact ID (must not be {@code null})
* @param version the version string (must not be {@code null})
*/
public MavenArtifact(final String groupId, final String artifactId, final String version) {
this(groupId, artifactId, version, "");
}
/**
* Parse a string and produce artifact coordinates from it.
*
* @param string the string to parse (must not be {@code null})
* @return the artifact coordinates object (not {@code null})
*/
public static MavenArtifact fromString(String string) {
final Matcher matcher = VALID_PATTERN.matcher(string);
if (matcher.matches()) {
if (matcher.group(4) != null) {
return new MavenArtifact(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4));
} else {
return new MavenArtifact(matcher.group(1), matcher.group(2), matcher.group(3));
}
} else {
throw new IllegalArgumentException(string);
}
}
public static boolean isMavenArtifact(String string) {
return VALID_PATTERN.matcher(string).matches();
}
@Override
public Path resolveArtifact() throws IOException {
return resolveArtifact("jar");
}
Path resolveArtifact(String packaging) throws IOException {
String artifactRelativePath = relativeArtifactPath(File.separatorChar);
String artifactRelativeHttpPath = relativeArtifactPath('/');
final MavenSettings settings = MavenSettings.init();
final Path localRepository = settings.getLocalRepository();
final String pomPath = artifactRelativePath + ".pom";
if ("pom".equals(packaging)) {
// ignore classifier
Path pom = localRepository.resolve(pomPath);
if (Files.exists(pom)) {
return pom;
}
List<String> remoteRepos = settings.getRemoteRepositories();
if (remoteRepos.isEmpty()) {
return null;
}
for (String remoteRepository : remoteRepos) {
try {
String remotePomPath = remoteRepository + artifactRelativeHttpPath + ".pom";
downloadFile(new URL(remotePomPath), pom, verbose, force);
if (Files.exists(pom)) { //download successful
return pom;
}
} catch (IOException e) {
System.out.printf("Could not download '%s' from '%s' repository (%s)%n", artifactRelativePath, remoteRepository, e.getMessage());
// try next one
}
}
} else {
String classifier = this.classifier.isEmpty() ? "" : "-" + this.classifier;
String artifactPath = artifactRelativePath + classifier + "." + packaging;
Path fp = localRepository.resolve(artifactPath);
if (Files.exists(fp) && !force) {
return fp;
}
List<String> remoteRepos = settings.getRemoteRepositories();
if (remoteRepos.isEmpty()) {
return null;
}
final Path artifact = localRepository.resolve(artifactPath);
final Path pom = localRepository.resolve(pomPath);
for (String remoteRepository : remoteRepos) {
try {
String remotePomPath = remoteRepository + artifactRelativeHttpPath + ".pom";
String remoteArtifactPath = remoteRepository + artifactRelativeHttpPath + classifier + "." + packaging;
downloadFile(new URL(remotePomPath), pom, verbose, force);
if (!Files.exists(pom)) {
// no POM; skip it
continue;
}
downloadFile(new URL(remoteArtifactPath), artifact, verbose, force);
if (Files.exists(artifact)) { //download successful
return artifact;
}
} catch (IOException e) {
System.out.printf("Could not download '%s' from '%s' repository%n", artifactRelativePath, remoteRepository);
}
}
}
//could not find it in remote
if (verbose) {
System.out.println("Could not find in any remote repository");
}
return null;
}
/**
* Create a relative repository path for the given artifact coordinates.
*
* @param separator the separator character to use (typically {@code '/'} or {@link File#separatorChar})
* @return the path string
*/
public String relativeArtifactPath(char separator) {
StringBuilder builder = new StringBuilder(groupId.replace('.', separator));
builder.append(separator).append(artifactId).append(separator);
String pathVersion;
final Matcher versionMatcher = snapshotPattern.matcher(version);
if (versionMatcher.find()) {
// it's really a snapshot
pathVersion = version.substring(0, versionMatcher.start()) + "-SNAPSHOT";
} else {
pathVersion = version;
}
builder.append(pathVersion).append(separator).append(artifactId).append('-').append(version);
return builder.toString();
}
/**
* Get the string representation.
*
* @return the string representation
*/
public String toString() {
String toString = this.toString;
if (toString == null) {
final StringBuilder b = new StringBuilder(groupId.length() + artifactId.length() + version.length() + classifier.length() + 16);
b.append(groupId).append(':').append(artifactId).append(':').append(version);
if (!classifier.isEmpty()) {
b.append(':').append(classifier);
}
this.toString = toString = b.toString();
}
return toString;
}
}
| 7,246
| 37.962366
| 146
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/persistence/Store.java
|
package org.infinispan.commons.persistence;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Store. An annotation for identifying a persistent store and explicitly stating some of its characteristics.
*
* @author Ryan Emerson
* @since 9.0
* @deprecated since 11.0. To be removed in 14.0 ISPN-11866. Stores should utilise
* {@link org.infinispan.persistence.spi.NonBlockingStore.Characteristic}s to specify a store's capabilities.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Deprecated
public @interface Store {
/**
* Whether the store can be shared amongst nodes in a distributed/replicated cache
*/
boolean shared() default false;
}
| 797
| 30.92
| 110
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/jdkspecific/ProcessInfo.java
|
package org.infinispan.commons.jdkspecific;
import java.util.Arrays;
import java.util.List;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 11.0
**/
public class ProcessInfo {
private final String name;
private final long pid;
private final long ppid;
private final List<String> arguments;
private ProcessInfo(ProcessHandle handle) {
name = handle.info().command().orElse("-");
pid = handle.pid();
ppid = handle.parent().map(ProcessHandle::pid).orElse(-1l);
arguments = Arrays.asList(handle.info().arguments().orElse(new String[]{}));
}
public static ProcessInfo getInstance() {
return new ProcessInfo(ProcessHandle.current());
}
public static ProcessInfo of(Process process) {
return new ProcessInfo(process.toHandle());
}
public String getName() {
return name;
}
public long getPid() {
return pid;
}
public List<String> getArguments() {
return arguments;
}
public ProcessInfo getParent() {
if (ppid > 0) {
return new ProcessInfo(ProcessHandle.of(ppid).get());
} else {
return null;
}
}
@Override
public String toString() {
return "Process[jdk11]{" +
"name='" + name + '\'' +
", pid=" + pid +
", ppid=" + ppid +
", arguments=" + arguments +
'}';
}
}
| 1,405
| 22.04918
| 82
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/jdkspecific/ThreadCreator.java
|
package org.infinispan.commons.jdkspecific;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.util.Util;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 11.0
**/
public class ThreadCreator {
static org.infinispan.commons.spi.ThreadCreator INSTANCE = getInstance();
private static org.infinispan.commons.spi.ThreadCreator getInstance() {
try {
if (Boolean.getBoolean("org.infinispan.threads.virtual")) {
org.infinispan.commons.spi.ThreadCreator instance = Util.getInstance("org.infinispan.commons.jdk21.ThreadCreatorImpl", ThreadCreator.class.getClassLoader());
Log.CONTAINER.infof("Virtual threads support enabled");
return instance;
}
} catch (Throwable t) {
Log.CONTAINER.debugf("Could not initialize virtual threads", t);
}
return new ThreadCreatorImpl();
}
public static Thread createThread(ThreadGroup threadGroup, Runnable target, boolean lightweight) {
return INSTANCE.createThread(threadGroup, target, lightweight);
}
static class ThreadCreatorImpl implements org.infinispan.commons.spi.ThreadCreator {
@Override
public Thread createThread(ThreadGroup threadGroup, Runnable target, boolean lightweight) {
return new Thread(threadGroup, target);
}
}
}
| 1,355
| 33.769231
| 169
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/jdkspecific/CallerId.java
|
package org.infinispan.commons.jdkspecific;
public class CallerId {
static private final StackWalker WALKER = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
public static Class<?> getCallerClass(int n) {
return WALKER.walk(s ->
s.map(StackWalker.StackFrame::getDeclaringClass).skip(n).findFirst().orElse(null));
}
public static String getCallerMethodName(int n) {
return WALKER.walk(s ->
s.map(StackWalker.StackFrame::getMethodName).skip(n).findFirst().orElse(null));
}
}
| 547
| 33.25
| 112
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/jdkspecific/ClasspathURLStreamHandlerProvider.java
|
package org.infinispan.commons.jdkspecific;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.spi.URLStreamHandlerProvider;
import org.kohsuke.MetaInfServices;
/**
* A {@link URLStreamHandlerProvider} which handles URLs with protocol "classpath".
* It is automatically registered using the service loader pattern. It can be disabled
* by setting the system property <pre>org.infinispan.urlstreamhandler.skip</pre>
*
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
@MetaInfServices
public class ClasspathURLStreamHandlerProvider extends URLStreamHandlerProvider {
private final boolean skipProvider = Boolean.getBoolean("org.infinispan.urlstreamhandler.skip");
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
if (!skipProvider && "classpath".equals(protocol)) {
return new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u) throws IOException {
String path = u.getPath();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader == null ? null : classLoader.getResource(path);
if (resource == null) {
resource = ClassLoader.getSystemClassLoader().getResource(path);
}
if (resource != null) {
return resource.openConnection();
} else {
throw new FileNotFoundException(u.toString());
}
}
};
}
return null;
}
}
| 1,719
| 35.595745
| 99
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/jdkspecific/ProcessorInfo.java
|
package org.infinispan.commons.jdkspecific;
/**
* JDK 10+ implementation
*
* @author Tristan Tarrant
*/
public class ProcessorInfo {
private ProcessorInfo() {
}
public static int availableProcessors() {
int javaProcs = Runtime.getRuntime().availableProcessors();
int userProcs = Integer.getInteger("infinispan.activeprocessorcount", javaProcs);
return Math.min(userProcs, javaProcs);
}
}
| 425
| 21.421053
| 87
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/MarshallUtil.java
|
package org.infinispan.commons.marshall;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.Util;
import net.jcip.annotations.Immutable;
/**
* MarshallUtil.
*
* @author Galder Zamarreño
* @since 4.0
*/
@Immutable
public class MarshallUtil {
private static final byte NULL_VALUE = -1;
private static final Log log = LogFactory.getLog(MarshallUtil.class);
public static byte[] toByteArray(ByteBuffer buf) {
if (buf.getOffset() == 0 && buf.getLength() == buf.getBuf().length) {
return buf.getBuf();
} else {
byte[] bytes = new byte[buf.getLength()];
System.arraycopy(buf.getBuf(), buf.getOffset(), bytes, 0, buf.getLength());
return bytes;
}
}
/**
* Marshall the {@code map} to the {@code ObjectOutput}.
* <p>
* {@code null} maps are supported.
*
* @param map {@link Map} to marshall.
* @param out {@link ObjectOutput} to write. It must be non-null.
* @param <K> Key type of the map.
* @param <V> Value type of the map.
* @param <T> Type of the {@link Map}.
* @throws IOException If any of the usual Input/Output related exceptions occur.
*/
public static <K, V, T extends Map<K, V>> void marshallMap(T map, ObjectOutput out) throws IOException {
final int mapSize = map == null ? NULL_VALUE : map.size();
marshallSize(out, mapSize);
if (mapSize <= 0) return;
for (Map.Entry<K, V> me : map.entrySet()) {
out.writeObject(me.getKey());
out.writeObject(me.getValue());
}
}
/**
* Unmarshall the {@link Map}.
* <p>
* If the marshalled map is {@code null}, then the {@link MapBuilder} is not invoked.
*
* @param in {@link ObjectInput} to read.
* @param builder {@link MapBuilder} to create the concrete {@link Map} implementation.
* @return The populated {@link Map} created by the {@link MapBuilder} or {@code null}.
* @throws IOException If any of the usual Input/Output related exceptions occur.
* @throws ClassNotFoundException If the class of a serialized object cannot be found.
* @see #marshallMap(Map, ObjectOutput)
*/
public static <K, V, T extends Map<K, V>> T unmarshallMap(ObjectInput in, MapBuilder<K, V, T> builder) throws IOException, ClassNotFoundException {
final int size = unmarshallSize(in);
if (size == NULL_VALUE) {
return null;
}
final T map = Objects.requireNonNull(builder, "MapBuilder must be non-null").build(size);
for (int i = 0; i < size; i++) //noinspection unchecked
map.put((K) in.readObject(), (V) in.readObject());
return map;
}
/**
* Marshall the {@code map} to the {@code ObjectOutput}.
* <p>
* {@code null} maps are supported.
*
* @param map {@link Map} to marshall.
* @param out {@link ObjectOutput} to write. It must be non-null.
* @param <K> Key type of the map.
* @param <V> Value type of the map.
* @param <T> Type of the {@link Map}.
* @throws IOException If any of the usual Input/Output related exceptions occur.
*/
public static <K, V, T extends Map<K, V>> void marshallMap(T map, ElementWriter<K> keyWriter, ElementWriter<V> valueWrite, ObjectOutput out) throws IOException {
final int mapSize = map == null ? NULL_VALUE : map.size();
marshallSize(out, mapSize);
if (mapSize <= 0) return;
for (Map.Entry<K, V> me : map.entrySet()) {
keyWriter.writeTo(out, me.getKey());
valueWrite.writeTo(out, me.getValue());
}
}
/**
* Unmarshall the {@link Map}.
* <p>
* If the marshalled map is {@code null}, then the {@link MapBuilder} is not invoked.
*
* @param in {@link ObjectInput} to read.
* @param builder {@link MapBuilder} to create the concrete {@link Map} implementation.
* @return The populated {@link Map} created by the {@link MapBuilder} or {@code null}.
* @throws IOException If any of the usual Input/Output related exceptions occur.
* @throws ClassNotFoundException If the class of a serialized object cannot be found.
* @see #marshallMap(Map, ElementWriter, ElementWriter, ObjectOutput)
*/
public static <K, V, T extends Map<K, V>> T unmarshallMap(ObjectInput in, ElementReader<K> keyReader, ElementReader<V> valueReader, MapBuilder<K, V, T> builder) throws IOException, ClassNotFoundException {
final int size = unmarshallSize(in);
if (size == NULL_VALUE) {
return null;
}
final T map = Objects.requireNonNull(builder, "MapBuilder must be non-null").build(size);
for (int i = 0; i < size; i++) //noinspection unchecked
map.put(keyReader.readFrom(in), valueReader.readFrom(in));
return map;
}
/**
* Marshall the {@link UUID} by sending the most and lest significant bits.
* <p>
* This method supports {@code null} if {@code checkNull} is set to {@code true}.
*
* @param uuid {@link UUID} to marshall.
* @param out {@link ObjectOutput} to write.
* @param checkNull If {@code true}, it checks if {@code uuid} is {@code null}.
* @throws IOException If any of the usual Input/Output related exceptions occur.
*/
public static void marshallUUID(UUID uuid, ObjectOutput out, boolean checkNull) throws IOException {
if (checkNull) {
if (uuid == null) {
out.writeBoolean(true);
return;
}
out.writeBoolean(false);
}
out.writeLong(uuid.getMostSignificantBits());
out.writeLong(uuid.getLeastSignificantBits());
}
/**
* Unmarshall {@link UUID}.
*
* @param in {@link ObjectInput} to read.
* @param checkNull If {@code true}, it checks if the {@link UUID} marshalled was {@code null}.
* @return {@link UUID} marshalled.
* @throws IOException If any of the usual Input/Output related exceptions occur.
* @see #marshallUUID(UUID, ObjectOutput, boolean).
*/
public static UUID unmarshallUUID(ObjectInput in, boolean checkNull) throws IOException {
if (checkNull && in.readBoolean()) {
return null;
}
return new UUID(in.readLong(), in.readLong());
}
/**
* Marshall arrays.
* <p>
* This method supports {@code null} {@code array}.
*
* @param array Array to marshall.
* @param out {@link ObjectOutput} to write.
* @param <E> Array type.
* @throws IOException If any of the usual Input/Output related exceptions occur.
*/
public static <E> void marshallArray(E[] array, ObjectOutput out) throws IOException {
final int size = array == null ? NULL_VALUE : array.length;
marshallSize(out, size);
if (size <= 0) {
return;
}
for (int i = 0; i < size; ++i) {
out.writeObject(array[i]);
}
}
/**
* Unmarshall arrays.
*
* @param in {@link ObjectInput} to read.
* @param builder {@link ArrayBuilder} to build the array.
* @param <E> Array type.
* @return The populated array.
* @throws IOException If any of the usual Input/Output related exceptions occur.
* @throws ClassNotFoundException If the class of a serialized object cannot be found.
* @see #marshallArray(Object[], ObjectOutput).
*/
public static <E> E[] unmarshallArray(ObjectInput in, ArrayBuilder<E> builder) throws IOException, ClassNotFoundException {
final int size = unmarshallSize(in);
if (size == NULL_VALUE) {
return null;
}
final E[] array = Objects.requireNonNull(builder, "ArrayBuilder must be non-null").build(size);
for (int i = 0; i < size; ++i) {
//noinspection unchecked
array[i] = (E) in.readObject();
}
return array;
}
/**
* Marshall a {@link Collection}.
* <p>
* This method supports {@code null} {@code collection}.
*
* @param collection {@link Collection} to marshal.
* @param out {@link ObjectOutput} to write.
* @param <E> Collection's element type.
* @throws IOException If any of the usual Input/Output related exceptions occur.
*/
public static <E> void marshallCollection(Collection<E> collection, ObjectOutput out) throws IOException {
marshallCollection(collection, out, ObjectOutput::writeObject);
}
/**
* Marshall a {@link Collection}.
* <p>
* This method supports {@code null} {@code collection}.
*
* @param collection {@link Collection} to marshal.
* @param out {@link ObjectOutput} to write.
* @param writer {@link ElementWriter} that writes single element to the output.
* @param <E> Collection's element type.
* @throws IOException If any of the usual Input/Output related exceptions occur.
*/
public static <E> void marshallCollection(Collection<E> collection, ObjectOutput out, ElementWriter<E> writer) throws IOException {
final int size = collection == null ? NULL_VALUE : collection.size();
marshallSize(out, size);
if (size <= 0) {
return;
}
for (E e : collection) {
writer.writeTo(out, e);
}
}
/**
* Unmarshal a {@link Collection}.
*
* @param in {@link ObjectInput} to read.
* @param builder {@link CollectionBuilder} builds the concrete {@link Collection} based on size.
* @param reader {@link ElementReader} reads one element from the input.
* @param <E> Collection's element type.
* @param <T> {@link Collection} implementation.
* @return The concrete {@link Collection} implementation.
* @throws IOException If any of the usual Input/Output related exceptions occur.
* @throws ClassNotFoundException If the class of a serialized object cannot be found.
*/
public static <E, T extends Collection<E>> T unmarshallCollection(ObjectInput in, CollectionBuilder<E, T> builder, ElementReader<E> reader) throws IOException, ClassNotFoundException {
final int size = unmarshallSize(in);
if (size == NULL_VALUE) {
return null;
}
T collection = Objects.requireNonNull(builder, "CollectionBuilder must be non-null").build(size);
for (int i = 0; i < size; ++i) {
//noinspection unchecked
collection.add(reader.readFrom(in));
}
return collection;
}
/**
* Unmarshal a {@link Collection}.
*
* @param in {@link ObjectInput} to read.
* @param builder {@link CollectionBuilder} builds the concrete {@link Collection} based on size.
* @param <E> Collection's element type.
* @param <T> {@link Collection} implementation.
* @return The concrete {@link Collection} implementation.
* @throws IOException If any of the usual Input/Output related exceptions occur.
* @throws ClassNotFoundException If the class of a serialized object cannot be found.
*/
public static <E, T extends Collection<E>> T unmarshallCollection(ObjectInput in, CollectionBuilder<E, T> builder) throws IOException, ClassNotFoundException {
return unmarshallCollection(in, builder, input -> (E) input.readObject());
}
/**
* Same as {@link #unmarshallCollection(ObjectInput, CollectionBuilder)}.
* <p>
* Used when the size of the {@link Collection} is not needed for it construction.
*
* @see #unmarshallCollection(ObjectInput, CollectionBuilder).
*/
public static <E, T extends Collection<E>> T unmarshallCollectionUnbounded(ObjectInput in, UnboundedCollectionBuilder<E, T> builder) throws IOException, ClassNotFoundException {
final int size = unmarshallSize(in);
if (size == NULL_VALUE) {
return null;
}
T collection = Objects.requireNonNull(builder, "UnboundedCollectionBuilder must be non-null").build();
for (int i = 0; i < size; ++i) {
//noinspection unchecked
collection.add((E) in.readObject());
}
return collection;
}
/**
* Marshall the {@link String}.
* <p>
* Same behavior as {@link ObjectOutput#writeUTF(String)} but it checks for {@code null}. If the {@code string} is
* never {@code null}, it is better to use {@link ObjectOutput#writeUTF(String)}.
*
* @param string {@link String} to marshall.
* @param out {@link ObjectOutput} to write.
* @throws IOException If any of the usual Input/Output related exceptions occur.
*/
public static void marshallString(String string, ObjectOutput out) throws IOException {
if (string == null) {
out.writeBoolean(true);
return;
}
out.writeBoolean(false);
out.writeUTF(string);
}
/**
* Unmarshall a {@link String}.
*
* @param in {@link ObjectInput} to read.
* @return The {@link String} or {@code null}.
* @throws IOException If any of the usual Input/Output related exceptions occur.
* @see #marshallString(String, ObjectOutput).
*/
public static String unmarshallString(ObjectInput in) throws IOException {
if (in.readBoolean()) {
return null;
}
return in.readUTF();
}
/**
* Same as {@link #marshallArray(Object[], ObjectOutput)} but specialized for byte arrays.
*
* @see #marshallArray(Object[], ObjectOutput).
*/
public static void marshallByteArray(byte[] array, ObjectOutput out) throws IOException {
final int size = array == null ? NULL_VALUE : array.length;
marshallSize(out, size);
if (size <= 0) {
return;
}
out.write(array);
}
/**
* Same as {@link #unmarshallArray(ObjectInput, ArrayBuilder)} but specialized for byte array.
* <p>
* No {@link ArrayBuilder} is necessary.
*
* @see #unmarshallArray(ObjectInput, ArrayBuilder).
*/
public static byte[] unmarshallByteArray(ObjectInput in) throws IOException {
final int size = unmarshallSize(in);
if (size == NULL_VALUE) {
return null;
} else if (size == 0) {
return Util.EMPTY_BYTE_ARRAY;
}
byte[] array = new byte[size];
in.readFully(array);
return array;
}
/**
* A special marshall implementation for integer.
* <p>
* This method supports negative values but they are handles as {@link #NULL_VALUE}. It means that the real value is
* lost and {@link #NULL_VALUE} is returned by {@link #unmarshallSize(DataInput)}.
* <p>
* The integer is marshalled in a variable length from 1 to 5 bytes. Negatives values are always marshalled in 1
* byte.
*
* @param out {@link ObjectOutput} to write.
* @param value Integer value to marshall.
* @throws IOException If any of the usual Input/Output related exceptions occur.
*/
public static void marshallSize(DataOutput out, int value) throws IOException {
if (value < 0) {
out.writeByte(0x80); //meaning it is a negative value!
return;
}
if ((value & ~0x3F) == 0) { // fits in 1 byte
out.writeByte(value & 0x3F); //first bit is 0 (== positive) and second bit is zero (== not more bytes)
return;
}
out.writeByte((value & 0x3F) | 0x40); //set second bit to 1 (== more bytes)
value >>>= 6; //6 bits written so far
//normal code for unsigned int. only the first byte is special
while ((value & ~0x7F) != 0) {
out.writeByte((byte) ((value & 0x7f) | 0x80));
value >>>= 7;
}
out.writeByte((byte) value);
}
/**
* Unmarshall an integer.
*
* @param in {@link ObjectInput} to read.
* @return The integer value or {@link #NULL_VALUE} if the original value was negative.
* @throws IOException If any of the usual Input/Output related exceptions occur.
* @see #marshallSize(DataOutput, int).
*/
public static int unmarshallSize(DataInput in) throws IOException {
byte b = in.readByte();
if ((b & 0x80) != 0) {
return NULL_VALUE; //negative value
}
int i = b & 0x3F;
if ((b & 0x40) == 0) {
return i;
}
int shift = 6;
do {
b = in.readByte();
i |= (b & 0x7F) << shift;
shift += 7;
} while ((b & 0x80) != 0);
return i;
}
public static <E extends Enum<E>> void marshallEnum(E e, ObjectOutput output) throws IOException {
if (e == null) {
output.writeByte(NULL_VALUE);
} else {
output.writeByte(e.ordinal());
}
}
public static <E extends Enum<E>> E unmarshallEnum(ObjectInput input, EnumBuilder<E> builder) throws IOException {
final byte ordinal = input.readByte();
if (ordinal == NULL_VALUE) {
return null;
}
try {
return Objects.requireNonNull(builder).build(ordinal);
} catch (ArrayIndexOutOfBoundsException e) {
throw new IOException("Unknown enum.", e);
}
}
/**
* Marshalls a collection of integers.
*
* @param collection the collection to marshall.
* @param out the {@link ObjectOutput} to write to.
* @throws IOException if an error occurs.
*/
public static void marshallIntCollection(Collection<Integer> collection, ObjectOutput out) throws IOException {
final int size = collection == null ? NULL_VALUE : collection.size();
marshallSize(out, size);
if (size <= 0) {
return;
}
for (Integer integer : collection) {
out.writeInt(integer);
}
}
/**
* Unmarshalls a collection of integers.
*
* @param in the {@link ObjectInput} to read from.
* @param builder the {@link CollectionBuilder} to build the collection of integer.
* @param <T> the concrete type of the collection.
* @return the collection.
* @throws IOException if an error occurs.
*/
public static <T extends Collection<Integer>> T unmarshallIntCollection(ObjectInput in, CollectionBuilder<Integer, T> builder) throws IOException {
final int size = unmarshallSize(in);
if (size == NULL_VALUE) {
return null;
}
T collection = Objects.requireNonNull(builder, "CollectionBuilder must be non-null").build(size);
for (int i = 0; i < size; ++i) {
collection.add(in.readInt());
}
return collection;
}
/**
* Checks whether class name is matched by the class name white list regular expressions provided.
*
* @param className class to verify
* @param allowList list of regular expressions to match class name against
* @return true if the class matched at least one of the regular expressions,
* false otherwise
*/
public static boolean isSafeClass(String className, List<String> allowList) {
for (String whiteRegExp : allowList) {
Pattern whitePattern = Pattern.compile(whiteRegExp);
Matcher whiteMatcher = whitePattern.matcher(className);
if (whiteMatcher.find()) {
if (log.isTraceEnabled())
log.tracef("Allowlist match: '%s'", className);
return true;
}
}
return false;
}
@FunctionalInterface
public interface ArrayBuilder<E> {
E[] build(int size);
}
@FunctionalInterface
public interface CollectionBuilder<E, T extends Collection<E>> {
T build(int size);
}
@FunctionalInterface
public interface UnboundedCollectionBuilder<E, T extends Collection<E>> {
T build();
}
@FunctionalInterface
public interface MapBuilder<K, V, T extends Map<K, V>> {
T build(int size);
}
@FunctionalInterface
public interface EnumBuilder<E extends Enum<E>> {
E build(int ordinal);
}
@FunctionalInterface
public interface ElementReader<E> {
E readFrom(ObjectInput input) throws ClassNotFoundException, IOException;
}
@FunctionalInterface
public interface ElementWriter<E> {
void writeTo(ObjectOutput output, E element) throws IOException;
}
}
| 20,431
| 35.420677
| 208
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/Ids.java
|
package org.infinispan.commons.marshall;
/**
* Internal marshalling identifiers.
*
* @author Galder Zamarreño
* @since 6.0
*/
public interface Ids {
// No internal externalizer should use this upper limit Id or anything higher than that.
int MAX_ID = 255;
Integer MAPS = 1;
Integer COLLECTIONS = 2;
// responses
Integer SUCCESSFUL_RESPONSE = 4;
Integer EXCEPTION_RESPONSE = 5;
Integer UNSUCCESSFUL_RESPONSE = 6;
// entries and values
Integer IMMORTAL_ENTRY = 7;
Integer MORTAL_ENTRY = 8;
Integer TRANSIENT_ENTRY = 9;
Integer TRANSIENT_MORTAL_ENTRY = 10;
Integer IMMORTAL_VALUE = 11;
Integer MORTAL_VALUE = 12;
Integer TRANSIENT_VALUE = 13;
Integer TRANSIENT_MORTAL_VALUE = 14;
Integer INT_SUMMARY_STATISTICS = 16;
Integer LONG_SUMMARY_STATISTICS = 17;
Integer DOUBLE_SUMMARY_STATISTICS = 18;
Integer GLOBAL_TRANSACTION = 19;
Integer JGROUPS_ADDRESS = 20;
Integer WRAPPED_BYTE_ARRAY = 21;
Integer DEADLOCK_DETECTING_GLOBAL_TRANSACTION = 22;
Integer DEFAULT_CONSISTENT_HASH = 27;
Integer REPLICATED_CONSISTENT_HASH = 28;
Integer UNSURE_RESPONSE = 29;
Integer JGROUPS_TOPOLOGY_AWARE_ADDRESS = 30;
Integer REPLICABLE_COMMAND = 31;
Integer XID = 32;
Integer XID_DEADLOCK_DETECTING_GLOBAL_TRANSACTION = 33;
Integer XID_GLOBAL_TRANSACTION = 34;
Integer IN_DOUBT_TX_INFO = 35;
Integer CACHE_RPC_COMMAND = 36;
Integer CACHE_TOPOLOGY = 37;
// Metadata entries and values
Integer METADATA_IMMORTAL_ENTRY = 38;
Integer METADATA_MORTAL_ENTRY = 39;
Integer METADATA_TRANSIENT_ENTRY = 40;
Integer METADATA_TRANSIENT_MORTAL_ENTRY = 41;
Integer METADATA_IMMORTAL_VALUE = 42;
Integer METADATA_MORTAL_VALUE = 43;
Integer METADATA_TRANSIENT_VALUE = 44;
Integer METADATA_TRANSIENT_MORTAL_VALUE = 45;
Integer TRANSACTION_INFO = 46;
Integer FLAG = 47;
Integer STATE_CHUNK = 48;
Integer CACHE_JOIN_INFO = 49;
Integer DEFAULT_CONSISTENT_HASH_FACTORY = 50;
Integer REPLICATED_CONSISTENT_HASH_FACTORY = 51;
Integer SYNC_CONSISTENT_HASH_FACTORY = 52;
Integer TOPOLOGY_AWARE_CONSISTENT_HASH_FACTORY = 53;
Integer TOPOLOGY_AWARE_SYNC_CONSISTENT_HASH_FACTORY = 54;
Integer SIMPLE_CLUSTERED_VERSION = 55;
Integer DELTA_COMPOSITE_KEY = 56;
Integer EMBEDDED_METADATA = 57;
Integer NUMERIC_VERSION = 58;
Integer CACHE_NOT_FOUND_RESPONSE = 59;
Integer KEY_VALUE_PAIR_ID = 60;
Integer INTERNAL_METADATA_ID = 61;
Integer MARSHALLED_ENTRY_ID = 62;
Integer ENUM_SET_ID = 63;
Integer SIMPLE_COLLECTION_KEY_FILTER = 64;
Integer KEY_FILTER_AS_KEY_VALUE_FILTER = 65;
Integer CLUSTER_EVENT = 66;
Integer CLUSTER_LISTENER_REMOVE_CALLABLE = 67;
Integer CLUSTER_LISTENER_REPLICATE_CALLABLE = 68;
// 69 unused
Integer X_SITE_STATE = 70;
Integer COMPOSITE_KEY_VALUE_FILTER = 71;
Integer CACHE_STATUS_RESPONSE = 72;
Integer CACHE_EVENT_CONVERTER_AS_CONVERTER = 73;
Integer CACHE_EVENT_FILTER_AS_KEY_VALUE_FILTER = 74;
Integer CACHE_EVENT_FILTER_CONVERTER_AS_KEY_VALUE_FILTER_CONVERTER = 75;
Integer KEY_FILTER_AS_CACHE_EVENT_FILTER = 76;
Integer KEY_VALUE_FILTER_AS_CACHE_EVENT_FILTER = 77;
Integer ACCEPT_ALL_KEY_VALUE_FILTER = 78;
Integer COMPOSITE_KEY_FILTER = 79;
Integer KEY_VALUE_FILTER_AS_KEY_FILTER = 80;
Integer MANAGER_STATUS_RESPONSE = 81;
// 82 unused
Integer EQUIVALENCE = 83;
Integer INTERMEDIATE_OPERATIONS = 84;
Integer TERMINAL_OPERATIONS = 85;
Integer STREAM_MARSHALLING = 86;
Integer CACHE_FILTERS = 87;
Integer OPTIONAL = 88;
Integer META_PARAMS_INTERNAL_METADATA = 89;
// TODO: Add other meta params
Integer META_LIFESPAN = 91;
Integer META_ENTRY_VERSION = 92;
Integer META_MAX_IDLE = 93;
Integer READ_WRITE_SNAPSHOT_VIEW = 94;
Integer AVAILABILITY_MODE = 95;
Integer SYNC_REPLICATED_CONSISTENT_HASH_FACTORY = 96;
Integer PERSISTENT_UUID = 97;
Integer READ_ONLY_SNAPSHOT_VIEW = 98;
Integer NO_VALUE_READ_ONLY_VIEW = 99;
Integer MIME_CACHE_ENTRY = 100;
Integer UUID = 101;
Integer QUEUE = 102;
Integer ARRAYS = 103;
Integer MURMURHASH_3 = 104;
Integer IMMUTABLE_MAP = 105;
Integer BYTE_BUFFER = 106;
// Functional lambdas
Integer LAMBDA_CONSTANT = 107;
Integer LAMBDA_SET_VALUE_IF_EQUALS_RETURN_BOOLEAN = 108;
Integer LAMBDA_WITH_METAS = 109;
Integer IMMUTABLE_SET = 110;
Integer STREAM_ITERATOR_RESPONSE = 111;
Integer END_ITERATOR = 112;
Integer STREAM_MAP_OPS = 113;
Integer TRIANGLE_ACK_EXTERNALIZER = 114;
Integer VERSIONED_RESULT = 115;
Integer VERSIONED_RESULTS = 116;
Integer APPLY_DELTA = 117;
Integer XID_IMPL = 118;
Integer ATOMIC_MAP_FUNCTIONS = 119;
Integer ATOMIC_KEY_SET = 120;
Integer ATOMIC_FINE_GRAINED_MAP_FUNCTIONS = 121;
Integer ENCODER_KEY_MAPPER = 122;
Integer ENCODER_VALUE_MAPPER = 123;
Integer ENCODER_ENTRY_MAPPER = 124;
Integer FUNCTION_MAPPER = 125;
Integer BI_FUNCTION_MAPPER = 126;
Integer SCATTERED_CONSISTENT_HASH_FACTORY = 127;
Integer SCATTERED_CONSISTENT_HASH = 128;
Integer METADATA_REMOTE = 129;
Integer MERGE_FUNCTION_MAPPER = 130;
Integer DATA_CONVERSION = 131;
Integer INT_SET = 132;
Integer SCOPED_STATE = 133;
Integer SCOPED_STATE_FILTER = 134;
Integer ADMIN_FLAG = 135;
Integer CACHE_STATE = 136;
Integer STATS_ENVELOPE = 137;
Integer BIAS_REVOCATION_RESPONSE = 138;
Integer KEY_VALUE_FILTER_CONVERTER_AS_CACHE_EVENT_FILTER_CONVERTER = 139;
Integer SIMPLE_PUBLISHER_RESULT = 140;
Integer PUBLISHER_REDUCERS = 141;
Integer CACHE_STREAM_INTERMEDIATE_PUBLISHER = 142;
Integer CACHE_STREAM_INTERMEDIATE_REDUCER = 143;
Integer CLASS = 144;
Integer DISTRIBUTED_CACHE_STATS_CALLABLE = 145;
Integer EXCEPTIONS = 146;
Integer IMMUTABLE_LIST_COPY = 147;
Integer INTERNAL_ENUMS = 148;
Integer PUBLISHER_RESPONSE = 149;
Integer CACHE_BI_CONSUMERS = 150;
Integer PUBLISHER_TRANSFORMERS = 151;
Integer PREPARE_RESPONSE = 152;
Integer XSITE_AUTO_TRANSFER_RESPONSE = 153;
Integer COMMAND_INVOCATION_ID = 154;
Integer CACHE_ENTRY_GROUP_PREDICATE = 155;
Integer CRC16_HASH = 156;
Integer COUNTER_CONFIGURATION = 2000; //from counter
Integer COUNTER_STATE = 2001; //from counter
}
| 6,320
| 26.012821
| 91
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/package-info.java
|
/**
* Provides Infinispan-specific input and output streams, buffers and related utilities.
*
* @api.public
*/
package org.infinispan.commons.marshall;
| 156
| 21.428571
| 88
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/PersistenceContextInitializer.java
|
package org.infinispan.commons.marshall;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterState;
import org.infinispan.counter.api.CounterType;
import org.infinispan.counter.api.Storage;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
/**
* Interface used to initialise a {@link org.infinispan.protostream.SerializationContext} using the specified Pojos,
* Marshaller implementations and provided .proto schemas.
*
* @author Ryan Emerson
* @since 10.0
*/
@AutoProtoSchemaBuilder(
includeClasses = {
MediaType.class,
WrappedByteArray.class,
CounterState.class,
CounterConfiguration.class,
CounterType.class,
Storage.class,
},
schemaFileName = "persistence.commons.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.persistence.commons",
service = false
)
public interface PersistenceContextInitializer extends SerializationContextInitializer {
}
| 1,183
| 33.823529
| 116
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/StreamAwareMarshaller.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.infinispan.commons.dataconversion.MediaType;
import net.jcip.annotations.ThreadSafe;
/**
* A minimal interface that facilitates the marshalling/unmarshalling of objects from the provided {@link
* java.io.InputStream}/{@link java.io.OutputStream}. Unlike the deprecated {@link StreamingMarshaller} this interface
* does not rely on the use of {@link java.io.ObjectInput} and {@link java.io.ObjectOutput} to read/write objects,
* which provides greater flexibility when marshalling objects to streams using third party libraries.
*
* @author Ryan Emerson
* @since 10.0
*/
@ThreadSafe
public interface StreamAwareMarshaller {
/**
* Marshall an object to the {@link OutputStream}
*
* @param o the object to write to the {@link OutputStream}
* @param out the {@link OutputStream} to write the object to
* @throws IOException if the object cannot be marshalled to the {@link OutputStream} due to some I/O error
*/
void writeObject(Object o, OutputStream out) throws IOException;
/**
* Unmarshall an object from the {@link InputStream}
*
* @param in the {@link InputStream} to unmarshall an object from
* @return the unmarshalled object instance
* @throws IOException if unmarshalling cannot complete due to some I/O error
* @throws ClassNotFoundException if the class of the object trying to unmarshall is not found
*/
Object readObject(InputStream in) throws ClassNotFoundException, IOException;
/**
* A method that checks whether the given object is marshallable as per the rules of this marshaller.
*
* @param o object to verify whether it's marshallable or not
* @return true if the object is marshallable, otherwise false
*/
boolean isMarshallable(Object o);
/**
* An method that provides an estimate of the buffer size that will be required once the object has been marshalled.
*
* @param o instance that will be stored in the buffer.
* @return int representing the next predicted buffer size.
*/
int sizeEstimate(Object o);
/**
* @return the {@link MediaType} associated with the content produced by the marshaller
*/
MediaType mediaType();
}
| 2,341
| 36.174603
| 119
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/InstanceReusingAdvancedExternalizer.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* An advanced externalizer that when implemented will allow for child instances that also extend this class to use object
* instances instead of serializing a brand new object.
* @author wburns
* @since 7.1
*/
public abstract class InstanceReusingAdvancedExternalizer<T> extends AbstractExternalizer<T> {
static class ReusableData {
Map<Object, Integer> map = new HashMap<>();
int offset;
}
private static ThreadLocal<ReusableData> cachedWriteObjects = new ThreadLocal<ReusableData>();
private static ThreadLocal<List<Object>> cachedReadObjects = new ThreadLocal<List<Object>>();
private static final int ID_NO_REPEAT = 0x01;
private static final int ID_REPEAT_OBJECT_NEAR = 0x02;
private static final int ID_REPEAT_OBJECT_NEARISH = 0x03;
private static final int ID_REPEAT_OBJECT_FAR = 0x04;
public InstanceReusingAdvancedExternalizer() {
this(true);
}
public InstanceReusingAdvancedExternalizer(boolean hasChildren) {
this.hasChildren = hasChildren;
}
/**
* This boolean controls whether or not it makes sense to actually create the context or not. In the case of
* classes that don't expect to have children that support this they shouldn't do the creation
*/
private final boolean hasChildren;
@Override
public final void writeObject(ObjectOutput output, T object) throws IOException {
ReusableData data = cachedWriteObjects.get();
boolean shouldRemove;
if (hasChildren && data == null) {
data = new ReusableData();
cachedWriteObjects.set(data);
shouldRemove = true;
} else {
shouldRemove = false;
}
try {
int id;
if (data != null && (id = data.map.getOrDefault(object, -1)) != -1) {
final int diff = id - data.offset;
if (diff >= -256) {
output.write(ID_REPEAT_OBJECT_NEAR);
output.write(diff);
} else if (diff >= -65536) {
output.write(ID_REPEAT_OBJECT_NEARISH);
output.writeShort(diff);
} else {
output.write(ID_REPEAT_OBJECT_FAR);
output.writeInt(id);
}
} else {
output.write(ID_NO_REPEAT);
doWriteObject(output, object);
// Set this before writing object in case of circular dependencies
if (data != null) {
data.map.put(object, data.offset++);
}
}
} finally {
if (shouldRemove) {
cachedWriteObjects.remove();
}
}
}
public abstract void doWriteObject(ObjectOutput output, T object) throws IOException;
@Override
public final T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
List<Object> data = cachedReadObjects.get();
boolean shouldRemove;
if (hasChildren && data == null) {
data = new ArrayList<>();
cachedReadObjects.set(data);
shouldRemove = true;
} else {
shouldRemove = false;
}
try {
int type = input.read();
switch (type) {
case ID_NO_REPEAT:
T object = doReadObject(input);
if (data != null) {
data.add(object);
}
return object;
case ID_REPEAT_OBJECT_NEAR:
int offset = input.read() | 0xffffff00;
return getFromCache(data, offset + data.size());
case ID_REPEAT_OBJECT_NEARISH:
offset = input.readShort() | 0xffff0000;
return getFromCache(data, offset + data.size());
case ID_REPEAT_OBJECT_FAR:
return getFromCache(data, input.readInt());
default:
throw new IllegalStateException("Unexpected byte encountered: " + type);
}
} finally {
if (shouldRemove) {
cachedReadObjects.remove();
}
}
}
private T getFromCache(List<Object> data, int index) throws InvalidObjectException {
try {
Object obj = data.get(index);
if (obj != null) {
return (T) obj;
}
} catch (IndexOutOfBoundsException e) {
}
throw new InvalidObjectException("Attempt to read a backreference for " + getClass() + " with an invalid ID (absolute "
+ index + ")");
}
public abstract T doReadObject(ObjectInput input) throws IOException, ClassNotFoundException;
}
| 4,769
| 33.316547
| 124
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/UserContextInitializer.java
|
package org.infinispan.commons.marshall;
import org.infinispan.commons.util.NullValue;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
/**
* Interface used to initialise a {@link org.infinispan.protostream.SerializationContext} using the specified Pojos,
* Marshaller implementations and provided .proto schemas.
*
* @author Dan Berindei
* @since 13.0
*/
@AutoProtoSchemaBuilder(
includeClasses = {
NullValue.class,
},
schemaFileName = "user.commons.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.commons",
service = false
)
public interface UserContextInitializer extends SerializationContextInitializer {
}
| 787
| 30.52
| 116
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/ProtoStreamMarshaller.java
|
package org.infinispan.commons.marshall;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.SerializationContextInitializer;
/**
* Provides the starting point for implementing a {@link org.infinispan.commons.marshall.Marshaller} that uses Protobuf
* encoding.
*
* @author anistor@redhat.com
* @since 6.0
*/
public class ProtoStreamMarshaller extends ImmutableProtoStreamMarshaller {
public ProtoStreamMarshaller() {
this(ProtobufUtil.newSerializationContext());
}
public ProtoStreamMarshaller(SerializationContext serializationContext) {
super(serializationContext);
}
public void register(SerializationContextInitializer initializer) {
initializer.registerSchema(getSerializationContext());
initializer.registerMarshallers(getSerializationContext());
}
@Override
public SerializationContext getSerializationContext() {
return (SerializationContext) serializationContext;
}
}
| 1,032
| 29.382353
| 119
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/IdentityMarshaller.java
|
package org.infinispan.commons.marshall;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_UNKNOWN;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.io.ByteBufferImpl;
/**
* A marshaller that does not transform the content, only applicable to byte[] payloads.
*
* @since 9.3
*/
public class IdentityMarshaller extends AbstractMarshaller {
public static final IdentityMarshaller INSTANCE = new IdentityMarshaller();
@Override
protected ByteBuffer objectToBuffer(Object o, int estimatedSize) {
return ByteBufferImpl.create((byte[]) o);
}
@Override
public Object objectFromByteBuffer(byte[] buf, int offset, int length) {
return buf;
}
@Override
public boolean isMarshallable(Object o) {
return o instanceof byte[];
}
@Override
public MediaType mediaType() {
return APPLICATION_UNKNOWN;
}
}
| 969
| 24.526316
| 88
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/WrappedByteArray.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.util.Util;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoTypeId;
/**
* Simple wrapper around a byte[] to provide equals and hashCode semantics
* @author wburns
* @since 9.0
*/
@ProtoTypeId(ProtoStreamTypeIds.WRAPPED_BYTE_ARRAY)
public class WrappedByteArray implements WrappedBytes {
public static final WrappedByteArray EMPTY_BYTES = new WrappedByteArray(Util.EMPTY_BYTE_ARRAY);
private final byte[] bytes;
private transient int hashCode;
private transient boolean initializedHashCode;
@ProtoFactory
public WrappedByteArray(byte[] bytes) {
this.bytes = bytes;
}
public WrappedByteArray(byte[] bytes, int hashCode) {
this.bytes = bytes;
assert hashCode == Arrays.hashCode(bytes) : "HashCode " + hashCode + " doesn't match " + Arrays.hashCode(bytes);
this.hashCode = hashCode;
this.initializedHashCode = true;
}
@Override
@ProtoField(1)
public byte[] getBytes() {
return bytes;
}
@Override
public int backArrayOffset() {
return 0;
}
@Override
public int getLength() {
return bytes.length;
}
@Override
public byte getByte(int offset) {
return bytes[offset];
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
Class<?> oClass = o.getClass();
if (getClass() != oClass) {
return WrappedBytes.class.isAssignableFrom(oClass) && equalsWrappedBytes((WrappedBytes) o);
}
WrappedByteArray that = (WrappedByteArray) o;
return Arrays.equals(bytes, that.bytes);
}
public boolean equalsWrappedBytes(WrappedBytes other) {
int length = getLength();
if (other.getLength() != length) return false;
if (other.hashCode() != hashCode()) return false;
for (int i = 0; i < length; ++i) {
if (getByte(i) != other.getByte(i)) return false;
}
return true;
}
@Override
public int hashCode() {
if (!initializedHashCode) {
this.hashCode = Arrays.hashCode(bytes);
initializedHashCode = true;
}
return hashCode;
}
@Override
public String toString() {
return "WrappedByteArray[" + Util.hexDump(bytes) + ']';
}
public static final class Externalizer extends AbstractExternalizer<WrappedByteArray> {
@Override
public Set<Class<? extends WrappedByteArray>> getTypeClasses() {
return Collections.singleton(WrappedByteArray.class);
}
@Override
public Integer getId() {
return Ids.WRAPPED_BYTE_ARRAY;
}
@Override
public void writeObject(ObjectOutput output, WrappedByteArray object) throws IOException {
MarshallUtil.marshallByteArray(object.bytes, output);
if (object.initializedHashCode) {
output.writeBoolean(true);
output.writeInt(object.hashCode);
} else {
output.writeBoolean(false);
}
}
@Override
public WrappedByteArray readObject(ObjectInput input) throws IOException {
byte[] bytes = MarshallUtil.unmarshallByteArray(input);
boolean hasHashCode = input.readBoolean();
if (hasHashCode) {
return new WrappedByteArray(bytes, input.readInt());
} else {
return new WrappedByteArray(bytes);
}
}
}
}
| 3,724
| 27.007519
| 118
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/BufferSizePredictor.java
|
package org.infinispan.commons.marshall;
/**
* Buffer size predictor
*
* @author Galder Zamarreño
* @since 5.0
*/
public interface BufferSizePredictor {
/**
* Provide the next buffer size taking in account
* the object to store in the buffer.
*
* @param obj instance that will be stored in the buffer
* @return int representing the next predicted buffer size
*/
int nextSize(Object obj);
/**
* Record the size of the of data in the last buffer used.
*
* @param previousSize int representing the size of the last
* object buffered.
*/
void recordSize(int previousSize);
}
| 660
| 21.793103
| 63
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/AbstractExternalizer.java
|
package org.infinispan.commons.marshall;
/**
* Base class for {@link AdvancedExternalizer} implementations that offers default
* implementations for some of its methods. In particular, this base class
* offers a default implementation for {@link org.infinispan.commons.marshall.AdvancedExternalizer#getId()}
* that returns null which is particularly useful for advanced externalizers
* whose id will be provided by XML or programmatic configuration rather than
* the externalizer implementation itself.
*
* @author Galder Zamarreño
* @since 5.0
*/
public abstract class AbstractExternalizer<T> implements AdvancedExternalizer<T> {
@Override
public Integer getId() {
return null;
}
}
| 711
| 31.363636
| 107
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/DelegatingObjectInput.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
/**
* Class that extends {@link InputStream} and implements {@link ObjectInput}.
* <p>
* All the methods delegates to a {@link ObjectInput} implementation.
*
* @author Pedro Ruivo
* @since 8.2
*/
public class DelegatingObjectInput extends InputStream implements ObjectInput {
protected final ObjectInput objectInput;
public DelegatingObjectInput(ObjectInput objectInput) {
this.objectInput = objectInput;
}
@Override
public Object readObject() throws ClassNotFoundException, IOException {
return objectInput.readObject();
}
@Override
public int read() throws IOException {
return objectInput.read();
}
@Override
public int read(byte[] b) throws IOException {
return objectInput.read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return objectInput.read(b, off, len);
}
@Override
public long skip(long n) throws IOException {
return objectInput.skip(n);
}
@Override
public int available() throws IOException {
return objectInput.available();
}
@Override
public void close() throws IOException {
objectInput.close();
}
@Override
public void readFully(byte[] b) throws IOException {
objectInput.readFully(b);
}
@Override
public void readFully(byte[] b, int off, int len) throws IOException {
objectInput.readFully(b, off, len);
}
@Override
public int skipBytes(int n) throws IOException {
return objectInput.skipBytes(n);
}
@Override
public boolean readBoolean() throws IOException {
return objectInput.readBoolean();
}
@Override
public byte readByte() throws IOException {
return objectInput.readByte();
}
@Override
public int readUnsignedByte() throws IOException {
return objectInput.readUnsignedByte();
}
@Override
public short readShort() throws IOException {
return objectInput.readShort();
}
@Override
public int readUnsignedShort() throws IOException {
return objectInput.readUnsignedShort();
}
@Override
public char readChar() throws IOException {
return objectInput.readChar();
}
@Override
public int readInt() throws IOException {
return objectInput.readInt();
}
@Override
public long readLong() throws IOException {
return objectInput.readLong();
}
@Override
public float readFloat() throws IOException {
return objectInput.readFloat();
}
@Override
public double readDouble() throws IOException {
return objectInput.readDouble();
}
@Override
public String readLine() throws IOException {
return objectInput.readLine();
}
@Override
public String readUTF() throws IOException {
return objectInput.readUTF();
}
}
| 2,957
| 21.240602
| 79
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/NotSerializableException.java
|
package org.infinispan.commons.marshall;
import org.infinispan.commons.CacheException;
/**
* An exception that hides inner stacktrace lines for non serializable exceptions.
*
* @author Galder Zamarreño
* @since 4.0
*/
public class NotSerializableException extends CacheException {
private static final long serialVersionUID = 8217398736102723887L;
public NotSerializableException(String message, Throwable cause) {
super(message, cause);
}
public NotSerializableException(String message) {
super(message);
}
@Override
public void setStackTrace(StackTraceElement[] stackTrace) {
// nothing
}
@Override
public Throwable fillInStackTrace() {
// no operation
return this;
}
}
| 748
| 20.4
| 82
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/AdvancedExternalizer.java
|
package org.infinispan.commons.marshall;
import java.util.Set;
/**
* {@link AdvancedExternalizer} provides an alternative way to provide
* externalizers for marshalling/unmarshalling user defined classes that
* overcome the deficiencies of the more user-friendly externalizer definition
* model explained in {@link Externalizer}.
*
* The first noticeable difference is that this method does not require user
* classes to be annotated in anyway, so it can be used with classes for which
* source code is not available or that cannot be modified. The bound between
* the externalizer and the classes that are marshalled/unmarshalled is set by
* providing an implementation for {@link #getTypeClasses()} which should
* return the list of classes that this externalizer can marshall.
*
* Secondly, in order to save the maximum amount of space possible in the
* payloads generated, this externalizer method requires externalizer
* implementations to provide a positive identified via {@link #getId()}
* implementations or via XML/programmatic configuration that identifies the
* externalizer when unmarshalling a payload. In order for this to work
* however, this externalizer method requires externalizers to be registered
* on cache manager creation time via XML or programmatic configuration. On
* the contrary, externalizers based on {@link Externalizer} and
* {@link SerializeWith} require no pre-registration whatsoever.
*
* Internally, Infinispan uses this advanced externalizer mechanism in order
* to marshall/unmarshall internal classes.
*
* Finally, {@link AbstractExternalizer} provides default implementations for
* some of the methods defined in this interface and so it's generally
* recommended that implementations extend that abstract class instead of
* implementing {@link AdvancedExternalizer} directly.
*
* Even though {@link AdvancedExternalizer} currently extends
* {@link java.io.Serializable} indirectly, there's no requirement for the
* advanced externalizer to be marshalled, because the pre-registration done
* on startup allows the marshaller to identify the externalizer from the
* given id.
*
* @author Galder Zamarreño
* @since 5.0
* @deprecated since 10.0, will be removed in a future release. Please configure a {@link
* org.infinispan.protostream.SerializationContextInitializer} and utilise ProtoStream annotations on Java objects instead, or
* specify a custom {@link Marshaller} implementation via the SerializationConfiguration.
*/
@Deprecated
public interface AdvancedExternalizer<T> extends Externalizer<T> {
/**
* The minimum ID which will be respected by Infinispan for user specified {@link AdvancedExternalizer} implementations.
*/
int USER_EXT_ID_MIN = 2500;
/**
* Returns a collection of Class instances representing the types that this
* AdvancedExternalizer can marshall. Clearly, empty sets are not allowed.
* The externalizer framework currently requires all individual types to be
* listed since it does not make assumptions based on super classes or
* interfaces.
*
* @return A set containing the Class instances that can be marshalled.
*/
Set<Class<? extends T>> getTypeClasses();
/**
* Returns an integer that identifies the externalizer type. This is used
* at read time to figure out which {@link AdvancedExternalizer} should read
* the contents of the incoming buffer.
*
* Using a positive integer allows for very efficient variable length
* encoding of numbers, and it's much more efficient than shipping
* {@link AdvancedExternalizer} implementation class information around.
* Negative values are not allowed.
*
* Implementers of this interface can use any positive integer as long as
* it does not clash with any other identifier in the system. You can find
* information on the pre-assigned identifier ranges in
* <a href="http://infinispan.org/docs/dev/user_guide/user_guide.html#preassigned_externalizer_id_ranges">here</a>.
*
* It's highly recommended that maintaining of these identifiers is done
* in a centralized way and you can do so by making annotations reference
* a set of statically defined identifiers in a separate class or
* interface. Such class/interface gives a global view of the identifiers
* in use and so can make it easier to assign new ids.
*
* Implementors can optionally avoid giving a meaningful implementation to
* this method (i.e. return null) and instead rely on XML or programmatic
* configuration to provide the AdvancedExternalizer id. If no id can be
* determined via the implementation or XML/programmatic configuration, an
* error will be reported. If an id has been defined both via the
* implementation and XML/programmatic configuration, the value defined via
* XML/programmatic configuration will be used ignoring the other.
*
* @return A positive identifier for the AdvancedExternalizer.
*/
Integer getId();
}
| 5,043
| 48.940594
| 126
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/StreamingMarshaller.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.OutputStream;
import net.jcip.annotations.ThreadSafe;
/**
* A specialization of {@link Marshaller} that supports streams.
* <p/>
* A single instance of any implementation is shared by multiple threads, so implementations <i>need</i> to be threadsafe,
* and preferably immutable.
*
* @author Manik Surtani
* @author Galder Zamarreño
* @since 4.0
* @deprecated for internal use only
* @see Marshaller
*/
@ThreadSafe
@Deprecated
public interface StreamingMarshaller extends Marshaller {
/**
* <p>Create and open an ObjectOutput instance for the given output stream. This method should be used for opening data
* outputs when multiple objectToObjectStream() calls will be made before the stream is closed by calling finishObjectOutput().</p>
*
* <p>This method also takes a boolean that represents whether this particular call to startObjectOutput() is reentrant
* or not. A call to startObjectOutput() should be marked reentrant whenever a 2nd or more calls to this method are made
* without having called finishObjectOutput() first.
*
* <p>To potentially speed up calling startObjectOutput multiple times in a non-reentrant way, i.e.
* startObjectOutput/finishObjectOutput...startObjectOutput/finishObjectOutput...etc, which is is the most common case, the
* StreamingMarshaller implementation could potentially use some mechanisms to speed up this startObjectOutput call.
*
* <p>On the other hand, when a call is reentrant, i.e. startObjectOutput/startObjectOutput(reentrant)...finishObjectOutput/finishObjectOutput,
* the StreamingMarshaller implementation might treat it differently. An example of reentrancy would be marshalling of MarshalledValue.
* When sending or storing a MarshalledValue, a call to startObjectOutput() would occur so that the stream is open and
* following, a 2nd call could occur so that MarshalledValue's raw byte array version is calculated and sent across.
* This enables storing as binary on the receiver side which is performance gain. The StreamingMarshaller implementation could decide
* that it needs a separate ObjectOutput or similar for the 2nd call since it's aim is only to get the raw byte array version
* and the close finish with it.</p>
*
* @param os output stream
* @param isReentrant whether the call is reentrant or not.
* @param estimatedSize estimated size in bytes of the output. Only meant as a possible performance optimization.
* @return ObjectOutput to write to
* @throws IOException
*/
ObjectOutput startObjectOutput(OutputStream os, boolean isReentrant, final int estimatedSize) throws IOException;
/**
* Finish using the given ObjectOutput. After opening a ObjectOutput and calling objectToObjectStream() multiple
* times, use this method to flush the data and close if necessary
*
* @param oo data output that finished using
*/
void finishObjectOutput(ObjectOutput oo);
/**
* Marshalls an object to a given {@link java.io.ObjectOutput}
*
* @param obj object to marshall
* @param out stream to marshall to
*/
void objectToObjectStream(Object obj, ObjectOutput out) throws IOException;
/**
* <p>Create and open a new ObjectInput for the given input stream. This method should be used for opening data inputs
* when multiple objectFromObjectStream() calls will be made before the stream is closed.</p>
*
* <p>This method also takes a boolean that represents whether this particular call to startObjectInput() is reentrant
* or not. A call to startObjectInput() should be marked reentrant whenever a 2nd or more calls to this method are made
* without having called finishObjectInput() first.</p>
*
* <p>To potentially speed up calling startObjectInput multiple times in a non-reentrant way, i.e.
* startObjectInput/finishObjectInput...startObjectInput/finishObjectInput...etc, which is is the most common case, the
* StreamingMarshaller implementation could potentially use some mechanisms to speed up this startObjectInput call.</p>
*
* @param is input stream
* @param isReentrant whether the call is reentrant or not.
* @return ObjectInput to read from
* @throws IOException
*/
ObjectInput startObjectInput(InputStream is, boolean isReentrant) throws IOException;
/**
* Finish using the given ObjectInput. After opening a ObjectInput and calling objectFromObjectStream() multiple
* times, use this method to flush the data and close if necessary
*
* @param oi data input that finished using
*/
void finishObjectInput(ObjectInput oi);
/**
* Unmarshalls an object from an {@link java.io.ObjectInput}
*
* @param in stream to unmarshall from
* @throws IOException if unmarshalling cannot complete due to some I/O error
* @throws ClassNotFoundException if the class of the object trying to unmarshall is unknown
* @throws InterruptedException if the unmarshalling was interrupted. Clients should take this as a sign that
* the marshaller is no longer available, maybe due to shutdown, and so no more unmarshalling should be attempted.
*/
Object objectFromObjectStream(ObjectInput in) throws IOException, ClassNotFoundException, InterruptedException;
/**
* Unmarshall an object from an {@link InputStream}
*
* @param is stream to unmarshall from
* @return the unmarshalled object instance
* @throws IOException if unmarshalling cannot complete due to some I/O error
* @throws ClassNotFoundException if the class of the object trying to unmarshall is unknown
*/
Object objectFromInputStream(InputStream is) throws IOException, ClassNotFoundException;
/**
* Stop the marshaller. Implementations of this method should clear up
* any cached data, or close any resources while marshalling/unmarshalling
* that have not been already closed.
*/
void stop();
void start();
}
| 6,159
| 47.125
| 146
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/DelegatingObjectOutput.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.OutputStream;
/**
* Class that extends {@link OutputStream} and implements {@link ObjectOutput}.
* <p>
* All the methods delegates to a {@link ObjectOutput} implementation.
*
* @author Pedro Ruivo
* @since 8.2
*/
public class DelegatingObjectOutput extends OutputStream implements ObjectOutput {
protected final ObjectOutput objectOutput;
public DelegatingObjectOutput(ObjectOutput objectOutput) {
this.objectOutput = objectOutput;
}
@Override
public void writeObject(Object obj) throws IOException {
objectOutput.writeObject(obj);
}
@Override
public void write(int b) throws IOException {
objectOutput.write(b);
}
@Override
public void write(byte[] b) throws IOException {
objectOutput.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
objectOutput.write(b, off, len);
}
@Override
public void flush() throws IOException {
objectOutput.flush();
}
@Override
public void close() throws IOException {
objectOutput.close();
}
@Override
public void writeBoolean(boolean v) throws IOException {
objectOutput.writeBoolean(v);
}
@Override
public void writeByte(int v) throws IOException {
objectOutput.writeByte(v);
}
@Override
public void writeShort(int v) throws IOException {
objectOutput.writeShort(v);
}
@Override
public void writeChar(int v) throws IOException {
objectOutput.writeChar(v);
}
@Override
public void writeInt(int v) throws IOException {
objectOutput.writeInt(v);
}
@Override
public void writeLong(long v) throws IOException {
objectOutput.writeLong(v);
}
@Override
public void writeFloat(float v) throws IOException {
objectOutput.writeFloat(v);
}
@Override
public void writeDouble(double v) throws IOException {
objectOutput.writeDouble(v);
}
@Override
public void writeBytes(String s) throws IOException {
objectOutput.writeBytes(s);
}
@Override
public void writeChars(String s) throws IOException {
objectOutput.writeChars(s);
}
@Override
public void writeUTF(String s) throws IOException {
objectOutput.writeUTF(s);
}
}
| 2,386
| 21.101852
| 82
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/LambdaExternalizer.java
|
package org.infinispan.commons.marshall;
/**
* A lambda {@link AdvancedExternalizer}.
*
* @param <T>
* @since 8.0
*/
public interface LambdaExternalizer<T> extends AdvancedExternalizer<T> {
ValueMatcherMode valueMatcher(Object o);
}
| 244
| 16.5
| 72
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/SingletonExternalizer.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Set;
import org.infinispan.commons.util.Util;
public class SingletonExternalizer<T> implements AdvancedExternalizer<T> {
private final Integer id;
private final T instance;
public SingletonExternalizer(Integer id, T instance) {
this.id = id;
this.instance = instance;
}
@Override
public Set<Class<? extends T>> getTypeClasses() {
Class<T> clazz = (Class<T>) instance.getClass();
return Util.asSet(clazz);
}
@Override
public Integer getId() {
return id;
}
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return instance;
}
}
| 893
| 21.923077
| 86
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/ValueMatcherMode.java
|
package org.infinispan.commons.marshall;
/**
* Value matcher mode.
*/
public enum ValueMatcherMode {
MATCH_ALWAYS,
MATCH_EXPECTED,
MATCH_EXPECTED_OR_NEW,
MATCH_NON_NULL,
MATCH_NEVER;
private static final ValueMatcherMode[] CACHED_VALUES = values();
public static ValueMatcherMode valueOf(int ordinal) {
return CACHED_VALUES[ordinal];
}
}
| 375
| 16.904762
| 68
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/WrappedBytes.java
|
package org.infinispan.commons.marshall;
/**
* Interface that describes and object holding onto some bytes
* @author wburns
* @since 9.0
*/
public interface WrappedBytes {
/**
* The backing array if there is one otherwise null is returned. Callers should use
* {@link WrappedBytes#backArrayOffset()} to know where to read the bytes from. This byte[] should never be modified
* by the caller
* @return the backing byte[] if there is one.
*/
byte[] getBytes();
/**
* The offset of where data starts in the backed array.
* @return -1 if there is no backed array otherwise ≥ 0 if there is backing array
*/
int backArrayOffset();
/**
* The length of the underlying wrapped bytes. This will always be ≥ 0.
* @return how many bytes are available from the underlying wrapped implementation
*/
int getLength();
/**
* Retrieves the byte given an offset. This offset should always be less than {@link WrappedBytes#getLength()}.
* @param offset the offset of where to find the byte
* @return the byte at this position
*/
byte getByte(int offset);
default boolean equalsWrappedBytes(WrappedBytes other) {
if (other == null) return false;
int length = getLength();
if (other.getLength() != length) return false;
if (other.hashCode() != hashCode()) return false;
for (int i = 0; i < length; ++i) {
if (getByte(i) != other.getByte(i)) return false;
}
return true;
}
}
| 1,512
| 31.191489
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/Marshaller.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.io.ByteBuffer;
import net.jcip.annotations.ThreadSafe;
/**
* A marshaller is a class that is able to marshall and unmarshall objects efficiently.
* <p/>
* This interface is used to marshall {@link org.infinispan.commands.ReplicableCommand}s, their parameters and their
* response values, as well as any other arbitrary Object ↔ byte[] conversions, such as those used in client/server
* communications.
* <p/>
* A single instance of any implementation is shared by multiple threads, so implementations <i>need</i> to be threadsafe,
* and preferably immutable.
*
* @author Manik Surtani
* @version 4.1
*/
@ThreadSafe
public interface Marshaller {
/**
* An optional method which allows an implementation to respect the {@link ClassAllowList} associated with the
* context, for example the EmbeddedCacheManager or RemoteCacheManager.
*/
default void initialize(ClassAllowList classAllowList) {
// no-op
}
/**
* Marshalls an object to a byte array. The estimatedSize parameter is a hint that can be passed in to allow for
* efficient sizing of the byte array before attempting to marshall the object. The more accurate this estimate is,
* the less likely byte[]s will need to be resized to hold the byte stream generated by marshalling the object.
*
* @param obj object to convert to a byte array. Must not be null.
* @param estimatedSize an estimate of how large the resulting byte array may be
* @return a byte array with the marshalled form of the object
* @throws IOException if marshalling cannot complete due to some I/O error
* @throws InterruptedException if the marshalling was interrupted. Clients should take this as a sign that
* the marshaller is no longer available, maybe due to shutdown, and so no more unmarshalling should be attempted.
*/
byte[] objectToByteBuffer(Object obj, int estimatedSize) throws IOException, InterruptedException;
/**
* Marshalls an object to a byte array.
*
* @param obj object to convert to a byte array. Must not be null.
* @return a byte array
* @throws IOException if marshalling cannot complete due to some I/O error
* @throws InterruptedException if the marshalling process was interrupted. Clients should take this as a sign that
* the marshaller is no longer available, maybe due to shutdown, and so no more marshalling should be attempted.
*/
byte[] objectToByteBuffer(Object obj) throws IOException, InterruptedException;
/**
* Unmarshalls an object from a byte array.
*
* @param buf byte array containing the binary representation of an object. Must not be null.
* @return an object
* @throws IOException if unmarshalling cannot complete due to some I/O error
* @throws ClassNotFoundException if the class of the object trying to unmarshall is unknown
*/
Object objectFromByteBuffer(byte[] buf) throws IOException, ClassNotFoundException;
/**
* Unmarshalls an object from a specific portion of a byte array.
*
* @param buf byte array containing the binary representation of an object. Must not be null.
* @param offset point in buffer to start reading
* @param length number of bytes to consider
* @return an object
* @throws IOException if unmarshalling cannot complete due to some I/O error
* @throws ClassNotFoundException if the class of the object trying to unmarshall is unknown
*/
Object objectFromByteBuffer(byte[] buf, int offset, int length) throws IOException, ClassNotFoundException;
/**
* A method that returns an instance of {@link org.infinispan.commons.io.ByteBuffer}, which allows direct access to the byte
* array with minimal array copying
*
* @param o object to marshall
* @throws IOException if marshalling cannot complete due to some I/O error
* @throws InterruptedException if the marshalling process was interrupted. Clients should take this as a sign that
* the marshaller is no longer available, maybe due to shutdown, and so no more marshalling should be attempted.
*/
ByteBuffer objectToBuffer(Object o) throws IOException, InterruptedException;
/**
* A method that checks whether the given object is marshallable as per the rules of this marshaller.
*
* @param o object to verify whether it's marshallable or not
* @return true if the object is marshallable, otherwise false
* @throws Exception if while checking whether the object was serializable or not, an exception arose
*/
boolean isMarshallable(Object o) throws Exception;
/**
* Returns a marshalled payload size predictor for a particular type.
* Accurate prediction of a type's serialized payload size helps avoid
* unnecessary copying and speeds up application performance.
*
* @param o Object for which serialized predictor will be returned
* @return an instance of {@link BufferSizePredictor}
* @throws NullPointerException if o is null
*/
BufferSizePredictor getBufferSizePredictor(Object o);
/**
* @return the {@link MediaType} associated with the content produced by the marshaller
*/
MediaType mediaType();
/**
* Perform any initialization required before the marshaller is used.
*/
default void start() {
// no-op
}
/**
* Stop the marshaller. Implementations of this method should clear up
* any cached data, or close any resources while marshalling/unmarshalling
* that have not been already closed.
*/
default void stop() {
// no-op
}
}
| 5,815
| 42.402985
| 127
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/AdminFlagExternalizer.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.api.CacheContainerAdmin;
public class AdminFlagExternalizer extends AbstractExternalizer<CacheContainerAdmin.AdminFlag> {
@Override
public void writeObject(ObjectOutput output, CacheContainerAdmin.AdminFlag flag) throws IOException {
MarshallUtil.marshallEnum(flag, output);
}
@Override
public CacheContainerAdmin.AdminFlag readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return MarshallUtil.unmarshallEnum(input, CacheContainerAdmin.AdminFlag::valueOf);
}
@Override
public Integer getId() {
return Ids.ADMIN_FLAG;
}
@Override
public Set<Class<? extends CacheContainerAdmin.AdminFlag>> getTypeClasses() {
return Collections.singleton(CacheContainerAdmin.AdminFlag.class);
}
}
| 977
| 29.5625
| 114
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/AbstractMarshaller.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.io.InputStream;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.io.ByteBufferImpl;
import org.infinispan.commons.io.LazyByteArrayOutputStream;
/**
* Abstract Marshaller implementation containing shared implementations.
*
* @author Galder Zamarreño
* @since 4.1
*/
public abstract class AbstractMarshaller implements Marshaller {
protected final MarshallableTypeHints marshallableTypeHints = new MarshallableTypeHints();
@Override
public BufferSizePredictor getBufferSizePredictor(Object o) {
return marshallableTypeHints.getBufferSizePredictor(o.getClass());
}
/**
* This is a convenience method for converting an object into a {@link org.infinispan.commons.io.ByteBuffer} which takes
* an estimated size as parameter. A {@link org.infinispan.commons.io.ByteBuffer} allows direct access to the byte
* array with minimal array copying
*
* @param o object to marshall
* @param estimatedSize an estimate of how large the resulting byte array may be
*/
protected abstract ByteBuffer objectToBuffer(Object o, int estimatedSize) throws IOException, InterruptedException;
@Override
public ByteBuffer objectToBuffer(Object obj) throws IOException, InterruptedException {
if (obj != null) {
BufferSizePredictor sizePredictor = marshallableTypeHints
.getBufferSizePredictor(obj.getClass());
int estimatedSize = sizePredictor.nextSize(obj);
ByteBuffer byteBuffer = objectToBuffer(obj, estimatedSize);
int length = byteBuffer.getLength();
// If the prediction is way off, then trim it
if (estimatedSize > (length * 4)) {
byte[] buffer = trimBuffer(byteBuffer);
byteBuffer = ByteBufferImpl.create(buffer);
}
sizePredictor.recordSize(length);
return byteBuffer;
} else {
return objectToBuffer(null, 1);
}
}
@Override
public byte[] objectToByteBuffer(Object o) throws IOException, InterruptedException {
if (o != null) {
BufferSizePredictor sizePredictor = marshallableTypeHints
.getBufferSizePredictor(o.getClass());
byte[] bytes = objectToByteBuffer(o, sizePredictor.nextSize(o));
sizePredictor.recordSize(bytes.length);
return bytes;
} else {
return objectToByteBuffer(null, 1);
}
}
@Override
public byte[] objectToByteBuffer(Object obj, int estimatedSize) throws IOException, InterruptedException {
ByteBuffer b = objectToBuffer(obj, estimatedSize);
return trimBuffer(b);
}
private byte[] trimBuffer(ByteBuffer b) {
byte[] bytes = new byte[b.getLength()];
System.arraycopy(b.getBuf(), b.getOffset(), bytes, 0, b.getLength());
return bytes;
}
@Override
public Object objectFromByteBuffer(byte[] buf) throws IOException, ClassNotFoundException {
return objectFromByteBuffer(buf, 0, buf.length);
}
/**
* This method implements {@link StreamingMarshaller#objectFromInputStream(java.io.InputStream)}, but its
* implementation has been moved here rather that keeping under a class that implements StreamingMarshaller
* in order to avoid code duplication.
*/
public Object objectFromInputStream(InputStream inputStream) throws IOException, ClassNotFoundException {
int len = inputStream.available();
LazyByteArrayOutputStream bytes;
byte[] buf;
if(len > 0) {
bytes = new LazyByteArrayOutputStream(len);
buf = new byte[Math.min(len, 1024)];
} else {
// Some input stream providers do not implement available()
bytes = new LazyByteArrayOutputStream();
buf = new byte[1024];
}
int bytesRead;
while ((bytesRead = inputStream.read(buf, 0, buf.length)) != -1) bytes.write(buf, 0, bytesRead);
return objectFromByteBuffer(bytes.getRawBuffer(), 0, bytes.size());
}
}
| 4,045
| 36.462963
| 123
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/ProtoStreamTypeIds.java
|
package org.infinispan.commons.marshall;
import org.infinispan.protostream.WrappedMessage;
/**
* TypeIds used by protostream in place of FQN message/enum names to reduce payload size.
* <p>
* ONCE SET VALUES IN THIS CLASS MUST NOT BE CHANGED AS IT WILL BREAK BACKWARDS COMPATIBILITY.
* <p>
* Values must in the range 0..65535, as this is marked for internal infinispan use by the protostream project.
* <p>
* TypeIds are written as a variable length uint32, so Ids in the range 0..127 should be prioritised for frequently
* marshalled classes.
* <p>
* Message names should not end in _LOWER_BOUND as this is used by ProtoStreamTypeIdsUniquenessTest.
* <p>
* If message/enum types are no longer required, the variable should be commented instead of deleted.
*
* @author Ryan Emerson
* @since 10.0
*/
public interface ProtoStreamTypeIds {
// 1 byte Ids 0..127 -> Reserved for critical messages used a lot
int WRAPPED_MESSAGE = WrappedMessage.PROTOBUF_TYPE_ID; // Id 0 is reserved for ProtoStream WrappedMessage class
int WRAPPED_BYTE_ARRAY = 1;
int MARSHALLABLE_USER_OBJECT = 2;
int BYTE_STRING = 3;
int EMBEDDED_METADATA = 4;
int EMBEDDED_EXPIRABLE_METADATA = 5;
int EMBEDDED_LIFESPAN_METADATA = 6;
int EMBEDDED_MAX_IDLE_METADATA = 7;
int NUMERIC_VERSION = 8;
int SIMPLE_CLUSTERED_VERSION = 9;
int JGROUPS_ADDRESS = 10;
int PROTOBUF_VALUE_WRAPPER = 11;
int MEDIA_TYPE = 12;
int PRIVATE_METADATA = 13;
int SUBJECT = 14;
// Priority counter values
int COUNTER_VALUE = 125;
int STRONG_COUNTER_KEY = 126;
int WEAK_COUNTER_KEY = 127;
// 2 byte Ids 128..16383
// Commons range 128 -> 999
int COMMONS_LOWER_BOUND = 128;
int NULL_VALUE = COMMONS_LOWER_BOUND;
// Core range 1000 -> 3999
int CORE_LOWER_BOUND = 1000;
int EVENT_LOG_CATEGORY = CORE_LOWER_BOUND;
int EVENT_LOG_LEVEL = CORE_LOWER_BOUND + 1;
int MARSHALLED_VALUE_IMPL = CORE_LOWER_BOUND + 2;
int META_PARAMS_INTERNAL_METADATA = CORE_LOWER_BOUND + 3;
int REMOTE_METADATA = CORE_LOWER_BOUND + 4;
int UUID = CORE_LOWER_BOUND + 5;
int IRAC_VERSION = CORE_LOWER_BOUND + 6;
int IRAC_SITE_VERSION = CORE_LOWER_BOUND + 7;
int IRAC_VERSION_ENTRY = CORE_LOWER_BOUND + 8;
int IRAC_METADATA = CORE_LOWER_BOUND + 9;
int ROLE_SET = CORE_LOWER_BOUND + 10;
int ROLE = CORE_LOWER_BOUND + 11;
int AUTHORIZATION_PERMISSION = CORE_LOWER_BOUND + 12;
// Counter range 4000 -> 4199
int COUNTERS_LOWER_BOUND = 4000;
int COUNTER_STATE = COUNTERS_LOWER_BOUND;
int COUNTER_CONFIGURATION = COUNTERS_LOWER_BOUND + 1;
int COUNTER_TYPE = COUNTERS_LOWER_BOUND + 2;
int COUNTER_STORAGE = COUNTERS_LOWER_BOUND + 3;
// Query range 4200 -> 4399
int QUERY_LOWER_BOUND = 4200;
int QUERY_METRICS = QUERY_LOWER_BOUND + 1;
int LOCAL_QUERY_STATS = QUERY_LOWER_BOUND + 2;
int LOCAL_INDEX_STATS = QUERY_LOWER_BOUND + 3;
int INDEX_INFO = QUERY_LOWER_BOUND + 4;
int INDEX_INFO_ENTRY = QUERY_LOWER_BOUND + 5;
int SEARCH_STATISTICS = QUERY_LOWER_BOUND + 6;
int STATS_TASK = QUERY_LOWER_BOUND + 7;
//int KNOWN_CLASS_KEY = QUERY_LOWER_BOUND;
// Remote Query range 4400 -> 4599
int REMOTE_QUERY_LOWER_BOUND = 4400;
int REMOTE_QUERY_REQUEST = REMOTE_QUERY_LOWER_BOUND;
int REMOTE_QUERY_RESPONSE = REMOTE_QUERY_LOWER_BOUND + 1;
int ICKLE_FILTER_RESULT = REMOTE_QUERY_LOWER_BOUND + 2;
int ICKLE_CONTINUOUS_QUERY_RESULT = REMOTE_QUERY_LOWER_BOUND + 3;
// Lucene Directory 4600 -> 4799
int LUCENE_LOWER_BOUND = 4600;
int CHUNK_CACHE_KEY = LUCENE_LOWER_BOUND;
int FILE_CACHE_KEY = LUCENE_LOWER_BOUND + 1;
int FILE_LIST_CACHE_KEY = LUCENE_LOWER_BOUND + 2;
int FILE_METADATA = LUCENE_LOWER_BOUND + 3;
int FILE_READ_LOCK_KEY = LUCENE_LOWER_BOUND + 4;
int FILE_LIST_CACHE_VALUE = LUCENE_LOWER_BOUND + 5;
// Tasks + Scripting 4800 -> 4999
int SCRIPTING_LOWER_BOUND = 4800;
int EXECUTION_MODE = SCRIPTING_LOWER_BOUND;
int SCRIPT_METADATA = SCRIPTING_LOWER_BOUND + 1;
int DISTRIBUTED_SERVER_TASK = SCRIPTING_LOWER_BOUND + 2;
int DISTRIBUTED_SERVER_TASK_PARAMETER = SCRIPTING_LOWER_BOUND + 3;
int DISTRIBUTED_SERVER_TASK_CONTEXT = SCRIPTING_LOWER_BOUND + 4;
// Memcached 5000 -> 5099
int MEMCACHED_LOWER_BOUND = 5000;
int MEMCACHED_METADATA = MEMCACHED_LOWER_BOUND;
// RocksDB 5100 -> 5199
int ROCKSDB_LOWER_BOUND = 5100;
int ROCKSDB_EXPIRY_BUCKET = ROCKSDB_LOWER_BOUND;
int ROCKSDB_PERSISTED_METADATA = ROCKSDB_LOWER_BOUND + 1;
// Event-logger 5200 -> 5299
int EVENT_LOGGER_LOWER_BOUND = 5200;
int SERVER_EVENT_IMPL = EVENT_LOGGER_LOWER_BOUND;
// MultiMap 5300 -> 5399
int MULTIMAP_LOWER_BOUND = 5300;
int MULTIMAP_BUCKET = MULTIMAP_LOWER_BOUND;
int MULTIMAP_LIST_BUCKET = MULTIMAP_LOWER_BOUND + 2;
int MULTIMAP_HASH_MAP_BUCKET = MULTIMAP_LOWER_BOUND + 3;
int MULTIMAP_HASH_MAP_BUCKET_ENTRY = MULTIMAP_LOWER_BOUND + 4;
int MULTIMAP_SET_BUCKET = MULTIMAP_LOWER_BOUND + 5;
int MULTIMAP_OBJECT_WRAPPER = MULTIMAP_LOWER_BOUND + 6;
int MULTIMAP_SORTED_SET_BUCKET = MULTIMAP_LOWER_BOUND + 7;
int MULTIMAP_SORTED_SET_SCORED_ENTRY = MULTIMAP_LOWER_BOUND + 8;
// Server Core 5400 -> 5799
int SERVER_CORE_LOWER_BOUND = 5400;
int IGNORED_CACHES = SERVER_CORE_LOWER_BOUND;
int CACHE_BACKUP_ENTRY = SERVER_CORE_LOWER_BOUND + 1;
int COUNTER_BACKUP_ENTRY = SERVER_CORE_LOWER_BOUND + 2;
int IP_FILTER_RULES = SERVER_CORE_LOWER_BOUND + 3;
int IP_FILTER_RULE = SERVER_CORE_LOWER_BOUND + 4;
// JDBC Store 5800 -> 5899
int JDBC_LOWER_BOUND = 5800;
int JDBC_PERSISTED_METADATA = JDBC_LOWER_BOUND;
// Spring integration 5900 -> 5999
int SPRING_LOWER_BOUND = 5900;
@Deprecated
int SPRING_NULL_VALUE = SPRING_LOWER_BOUND;
int SPRING_SESSION = SPRING_LOWER_BOUND + 1;
int SPRING_SESSION_ATTRIBUTE = SPRING_LOWER_BOUND + 2;
int SPRING_SESSION_REMAP = SPRING_LOWER_BOUND + 3;
// Data distribution metrics 6000 -> 6099
int DATA_DISTRIBUTION_LOWER_BOUND = 6000;
int CACHE_DISTRIBUTION_INFO = DATA_DISTRIBUTION_LOWER_BOUND;
int CLUSTER_DISTRIBUTION_INFO = DATA_DISTRIBUTION_LOWER_BOUND + 1;
int KEY_DISTRIBUTION_INFO = DATA_DISTRIBUTION_LOWER_BOUND + 2;
}
| 6,202
| 38.012579
| 115
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/MarshallableTypeHints.java
|
package org.infinispan.commons.marshall;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* Class providing hints about marshallable types, such as whether a particular
* type is marshallable or not, or an accurate approach to the serialized
* size of a particular type.
*
* @author Galder Zamarreño
* @since 5.1
*/
public final class MarshallableTypeHints {
private static final Log log = LogFactory.getLog(MarshallableTypeHints.class);
/**
* Cache of classes that are considered to be marshallable alongside their
* buffer size predictor. Since checking whether a type is marshallable
* requires attempting to marshalling them, a cache for the types that are
* known to be marshallable or not is advantageous.
*/
private final ConcurrentMap<Class<?>, MarshallingType> typeHints = new ConcurrentHashMap<>();
/**
* Get the serialized form size predictor for a particular type.
*
* @param type Marshallable type for which serialized form size will be predicted
* @return an instance of {@link BufferSizePredictor}
*/
public BufferSizePredictor getBufferSizePredictor(Class<?> type) {
MarshallingType marshallingType = typeHints.get(type);
if (marshallingType == null) {
// Initialise with isMarshallable to null, meaning it's unknown
marshallingType = new MarshallingType(null, new AdaptiveBufferSizePredictor());
MarshallingType prev = typeHints.putIfAbsent(type, marshallingType);
if (prev != null) {
marshallingType = prev;
} else {
if (log.isTraceEnabled()) {
log.tracef("Cache a buffer size predictor for '%s' assuming " +
"its serializability is unknown", type.getName());
}
}
}
return marshallingType.sizePredictor;
}
public BufferSizePredictor getBufferSizePredictor(Object obj) {
return obj == null
? NullBufferSizePredictor.INSTANCE
: getBufferSizePredictor(obj.getClass());
}
/**
* Returns whether the hint on whether a particular type is marshallable or
* not is available. This method can be used to avoid attempting to marshall
* a type, if the hints for the type have already been calculated.
*
* @param type Marshallable type to check whether an attempt to mark it as
* marshallable has been made.
* @return true if the type has been marked as marshallable at all, false
* if no attempt has been made to mark the type as marshallable.
*/
public boolean isKnownMarshallable(Class<?> type) {
MarshallingType marshallingType = typeHints.get(type);
return marshallingType != null && marshallingType.isMarshallable != null;
}
/**
* Returns whether a type can be serialized. In order for a type to be
* considered marshallable, the type must have been marked as marshallable
* using the {@link #markMarshallable(Class, boolean)} method earlier,
* passing true as parameter. If a type has not yet been marked as
* marshallable, this method will return false.
*/
public boolean isMarshallable(Class<?> type) {
MarshallingType marshallingType = typeHints.get(type);
if (marshallingType != null) {
Boolean marshallable = marshallingType.isMarshallable;
return marshallable != null ? marshallable.booleanValue() : false;
}
return false;
}
/**
* Marks a particular type as being marshallable or not being not marshallable.
*
* @param type Class to mark as serializable or non-serializable
* @param isMarshallable Whether the type can be marshalled or not.
*/
public void markMarshallable(Class<?> type, boolean isMarshallable) {
MarshallingType marshallType = typeHints.get(type);
if (marshallableUpdateRequired(isMarshallable, marshallType)) {
boolean replaced = typeHints.replace(type, marshallType, new MarshallingType(
Boolean.valueOf(isMarshallable), marshallType.sizePredictor));
if (replaced && log.isTraceEnabled()) {
log.tracef("Replacing '%s' type to be marshallable=%b",
type.getName(), isMarshallable);
}
} else if (marshallType == null) {
if (log.isTraceEnabled()) {
log.tracef("Cache '%s' type to be marshallable=%b",
type.getName(), isMarshallable);
}
typeHints.put(type, new MarshallingType(
Boolean.valueOf(isMarshallable), new AdaptiveBufferSizePredictor()));
}
}
/**
* Clear the cached marshallable type hints.
*/
public void clear() {
typeHints.clear();
}
private boolean marshallableUpdateRequired(boolean isMarshallable,
MarshallingType marshallType) {
return marshallType != null &&
(marshallType.isMarshallable == null ||
marshallType.isMarshallable.booleanValue() != isMarshallable);
}
private static class MarshallingType {
final Boolean isMarshallable;
final BufferSizePredictor sizePredictor;
private MarshallingType(Boolean marshallable, BufferSizePredictor sizePredictor) {
isMarshallable = marshallable;
this.sizePredictor = sizePredictor;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MarshallingType that = (MarshallingType) o;
if (isMarshallable != null ? !isMarshallable.equals(that.isMarshallable) : that.isMarshallable != null)
return false;
if (sizePredictor != null ? !sizePredictor.equals(that.sizePredictor) : that.sizePredictor != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = isMarshallable != null ? isMarshallable.hashCode() : 0;
result = 31 * result + (sizePredictor != null ? sizePredictor.hashCode() : 0);
return result;
}
}
final static class NullBufferSizePredictor implements BufferSizePredictor {
static final BufferSizePredictor INSTANCE = new NullBufferSizePredictor();
@Override
public int nextSize(Object obj) {
return 1;
}
@Override
public void recordSize(int previousSize) {
// No-op
}
}
}
| 6,561
| 35.455556
| 112
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/CheckedInputStream.java
|
package org.infinispan.commons.marshall;
import static org.infinispan.commons.logging.Log.CONTAINER;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.util.Util;
public class CheckedInputStream extends ObjectInputStream {
private final ClassAllowList allowList;
public CheckedInputStream(InputStream in, ClassAllowList allowList) throws IOException {
super(in);
this.allowList = allowList;
}
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
boolean safeClass = allowList.isSafeClass(desc.getName());
if (!safeClass)
throw CONTAINER.classNotInAllowList(desc.getName());
try {
return Util.loadClass(desc.getName(), allowList.getClassLoader());
} catch (Exception e) {
return super.resolveClass(desc);
}
}
}
| 1,025
| 29.176471
| 103
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/SerializeFunctionWith.java
|
package org.infinispan.commons.marshall;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicate that this function should be serialized with an instance of
* the given {@link Externalizer} class.
*
* Any externalizer type referred by this annotation must be either
* {@link java.io.Serializable} or {@link java.io.Externalizable} because the
* marshalling infrastructure will ship an instance of the externalizer to any
* node that's no aware of this externalizer, hence allowing for dynamic
* externalizer discovery.
*
* @since 8.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@Documented
public @interface SerializeFunctionWith {
/**
* Specify the externalizer class to be used by the annotated class.
*
* @return the externalizer type
*/
Class<? extends Externalizer<?>> value();
/**
* Specify the value matching capabilities of this function.
*
* @return a value matcher mode
*/
ValueMatcherMode valueMatcher() default ValueMatcherMode.MATCH_ALWAYS;
}
| 1,247
| 28.023256
| 78
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/SerializeWith.java
|
package org.infinispan.commons.marshall;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicate that this class should be serialized with an instance of the given {@link Externalizer} class.
* <p>
* Any externalizer type referred by this annotation must be either {@link java.io.Serializable} or {@link
* java.io.Externalizable} because the marshalling infrastructure will ship an instance of the externalizer to any node
* that's no aware of this externalizer, hence allowing for dynamic externalizer discovery.
*
* @author Galder Zamarreño
* @since 5.0
* @deprecated since 10.0, will be removed in a future release. Please configure a {@link
* org.infinispan.protostream.SerializationContextInitializer} and utilise ProtoStream annotations on Java objects instead, or
* specify a custom {@link Marshaller} implementation via the SerializationConfiguration.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@Documented
@Deprecated
public @interface SerializeWith {
/**
* Specify the externalizer class to be used by the annotated class.
*
* @return the externalizer type
*/
Class<? extends Externalizer<?>> value();
}
| 1,384
| 35.447368
| 126
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/UTF8StringMarshaller.java
|
package org.infinispan.commons.marshall;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.infinispan.commons.dataconversion.MediaType;
public final class UTF8StringMarshaller extends StringMarshaller {
private static final MediaType UTF8_MEDIA_TYPE = MediaType.fromString("text/plain; charset=UTF-8");
public UTF8StringMarshaller() {
super(UTF_8);
}
@Override
public MediaType mediaType() {
return UTF8_MEDIA_TYPE;
}
}
| 472
| 22.65
| 102
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/AdaptiveBufferSizePredictor.java
|
package org.infinispan.commons.marshall;
import java.util.ArrayList;
import java.util.List;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* The {@link BufferSizePredictor} that automatically increases and
* decreases the predicted buffer size on feed back.
* <p>
* It gradually increases the expected number of bytes if the previous buffer
* fully filled the allocated buffer. It gradually decreases the expected
* number of bytes if the read operation was not able to fill a certain amount
* of the allocated buffer two times consecutively. Otherwise, it keeps
* returning the same prediction.
*
* TODO: Object type hints could be useful at giving more type-specific predictions
*
* @author <a href="http://gleamynode.net/">Trustin Lee</a>
* @author Galder Zamarreño
* @since 5.0
*/
public class AdaptiveBufferSizePredictor implements BufferSizePredictor {
private static final Log log = LogFactory.getLog(AdaptiveBufferSizePredictor.class);
static final int DEFAULT_MINIMUM = 16;
static final int DEFAULT_INITIAL = 512;
static final int DEFAULT_MAXIMUM = 65536;
private static final int INDEX_INCREMENT = 4;
private static final int INDEX_DECREMENT = 1;
private static final int[] SIZE_TABLE;
private final int minIndex;
private final int maxIndex;
private int index;
private int nextBufferSize;
private boolean decreaseNow;
static {
List<Integer> sizeTable = new ArrayList<Integer>();
// First, add the base 1 to 8 bytes sizes
for (int i = 1; i <= 8; i++)
sizeTable.add(i);
for (int i = 4; i < 32; i++) {
long v = 1L << i;
long inc = v >>> 4;
v -= inc << 3;
// From 8 onwards, follow a 2^i progression of increments,
// applying each increment 8 times. For example:
// for incr=2^1 -> 9, 10, 11, 12, 13, 14, 15, 16
// for incr=2^2 -> 18, 20, 22, 24, 26, 28, 30, 32
// for incr=2^3 -> 36, 40, 44, 48 ...
// ...
// for incr=2^31 -> 1073741824, 1207959552...etc
for (int j = 0; j < 8; j++) {
v += inc;
if (v > Integer.MAX_VALUE)
sizeTable.add(Integer.MAX_VALUE);
else
sizeTable.add((int) v);
}
}
SIZE_TABLE = new int[sizeTable.size()];
for (int i = 0; i < SIZE_TABLE.length; i++)
SIZE_TABLE[i] = sizeTable.get(i);
}
private static int getSizeTableIndex(final int size) {
if (size <= 16)
return size - 1;
int bits = 0;
int v = size;
do {
v >>>= 1;
bits ++;
} while (v != 0);
final int baseIdx = bits << 3;
final int startIdx = baseIdx - 18;
final int endIdx = baseIdx - 25;
for (int i = startIdx; i >= endIdx; i --)
if (size >= SIZE_TABLE[i])
return i;
throw new RuntimeException("Shouldn't reach here; please file a bug report.");
}
/**
* Creates a new predictor with the default parameters. With the default
* parameters, the expected buffer size starts from {@code 512}, does not
* go down below {@code 16}, and does not go up above {@code 65536}.
*/
public AdaptiveBufferSizePredictor() {
this(DEFAULT_MINIMUM, DEFAULT_INITIAL, DEFAULT_MAXIMUM);
}
/**
* Creates a new predictor with the specified parameters.
*
* @param minimum the inclusive lower bound of the expected buffer size
* @param initial the initial buffer size when no feed back was received
* @param maximum the inclusive upper bound of the expected buffer size
*/
public AdaptiveBufferSizePredictor(int minimum, int initial, int maximum) {
if (minimum <= 0)
throw new IllegalArgumentException("minimum: " + minimum);
if (initial < minimum)
throw new IllegalArgumentException("initial: " + initial);
if (maximum < initial)
throw new IllegalArgumentException("maximum: " + maximum);
int minIndex = getSizeTableIndex(minimum);
if (SIZE_TABLE[minIndex] < minimum)
this.minIndex = minIndex + 1;
else
this.minIndex = minIndex;
int maxIndex = getSizeTableIndex(maximum);
if (SIZE_TABLE[maxIndex] > maximum)
this.maxIndex = maxIndex - 1;
else
this.maxIndex = maxIndex;
index = getSizeTableIndex(initial);
nextBufferSize = SIZE_TABLE[index];
}
@Override
public int nextSize(Object obj) {
if (log.isTraceEnabled())
log.tracef("Next predicted buffer size for object type '%s' will be %d",
obj == null ? "Null" : obj.getClass().getName(), nextBufferSize);
return nextBufferSize;
}
@Override
public void recordSize(int previousSize) {
if (previousSize <= SIZE_TABLE[Math.max(0, index - INDEX_DECREMENT - 1)]) {
if (decreaseNow) {
index = Math.max(index - INDEX_DECREMENT, minIndex);
nextBufferSize = SIZE_TABLE[index];
decreaseNow = false;
} else {
decreaseNow = true;
}
} else if (previousSize >= nextBufferSize) {
index = Math.min(index + INDEX_INCREMENT, maxIndex);
nextBufferSize = SIZE_TABLE[index];
decreaseNow = false;
}
}
}
| 5,407
| 31
| 87
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/Externalizer.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
/**
* One of the key aspects of Infinispan is that it often needs to marshall or
* unmarshall objects in order to provide some of its functionality. For
* example, if it needs to store objects in a write-through or write-behind
* cache store, the objects stored need marshalling. If a cluster of
* Infinispan nodes is formed, objects shipped around need marshalling. Even
* if you enable storing as binary, objects need to marshalled so that they
* can be lazily unmarshalled with the correct classloader.
*
* Using standard JDK serialization is slow and produces payloads that are too
* big and can affect bandwidth usage. On top of that, JDK serialization does
* not work well with objects that are supposed to be immutable. In order to
* avoid these issues, Infinispan uses JBoss Marshalling for
* marshalling/unmarshalling objects. JBoss Marshalling is fast, provides
* very space efficient payloads, and on top of that, allows users to
* construct objects themselves during unmarshalling, hence allowing objects
* to carry on being immutable.
*
* Starting with 5.0, users of Infinispan can now benefit from this marshalling
* framework as well. In the simplest possible form, users just need to
* provide an {@link Externalizer} implementation for the type that they want
* to marshall/unmarshall, and then annotate the marshalled type class with
* {@link SerializeWith} indicating the externalizer class to use and that's
* all about it. At runtime JBoss Marshaller will inspect the object and
* discover that's marshallable thanks to the annotation and so marshall it
* using the externalizer class passed.
*
* It's common practice to include externalizer implementations within the
* classes that they marshall/unmarshall as <code>public static classes</code>.
* To make externalizer implementations easier to code and more typesafe, make
* sure you define type <T> as the type of object that's being
* marshalled/unmarshalled.
*
* Even though this way of defining externalizers is very user friendly, it has
* some disadvantages:
*
* <ul>
* <li>Due to several constraints of the model, such as support different
* versions of the same class or the need to marshall the Externalizer
* class, the payload sizes generated via this method are not the most
* efficient.</li>
* <li>This model requires for the marshalled class to be annoated with
* {@link SerializeWith} but a user might need to provide an Externalizer
* for a class for which source code is not available, or for any other
* constraints, it cannot be modified.</li>
* <li>The use of annotations by this model might be limiting for framework
* developers or service providers that try to abstract lower level
* details, such as the marshalling layer, away from the user.</li>
* </ul>
*
* If you're affected by any of these disadvantages, an alternative mechanism
* to provide externalizers is available via {@link AdvancedExternalizer}.
* More details can be found in this interface's javadoc.
*
* Please note that even though Externalizer is marked as {@link Serializable},
* the need to marshall the externalizer is only really needed when developing
* user friendly externalizers (using {@link SerializeWith}). {@link AdvancedExternalizer}
* instances do not require the externalizer to be serializable since the
* externalizer itself is not marshalled.
*
* Even though it's not strictly necessary, to avoid breaking compatibility
* with old clients, {@link Externalizer} implements {@link Serializable} but
* this requirement is only needed for those user friendly externalizers.
* There's a chance that in future major releases {@link Externalizer} won't
* extend {@link Serializable} any more, hence we strongly recommend that any
* user-friendly externalizer users mark their externalizer implementations as
* either {@link Serializable} or {@link java.io.Externalizable}.
*
* @author Galder Zamarreño
* @since 5.0
* @deprecated since 10.0, will be removed in a future release. Please configure a {@link
* org.infinispan.protostream.SerializationContextInitializer} and utilise ProtoStream annotations on Java objects instead, or
* specify a custom {@link Marshaller} implementation via the SerializationConfiguration.
*/
@Deprecated
public interface Externalizer<T> extends Serializable {
/**
* Write the object reference to the stream.
*
* @param output the object output to write to
* @param object the object reference to write
* @throws IOException if an I/O error occurs
*/
void writeObject(ObjectOutput output, T object) throws IOException;
/**
* Read an instance from the stream. The instance will have been written by the
* {@link #writeObject(ObjectOutput, Object)} method. Implementations are free
* to create instances of the object read from the stream in any way that they
* feel like. This could be via constructor, factory or reflection.
*
* @param input the object input to read from
* @return the object instance
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if a class could not be found
*/
T readObject(ObjectInput input) throws IOException, ClassNotFoundException;
}
| 5,449
| 49.462963
| 126
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/JavaSerializationMarshaller.java
|
package org.infinispan.commons.marshall;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collections;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.io.ByteBufferImpl;
import org.infinispan.commons.io.LazyByteArrayOutputStream;
/**
* Standard Java serialization marshaller.
*
* @author Galder Zamarreño
* @since 5.3
*/
public class JavaSerializationMarshaller extends AbstractMarshaller {
final ClassAllowList allowList;
public JavaSerializationMarshaller() {
this(new ClassAllowList(Collections.emptyList()));
}
public JavaSerializationMarshaller(ClassAllowList allowList) {
this.allowList = allowList;
}
@Override
public void initialize(ClassAllowList classAllowList) {
this.allowList.read(classAllowList);
}
@Override
protected ByteBuffer objectToBuffer(Object o, int estimatedSize) throws IOException {
LazyByteArrayOutputStream baos = new LazyByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(baos);
out.writeObject(o);
out.close();
baos.close();
return ByteBufferImpl.create(baos.getRawBuffer(), 0, baos.size());
}
@Override
public Object objectFromByteBuffer(byte[] buf, int offset, int length) throws IOException, ClassNotFoundException {
try (ObjectInputStream ois = new CheckedInputStream(new ByteArrayInputStream(buf), allowList)) {
return ois.readObject();
}
}
@Override
public boolean isMarshallable(Object o) {
return o instanceof Serializable;
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_SERIALIZED_OBJECT;
}
}
| 1,940
| 27.544118
| 118
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/StringMarshaller.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.nio.charset.Charset;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.io.ByteBufferImpl;
public class StringMarshaller extends AbstractMarshaller {
final Charset charset;
public StringMarshaller(Charset charset) {
this.charset = charset;
}
@Override
protected ByteBuffer objectToBuffer(Object o, int estimatedSize) {
byte[] bytes = o instanceof byte[] ? (byte[]) o : (o.toString()).getBytes(charset);
return ByteBufferImpl.create(bytes);
}
@Override
public Object objectFromByteBuffer(byte[] buf, int offset, int length) throws IOException, ClassNotFoundException {
return new String(buf, charset);
}
@Override
public boolean isMarshallable(Object o) {
return o instanceof String;
}
@Override
public MediaType mediaType() {
return MediaType.TEXT_PLAIN;
}
}
| 1,011
| 24.3
| 118
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/ImmutableProtoStreamMarshaller.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.io.ByteBufferImpl;
import org.infinispan.protostream.ImmutableSerializationContext;
import org.infinispan.protostream.ProtobufUtil;
/**
* A ProtoStream {@link org.infinispan.commons.marshall.Marshaller} implementation that uses Protobuf encoding.
*
* @author Ryan Emerson
* @since 12.0
*/
public class ImmutableProtoStreamMarshaller extends AbstractMarshaller {
protected final ImmutableSerializationContext serializationContext;
public ImmutableProtoStreamMarshaller(ImmutableSerializationContext serializationContext) {
this.serializationContext = serializationContext;
}
public ImmutableSerializationContext getSerializationContext() {
return serializationContext;
}
@Override
public Object objectFromByteBuffer(byte[] buf, int offset, int length) throws IOException, ClassNotFoundException {
return ProtobufUtil.fromWrappedByteArray(getSerializationContext(), buf, offset, length);
}
@Override
public boolean isMarshallable(Object o) {
// our marshaller can handle all of these primitive/scalar types as well even if we do not
// have a per-type marshaller defined in our SerializationContext
return o instanceof String ||
o instanceof Long ||
o instanceof Integer ||
o instanceof Double ||
o instanceof Float ||
o instanceof Boolean ||
o instanceof byte[] ||
o instanceof Byte ||
o instanceof Short ||
o instanceof Character ||
o instanceof java.util.Date ||
o instanceof java.time.Instant ||
getSerializationContext().canMarshall(o.getClass());
}
@Override
protected ByteBuffer objectToBuffer(Object o, int estimatedSize) throws IOException {
java.nio.ByteBuffer nioBuffer = ProtobufUtil.toWrappedByteBuffer(getSerializationContext(), o);
return ByteBufferImpl.create(nioBuffer.array(), nioBuffer.arrayOffset(), nioBuffer.remaining());
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_PROTOSTREAM;
}
}
| 2,295
| 34.875
| 118
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/MarshallingException.java
|
package org.infinispan.commons.marshall;
import org.infinispan.commons.CacheException;
/**
* An exception that can be thrown by a cache if an object cannot be successfully serialized/deserialized.
*
* @author Ryan Emerson
* @since 10.0
*/
public class MarshallingException extends CacheException {
public MarshallingException() {
super();
}
public MarshallingException(Throwable cause) {
super(cause);
}
public MarshallingException(String msg) {
super(msg);
}
public MarshallingException(String msg, Throwable cause) {
super(msg, cause);
}
public MarshallingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| 795
| 23.875
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/SuppliedExternalizer.java
|
package org.infinispan.commons.marshall;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Set;
import java.util.function.Supplier;
import org.infinispan.commons.util.Util;
public class SuppliedExternalizer<T> implements AdvancedExternalizer<T> {
private final Integer id;
private final Class<T> clazz;
private final Supplier<T> supplier;
public SuppliedExternalizer(Integer id, Class<T> clazz, Supplier<T> supplier) {
this.id = id;
this.clazz = clazz;
this.supplier = supplier;
}
@Override
public Set<Class<? extends T>> getTypeClasses() {
return Util.asSet(clazz);
}
@Override
public Integer getId() {
return id;
}
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
}
@Override
public T readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return supplier.get();
}
}
| 973
| 22.756098
| 86
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/exts/package-info.java
|
/**
* Provides Infinispan-specific extensions to the marshallers.
*
* @api.public
*/
package org.infinispan.commons.marshall.exts;
| 135
| 18.428571
| 62
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/marshall/exts/NoStateExternalizer.java
|
package org.infinispan.commons.marshall.exts;
import java.io.IOException;
import java.io.ObjectOutput;
import org.infinispan.commons.marshall.AbstractExternalizer;
/**
* An externalizer that writes no state. It simply marshalls class information.
*
* @author Galder Zamarreño
* @since 5.0
*/
public abstract class NoStateExternalizer<T> extends AbstractExternalizer<T> {
@Override
public void writeObject(ObjectOutput output, T object) throws IOException {
// The instance has no state, so no-op.
}
}
| 526
| 22.954545
| 79
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/internal/BlockHoundUtil.java
|
package org.infinispan.commons.internal;
public class BlockHoundUtil {
/**
* Signal to BlockHound that a method must not be called from a non-blocking thread.
*
* <p>Helpful when the method only blocks some of the time, and it is hard to force it to block
* in all the scenarios that use it.</p>
*/
public static void pretendBlock() {
// Do nothing
}
}
| 389
| 26.857143
| 98
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.