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/tasks/scripting/src/main/java/org/infinispan/scripting/impl/ScriptTask.java
package org.infinispan.scripting.impl; import java.util.Set; import org.infinispan.tasks.Task; import org.infinispan.tasks.TaskExecutionMode; public class ScriptTask implements Task { private final String name; private final TaskExecutionMode mode; private final Set<String> parameters; ScriptTask(String name, TaskExecutionMode mode, Set<String> parameters) { this.name = name; this.mode = mode; this.parameters = parameters; } @Override public String getName() { return name; } @Override public String getType() { return "Script"; } @Override public TaskExecutionMode getExecutionMode() { return mode; } @Override public Set<String> getParameters() { return parameters; } }
779
18.02439
76
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/ExecutionMode.java
package org.infinispan.scripting.impl; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.protostream.annotations.ProtoEnumValue; import org.infinispan.protostream.annotations.ProtoTypeId; /** * ScriptExecutionMode. * * @author Tristan Tarrant * @since 7.2 */ @ProtoTypeId(ProtoStreamTypeIds.EXECUTION_MODE) public enum ExecutionMode { @ProtoEnumValue(number = 0) LOCAL(LocalRunner.INSTANCE, false), @ProtoEnumValue(number = 1) DISTRIBUTED(DistributedRunner.INSTANCE, true); private final ScriptRunner runner; private final boolean clustered; private ExecutionMode(ScriptRunner runner, boolean clustered) { this.runner = runner; this.clustered = clustered; } public ScriptRunner getRunner() { return runner; } public boolean isClustered() { return clustered; } }
866
21.815789
66
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/ScriptMetadataParser.java
package org.infinispan.scripting.impl; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.util.Util; import org.infinispan.scripting.logging.Log; import org.infinispan.util.logging.LogFactory; public class ScriptMetadataParser { private static final Log log = LogFactory.getLog(ScriptMetadataParser.class, Log.class); private static final String DEFAULT_SCRIPT_EXTENSION = "js"; private static final Pattern METADATA_COMMENT = Pattern.compile("^(?:#|//|;;)\\s*(.+)"); private static final Pattern METADATA_KV = Pattern .compile("\\s*(\\w+)\\s*=\\s*(\"[^\"]*\"|\'[^\']*\'|\\[[\\w,\\s]*\\]|[^,=\\s\"]+)\\s*,?"); public static ScriptMetadata parse(String name, String script) { ScriptMetadata.Builder metadataBuilder = new ScriptMetadata.Builder(); metadataBuilder.name(name); metadataBuilder.mode(ExecutionMode.LOCAL); int s = name.lastIndexOf(".") + 1; if (s == 0 || s == name.length()) metadataBuilder.extension(DEFAULT_SCRIPT_EXTENSION); else metadataBuilder.extension(name.substring(s)); try (BufferedReader r = new BufferedReader(new StringReader(script))) { for (String line = r.readLine(); line != null; line = r.readLine()) { Matcher matcher = METADATA_COMMENT.matcher(line); if (!matcher.matches()) break; String text = matcher.group(1); matcher = METADATA_KV.matcher(text); while (matcher.find()) { String key = matcher.group(1).toLowerCase(); String value = Util.unquote(matcher.group(2)); switch (key) { case "name": metadataBuilder.name(value); break; case "extension": metadataBuilder.extension(value); break; case "language": metadataBuilder.language(value); break; case "mode": metadataBuilder.mode(ExecutionMode.valueOf(value.toUpperCase())); break; case "parameters": metadataBuilder.parameters(unarray(value)); break; case "role": metadataBuilder.role(value); break; case "datatype": metadataBuilder.dataType(MediaType.fromString(value)); break; default: throw log.unknownScriptProperty(key); } } } } catch (IOException e) { } return metadataBuilder.build(); } private static Set<String> unarray(String s) { if (s.charAt(0) == '[') { String[] ps = s.substring(1, s.length() - 1).split("\\s*,\\s*"); Set<String> parameters = new HashSet<>(); for (String p : ps) { parameters.add(p); } return parameters; } else { throw log.parametersNotArray(); } } }
3,261
34.846154
99
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/impl/ScriptingTaskEngine.java
package org.infinispan.scripting.impl; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.infinispan.tasks.Task; import org.infinispan.tasks.TaskContext; import org.infinispan.tasks.TaskExecutionMode; import org.infinispan.tasks.spi.NonBlockingTaskEngine; import org.infinispan.util.concurrent.BlockingManager; /** * ScriptingTaskEngine. * * @author Tristan Tarrant * @since 8.1 */ public class ScriptingTaskEngine implements NonBlockingTaskEngine { private final ScriptingManagerImpl scriptingManager; public ScriptingTaskEngine(ScriptingManagerImpl scriptingManager) { this.scriptingManager = scriptingManager; } @Override public String getName() { return "Script"; } @Override public List<Task> getTasks() { List<Task> tasks = new ArrayList<>(); scriptingManager.getScriptNames().forEach(s -> { ScriptMetadata scriptMetadata = scriptingManager.getScriptMetadata(s); tasks.add(new ScriptTask(s, scriptMetadata.mode().isClustered() ? TaskExecutionMode.ALL_NODES : TaskExecutionMode.ONE_NODE, scriptMetadata.parameters())); }); return tasks; } @Override public CompletionStage<List<Task>> getTasksAsync() { BlockingManager blockingManager = scriptingManager.cacheManager.getGlobalComponentRegistry().getComponent(BlockingManager.class); return blockingManager.supplyBlocking(this::getTasks, "ScriptingTaskEngine - getTasksAsync"); } @Override public <T> CompletableFuture<T> runTask(String taskName, TaskContext context, BlockingManager blockingManager) { return scriptingManager.<T>runScript(taskName, context) .toCompletableFuture(); } @Override public boolean handles(String taskName) { return scriptingManager.containsScript(taskName); } @Override public CompletionStage<Boolean> handlesAsync(String taskName) { return scriptingManager.containsScriptAsync(taskName); } }
2,053
30.6
163
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/utils/ScriptConversions.java
package org.infinispan.scripting.utils; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.Transcoder; import org.infinispan.encoding.DataConversion; import org.infinispan.marshall.core.EncoderRegistry; import org.infinispan.tasks.TaskContext; /** * @since 9.4 */ public final class ScriptConversions { public static final MediaType APPLICATION_TEXT_STRING = MediaType.TEXT_PLAIN.withClassType(String.class); private final Map<String, OutputFormatter> formatterByMediaType = new HashMap<>(2); private final EncoderRegistry encoderRegistry; public ScriptConversions(EncoderRegistry encoderRegistry) { this.encoderRegistry = encoderRegistry; formatterByMediaType.put(TEXT_PLAIN_TYPE, new TextPlainFormatter()); } public Map<String, Object> convertParameters(TaskContext context) { if (context.getParameters().isEmpty()) return null; Map<String, Object> contextParams = context.getParameters().get(); if (contextParams == Collections.EMPTY_MAP) { return new HashMap<>(2); } Map<String, Object> converted = new HashMap<>(contextParams.size()); if (context.getCache().isPresent()) { DataConversion valueDataConversion = context.getCache().get().getAdvancedCache().getValueDataConversion(); MediaType requestMediaType = valueDataConversion.getRequestMediaType(); contextParams.forEach((s, o) -> { Object c = requestMediaType == null ? o : encoderRegistry.convert(o, valueDataConversion.getRequestMediaType(), APPLICATION_OBJECT); converted.put(s, c); }); return converted; } else { return contextParams; } } public Object convertToRequestType(Object obj, MediaType objType, MediaType requestType) { if (obj == null) return null; if (requestType.equals(MediaType.MATCH_ALL)) return obj; // Older HR clients do not send request type and assume the script metadata type is the output type MediaType outputFormat = requestType.match(MediaType.APPLICATION_UNKNOWN) ? objType : requestType; OutputFormatter outputFormatter = formatterByMediaType.get(outputFormat.getTypeSubtype()); if (obj instanceof Collection) { if (outputFormatter != null) { return outputFormatter.formatCollection((Collection<?>) obj, objType, requestType); } } Transcoder transcoder = encoderRegistry.getTranscoder(objType, requestType); return transcoder.transcode(obj, objType, requestType); } private interface OutputFormatter { Object formatCollection(Collection<?> elements, MediaType elementType, MediaType destinationType); } private class TextPlainFormatter implements OutputFormatter { private String quote(Object element) { if (element == null) return "null"; return "\"" + element.toString() + "\""; } @Override public Object formatCollection(Collection<?> elements, MediaType elementType, MediaType destinationType) { Transcoder transcoder = encoderRegistry.getTranscoder(elementType, APPLICATION_TEXT_STRING); return elements.stream().map(s -> transcoder.transcode(s, elementType, APPLICATION_TEXT_STRING)) .map(this::quote).collect(Collectors.joining(", ", "[", "]")) .getBytes(destinationType.getCharset()); } } }
3,733
40.488889
144
java
null
infinispan-main/tasks/scripting/src/main/java/org/infinispan/scripting/utils/JSArrays.java
package org.infinispan.scripting.utils; import java.lang.reflect.Method; import java.util.Arrays; import java.util.stream.Stream; public class JSArrays { static final Method SCRIPTUTILS_CONVERT; static { Class<?> SCRIPTUTILS; ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { SCRIPTUTILS = Class.forName("org.openjdk.nashorn.api.scripting.ScriptUtils", true, loader); } catch (ClassNotFoundException e1) { try { SCRIPTUTILS = Class.forName("jdk.nashorn.api.scripting.ScriptUtils", true, loader); } catch (ClassNotFoundException e2) { RuntimeException rte = new RuntimeException("Cannot find Nashorn ScriptUtils"); rte.addSuppressed(e1); rte.addSuppressed(e2); throw rte; } } try { SCRIPTUTILS_CONVERT = SCRIPTUTILS.getMethod("convert", Object.class, Object.class); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } @SuppressWarnings("restriction") public static Stream<Object> stream(Object array) { try { return Arrays.stream((Object[]) SCRIPTUTILS_CONVERT.invoke(null, array, Object[].class)); } catch (Throwable t) { throw new RuntimeException(t); } } }
1,323
31.292683
100
java
null
infinispan-main/jboss-marshalling/src/test/java/org/infinispan/jboss/marshalling/MarshallExternalizersTest.java
package org.infinispan.jboss.marshalling; import java.lang.reflect.Method; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.jboss.marshalling.core.JBossUserMarshaller; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; @Test(groups = "functional", testName = "marshall.MarshallExternalizersTest") public class MarshallExternalizersTest extends org.infinispan.marshall.MarshallExternalizersTest { @Override protected GlobalConfigurationBuilder globalConfigurationBuilder() { GlobalConfigurationBuilder globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); globalBuilder.serialization().marshaller(new JBossUserMarshaller()); return globalBuilder; } public void testReplicateJBossExternalizePojo(Method m) { PojoWithJBossExternalize pojo = new PojoWithJBossExternalize(34, TestingUtil.k(m)); doReplicatePojo(m, pojo); } @Test(dependsOnMethods = "testReplicateJBossExternalizePojo") public void testReplicateJBossExternalizePojoToNewJoiningNode(Method m) { PojoWithJBossExternalize pojo = new PojoWithJBossExternalize(48, TestingUtil.k(m)); doReplicatePojoToNewJoiningNode(m, pojo); } }
1,241
39.064516
102
java
null
infinispan-main/jboss-marshalling/src/test/java/org/infinispan/jboss/marshalling/PojoWithJBossExternalize.java
package org.infinispan.jboss.marshalling; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.infinispan.commons.marshall.PojoWithAttributes; import org.jboss.marshalling.Externalize; /** * A test pojo that is marshalled using JBoss Marshalling's * {@link org.jboss.marshalling.Externalizer} which is annotated with * {@link Externalize} * * @author Galder Zamarreño * @since 5.0 */ @Externalize(PojoWithJBossExternalize.Externalizer.class) public class PojoWithJBossExternalize { final PojoWithAttributes pojo; public PojoWithJBossExternalize(int age, String key) { this.pojo = new PojoWithAttributes(age, key); } PojoWithJBossExternalize(PojoWithAttributes pojo) { this.pojo = pojo; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PojoWithJBossExternalize that = (PojoWithJBossExternalize) o; if (pojo != null ? !pojo.equals(that.pojo) : that.pojo != null) return false; return true; } @Override public int hashCode() { return pojo != null ? pojo.hashCode() : 0; } public static class Externalizer implements org.jboss.marshalling.Externalizer { private static final long serialVersionUID = -1855797134490457326L; @Override public void writeExternal(Object subject, ObjectOutput output) throws IOException { PojoWithAttributes.writeObject(output, ((PojoWithJBossExternalize) subject).pojo); } @Override public Object createExternal(Class<?> subjectType, ObjectInput input) throws IOException, ClassNotFoundException { return new PojoWithJBossExternalize(PojoWithAttributes.readObject(input)); } } }
1,806
28.145161
120
java
null
infinispan-main/jboss-marshalling/src/test/java/org/infinispan/jboss/marshalling/JBossMarshallingThreadLocalLeakTest.java
package org.infinispan.jboss.marshalling; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.util.ThreadLocalLeakTest; import org.testng.annotations.Test; /** * AbstractJBossMarshaller uses a thread-local cache of RiverMarshaller instances, * so it's worth checking for thread leaks. * * @author Dan Berindei * @since 13.0 */ @Test(groups = "functional", testName = "jboss.marshalling.JBossMarshallingThreadLocalLeakTest") public class JBossMarshallingThreadLocalLeakTest extends ThreadLocalLeakTest { @Override protected void amendConfiguration(ConfigurationBuilder builder) { builder.encoding().mediaType(MediaType.APPLICATION_JBOSS_MARSHALLING_TYPE); } }
772
34.136364
96
java
null
infinispan-main/jboss-marshalling/src/test/java/org/infinispan/jboss/marshalling/JBossMarshallingTest.java
package org.infinispan.jboss.marshalling; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import org.infinispan.test.AbstractInfinispanTest; import org.jboss.marshalling.ByteInput; import org.jboss.marshalling.ByteOutput; import org.jboss.marshalling.ContextClassResolver; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.Unmarshaller; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test the behaivour of JBoss Marshalling library itself. This class has been created to * ease the creation of tests that check specific behaivour at this level. */ @Test(groups = "functional", testName = "marshall.jboss.JBossMarshallingTest") public class JBossMarshallingTest extends AbstractInfinispanTest { private MarshallerFactory factory; private Marshaller marshaller; private Unmarshaller unmarshaller; @BeforeClass public void setUp() throws Exception { factory = (MarshallerFactory) Thread.currentThread().getContextClassLoader().loadClass("org.jboss.marshalling.river.RiverMarshallerFactory").newInstance(); MarshallingConfiguration configuration = new MarshallingConfiguration(); configuration.setClassResolver(new ContextClassResolver()); marshaller = factory.createMarshaller(configuration); unmarshaller = factory.createUnmarshaller(configuration); } @AfterClass public void tearDown() { } public void testSerObjWithRefToSerObjectWithCustomReadObj() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); ByteOutput byteOutput = Marshalling.createByteOutput(baos); marshaller.start(byteOutput); ObjectThatContainsACustomReadObjectMethod obj = new ObjectThatContainsACustomReadObjectMethod(); obj.anObjectWithCustomReadObjectMethod = new CustomReadObjectMethod(); try { marshaller.writeObject(obj); } finally { marshaller.finish(); } byte[] bytes = baos.toByteArray(); ByteInput byteInput = Marshalling.createByteInput(new ByteArrayInputStream(bytes)); unmarshaller.start(byteInput); try { assert obj.equals(unmarshaller.readObject()); } finally { unmarshaller.finish(); } } public static class CustomReadObjectMethod implements Serializable { private static final long serialVersionUID = 1L; String lastName; String ssn; transient boolean deserialized; public CustomReadObjectMethod( ) { this("Zamarreno", "234-567-8901"); } public CustomReadObjectMethod(String lastName, String ssn) { this.lastName = lastName; this.ssn = ssn; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof CustomReadObjectMethod)) return false; CustomReadObjectMethod pk = (CustomReadObjectMethod) obj; if (!lastName.equals(pk.lastName)) return false; if (!ssn.equals(pk.ssn)) return false; return true; } @Override public int hashCode( ) { int result = 17; result = result * 31 + lastName.hashCode(); result = result * 31 + ssn.hashCode(); return result; } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); deserialized = true; } } public static class ObjectThatContainsACustomReadObjectMethod implements Serializable { private static final long serialVersionUID = 1L; public CustomReadObjectMethod anObjectWithCustomReadObjectMethod; Integer balance; public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof ObjectThatContainsACustomReadObjectMethod)) return false; ObjectThatContainsACustomReadObjectMethod acct = (ObjectThatContainsACustomReadObjectMethod) obj; if (!safeEquals(balance, acct.balance)) return false; if (!safeEquals(anObjectWithCustomReadObjectMethod, acct.anObjectWithCustomReadObjectMethod)) return false; return true; } public int hashCode() { int result = 17; result = result * 31 + safeHashCode(balance); result = result * 31 + safeHashCode(anObjectWithCustomReadObjectMethod); return result; } private static int safeHashCode(Object obj) { return obj == null ? 0 : obj.hashCode(); } private static boolean safeEquals(Object a, Object b) { return (a == b || (a != null && a.equals(b))); } } }
4,997
33.951049
161
java
null
infinispan-main/jboss-marshalling/src/test/java/org/infinispan/jboss/marshalling/VersionAwareMarshallerTest.java
package org.infinispan.jboss.marshalling; import static org.infinispan.test.TestingUtil.k; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Set; import java.util.TreeSet; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.jboss.marshalling.core.JBossUserMarshaller; import org.jboss.marshalling.TraceInformation; public class VersionAwareMarshallerTest extends org.infinispan.marshall.VersionAwareMarshallerTest { @Override protected GlobalConfigurationBuilder globalConfiguration() { GlobalConfigurationBuilder globalBuilder = super.globalConfiguration(); globalBuilder.serialization().marshaller(new JBossUserMarshaller()); return globalBuilder; } public void testPojoWithJBossMarshallingExternalizer(Method m) throws Exception { PojoWithJBossExternalize pojo = new PojoWithJBossExternalize(27, k(m)); marshallAndAssertEquality(pojo); } public void testIsMarshallableJBossExternalizeAnnotation() throws Exception { PojoWithJBossExternalize pojo = new PojoWithJBossExternalize(34, "k2"); assertTrue(marshaller.isMarshallable(pojo)); } public void testMarshallObjectThatContainsACustomReadObjectMethod() throws Exception { JBossMarshallingTest.ObjectThatContainsACustomReadObjectMethod obj = new JBossMarshallingTest.ObjectThatContainsACustomReadObjectMethod(); obj.anObjectWithCustomReadObjectMethod = new JBossMarshallingTest.CustomReadObjectMethod(); marshallAndAssertEquality(obj); } public void testMarshallingNestedSerializableSubclass() throws Exception { Child1 child1Obj = new Child1(1234, "1234"); Child2 child2Obj = new Child2(2345, "2345", child1Obj); byte[] bytes = marshaller.objectToByteBuffer(child2Obj); Child2 readChild2 = (Child2) marshaller.objectFromByteBuffer(bytes); assertEquals(2345, readChild2.someInt); assertEquals("2345", readChild2.getId()); assertEquals(1234, readChild2.getChild1Obj().someInt); assertEquals("1234", readChild2.getChild1Obj().getId()); } public void testMarshallingSerializableSubclass() throws Exception { Child1 child1Obj = new Child1(1234, "1234"); byte[] bytes = marshaller.objectToByteBuffer(child1Obj); Child1 readChild1 = (Child1) marshaller.objectFromByteBuffer(bytes); assertEquals(1234, readChild1.someInt); assertEquals("1234", readChild1.getId()); } public void testTreeSetWithComparator() throws Exception { Set<Human> treeSet = new TreeSet<>(new HumanComparator()); for (int i = 0; i < 10; i++) { treeSet.add(new Human().age(i)); } marshallAndAssertEquality(treeSet); } @Override public void testErrorUnmarshalling() throws Exception { Pojo pojo = new PojoWhichFailsOnUnmarshalling(); byte[] bytes = marshaller.objectToByteBuffer(pojo); try { marshaller.objectFromByteBuffer(bytes); } catch (Exception e) { TraceInformation inf = (TraceInformation) e.getCause(); assert inf.toString().contains("in object of type org.infinispan.marshall.VersionAwareMarshallerTest$PojoWhichFailsOnUnmarshalling"); } } static class Parent implements Serializable { private final String id; private final Child1 child1Obj; public Parent(String id, Child1 child1Obj) { this.id = id; this.child1Obj = child1Obj; } public String getId() { return id; } public Child1 getChild1Obj() { return child1Obj; } } static class Child1 extends Parent { private final int someInt; public Child1(int someInt, String parentStr) { super(parentStr, null); this.someInt = someInt; } } static class Child2 extends Parent { private final int someInt; public Child2(int someInt, String parentStr, Child1 child1Obj) { super(parentStr, child1Obj); this.someInt = someInt; } } }
4,144
34.732759
144
java
null
infinispan-main/jboss-marshalling/src/test/java/org/infinispan/jboss/marshalling/dataconversion/DataConversionTest.java
package org.infinispan.jboss.marshalling.dataconversion; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.infinispan.test.fwk.TestCacheManagerFactory.createCacheManager; import static org.testng.Assert.assertEquals; import java.io.IOException; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.jboss.marshalling.commons.GenericJBossMarshaller; import org.infinispan.marshall.core.EncoderRegistry; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.data.Person; import org.testng.annotations.Test; @Test(groups = "functional", testName = "marshall.jboss.DataConversionTest") public class DataConversionTest extends org.infinispan.dataconversion.DataConversionTest { @Test public void testObjectEncoder() { GenericJbossMarshallerEncoder encoder = new GenericJbossMarshallerEncoder(org.infinispan.dataconversion.DataConversionTest.class.getClassLoader()); withCacheManager(new CacheManagerCallable( createCacheManager(new ConfigurationBuilder())) { GenericJBossMarshaller marshaller = new GenericJBossMarshaller(); private byte[] marshall(Object o) { try { return marshaller.objectToByteBuffer(o); } catch (IOException | InterruptedException e) { throw new AssertionError("Cannot marshall content", e); } } @Override public void call() { GlobalComponentRegistry registry = cm.getGlobalComponentRegistry(); EncoderRegistry encoderRegistry = registry.getComponent(EncoderRegistry.class); encoderRegistry.registerEncoder(encoder); cm.getClassAllowList().addClasses(Person.class); Cache<byte[], byte[]> cache = cm.getCache(); // Write encoded content to the cache Person key1 = new Person("key1"); Person value1 = new Person("value1"); byte[] encodedKey1 = marshall(key1); byte[] encodedValue1 = marshall(value1); cache.put(encodedKey1, encodedValue1); // Read encoded content assertEquals(cache.get(encodedKey1), encodedValue1); // Read with a different valueEncoder AdvancedCache<Person, Person> encodingCache = (AdvancedCache<Person, Person>) cache.getAdvancedCache().withEncoding(GenericJbossMarshallerEncoder.class); assertEquals(encodingCache.get(key1), value1); } }); } }
2,654
39.227273
165
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/JbossMarshallingModule.java
package org.infinispan.jboss.marshalling; import static org.infinispan.util.logging.Log.PERSISTENCE; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.jboss.marshalling.commons.GenericJBossMarshaller; import org.infinispan.jboss.marshalling.core.JBossUserMarshaller; import org.infinispan.jboss.marshalling.dataconversion.JBossMarshallingTranscoder; import org.infinispan.lifecycle.ModuleLifecycle; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.core.EncoderRegistry; /** * JBoss Marshalling module lifecycle callbacks * * <p>Registers a JBoss Marshalling encoder and transcoder.</p> * * @author Dan Berindei * @since 11.0 */ @InfinispanModule(name = "jboss-marshalling", requiredModules = "core") public class JbossMarshallingModule implements ModuleLifecycle { @Override public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) { PERSISTENCE.jbossMarshallingDetected(); Marshaller userMarshaller = globalConfiguration.serialization().marshaller(); if (userMarshaller instanceof JBossUserMarshaller) { // Core automatically registers a transcoder for the user marshaller // Initialize the externalizers from the serialization configuration ((JBossUserMarshaller) userMarshaller).initialize(gcr); } else { // Register a JBoss Marshalling transcoder, ignoring any configured externalizers ClassAllowList classAllowList = gcr.getComponent(EmbeddedCacheManager.class).getClassAllowList(); ClassLoader classLoader = globalConfiguration.classLoader(); GenericJBossMarshaller jbossMarshaller = new GenericJBossMarshaller(classLoader, classAllowList); EncoderRegistry encoderRegistry = gcr.getComponent(EncoderRegistry.class); encoderRegistry.registerTranscoder(new JBossMarshallingTranscoder(jbossMarshaller)); } } }
2,191
45.638298
107
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/core/JBossUserMarshaller.java
package org.infinispan.jboss.marshalling.core; import static org.infinispan.marshall.core.GlobalMarshaller.ID_EXTERNAL; import static org.infinispan.marshall.core.GlobalMarshaller.writeExternalClean; import java.io.IOException; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.marshall.core.impl.ClassToExternalizerMap; import org.infinispan.marshall.core.impl.ExternalExternalizers; import org.jboss.marshalling.ClassResolver; import org.jboss.marshalling.ObjectTable; import org.jboss.marshalling.Unmarshaller; /** * An extension of the {@link JBossMarshaller} that loads user defined {@link org.infinispan.commons.marshall.Externalizer} * implementations. This class can be removed if/when we no longer support a jboss-marshalling based user marshaller. * * @author Ryan Emerson * @since 10.0 * @deprecated since 11.0. To be removed in 14.0 ISPN-11947. */ @SuppressWarnings("unused") @Deprecated public class JBossUserMarshaller extends JBossMarshaller { public static final int USER_EXT_ID_MIN = AdvancedExternalizer.USER_EXT_ID_MIN; private ClassToExternalizerMap externalExts; public JBossUserMarshaller() { this(null); } public JBossUserMarshaller(ClassResolver classResolver) { super(classResolver); } public void initialize(GlobalComponentRegistry gcr) { this.globalCfg = gcr.getGlobalConfiguration(); // Only load the externalizers outside of the ISPN reserved range, this ensures that we don't accidentally persist internal types this.externalExts = ExternalExternalizers.load(globalCfg, USER_EXT_ID_MIN, Integer.MAX_VALUE); this.objectTable = new UserExternalizerObjectTable(); } @Override public boolean isMarshallable(Object o) throws Exception { return (externalExts.get(o.getClass()) != null || super.isMarshallable(o)); } /** * A {@link org.jboss.marshalling.ObjectTable} implementation that creates {@link org.jboss.marshalling.ObjectTable.Writer} * based upon a users configured {@link org.infinispan.commons.marshall.Externalizer} implementations. */ class UserExternalizerObjectTable implements ObjectTable { final ClassToExternalizerMap.IdToExternalizerMap reverseExts = externalExts.reverseMap(); @Override public ObjectTable.Writer getObjectWriter(Object object) { Class clazz = object.getClass(); AdvancedExternalizer ext = externalExts.get(clazz); return ext != null ? (out, obj) -> writeExternalClean(obj, ext, out) : null; } @Override public Object readObject(Unmarshaller unmarshaller) throws IOException, ClassNotFoundException { int type = unmarshaller.readUnsignedByte(); if (type != ID_EXTERNAL) throw new IllegalStateException(String.format("Expected type %s but received %s", ID_EXTERNAL, type)); int externalizerId = unmarshaller.readInt(); return reverseExts.get(externalizerId).readObject(unmarshaller); } } }
3,074
38.423077
135
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/core/JBossMarshaller.java
package org.infinispan.jboss.marshalling.core; import org.infinispan.commons.marshall.SerializeWith; import org.infinispan.commons.marshall.StreamingMarshaller; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.jboss.marshalling.commons.AbstractJBossMarshaller; import org.infinispan.jboss.marshalling.commons.DefaultContextClassResolver; import org.infinispan.jboss.marshalling.commons.SerializeWithExtFactory; import org.jboss.marshalling.ClassResolver; import org.jboss.marshalling.Externalize; import org.jboss.marshalling.ObjectTable; /** * A JBoss Marshalling based marshaller that is oriented at internal, embedded, Infinispan usage. It uses of a custom * object table for Infinispan based Externalizer instances that are either internal or user defined. * <p/> * The reason why this is implemented specially in Infinispan rather than resorting to Java serialization or even the * more efficient JBoss serialization is that a lot of efficiency can be gained when a majority of the serialization * that occurs has to do with a small set of known types such as {@link org.infinispan.transaction.xa.GlobalTransaction} * or {@link org.infinispan.commands.ReplicableCommand}, and class type information can be replaced with simple magic * numbers. * <p/> * Unknown types (typically user data) falls back to Java serialization. * * @author Galder Zamarreño * @author Sanne Grinovero * @since 4.0 * @deprecated since 11.0. To be removed in 14.0 ISPN-11947. */ @Deprecated public class JBossMarshaller extends AbstractJBossMarshaller implements StreamingMarshaller { GlobalConfiguration globalCfg; ObjectTable objectTable; ClassResolver classResolver; JBossMarshaller(ClassResolver classResolver) { this.classResolver = classResolver; } @Override public void start() { super.start(); baseCfg.setClassExternalizerFactory(new SerializeWithExtFactory()); baseCfg.setObjectTable(objectTable); if (classResolver == null) { // Override the class resolver with one that can detect injected // classloaders via AdvancedCache.with(ClassLoader) calls. ClassLoader cl = globalCfg.classLoader(); classResolver = new DefaultContextClassResolver(cl); } baseCfg.setClassResolver(classResolver); } @Override public void stop() { super.stop(); // Just in case, to avoid leaking class resolver which references classloader baseCfg.setClassResolver(null); } @Override public boolean isMarshallableCandidate(Object o) { return super.isMarshallableCandidate(o) || o.getClass().getAnnotation(SerializeWith.class) != null || o.getClass().getAnnotation(Externalize.class) != null; } }
2,788
38.842857
120
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/commons/RiverCloseListener.java
package org.infinispan.jboss.marshalling.commons; /** * RiverCloseListener is used by Infinispan's extension of River Marshaller and Unmarshaller * so that pools can be notified of instances not being in use anymore. * * @author Sanne Grinovero * @since 5.1 * @deprecated since 11.0. To be removed in 14.0 ISPN-11947. */ @Deprecated public interface RiverCloseListener { void closeMarshaller(); void closeUnmarshaller(); }
440
22.210526
92
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/commons/package-info.java
/** * Hooks to bridge Infinispan's marshalling APIs with JBoss Marshalling internals. * * @api.public */ package org.infinispan.jboss.marshalling.commons;
159
21.857143
82
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/commons/ExtendedRiverUnmarshaller.java
package org.infinispan.jboss.marshalling.commons; import java.io.IOException; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.reflect.SerializableClassRegistry; import org.jboss.marshalling.river.RiverMarshallerFactory; import org.jboss.marshalling.river.RiverUnmarshaller; /** * An extended {@link RiverUnmarshaller} that allows to track lifecycle of * unmarshaller so that pools can be notified when not in use any more. * * @author Galder Zamarreño * @since 5.1 * @deprecated since 11.0. To be removed in 14.0 ISPN-11947. */ @Deprecated public class ExtendedRiverUnmarshaller extends RiverUnmarshaller { private RiverCloseListener listener; protected ExtendedRiverUnmarshaller(RiverMarshallerFactory factory, SerializableClassRegistry registry, MarshallingConfiguration cfg) { super(factory, registry, cfg); } void setCloseListener(RiverCloseListener closeListener) { this.listener = closeListener; } @Override public void finish() throws IOException { super.finish(); if (listener != null) { listener.closeUnmarshaller(); } } /** * Returns number unread buffered bytes. */ public int getUnreadBufferedCount() { return limit - position; } }
1,291
25.916667
76
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/commons/JBossMarshallerFactory.java
package org.infinispan.jboss.marshalling.commons; import java.io.IOException; import org.jboss.marshalling.AbstractMarshallerFactory; import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.reflect.SerializableClassRegistry; import org.jboss.marshalling.river.RiverMarshallerFactory; /** * A JBoss Marshalling factory class for retrieving marshaller/unmarshaller * instances. The aim of this factory is to allow Infinispan to provide its own * JBoss Marshalling marshaller/unmarshaller extensions. * * @author Galder Zamarreño * @since 5.1 * @deprecated since 11.0. To be removed in 14.0 ISPN-11947. */ @Deprecated public class JBossMarshallerFactory extends AbstractMarshallerFactory { private final SerializableClassRegistry registry; private final RiverMarshallerFactory factory; public JBossMarshallerFactory() { factory = (RiverMarshallerFactory) Marshalling.getMarshallerFactory( "river", Marshalling.class.getClassLoader()); if (factory == null) throw new IllegalStateException( "River marshaller factory not found. Verify that the JBoss Marshalling River jar archive is in the classpath."); registry = SerializableClassRegistry.getInstance(); } @Override public ExtendedRiverUnmarshaller createUnmarshaller(MarshallingConfiguration configuration) throws IOException { return new ExtendedRiverUnmarshaller(factory, registry, configuration); } @Override public ExtendedRiverMarshaller createMarshaller(MarshallingConfiguration configuration) throws IOException { return new ExtendedRiverMarshaller(factory, registry, configuration); } }
1,724
35.702128
125
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/commons/SerializeWithExtFactory.java
package org.infinispan.jboss.marshalling.commons; import org.infinispan.commons.marshall.SerializeFunctionWith; import org.infinispan.commons.marshall.SerializeWith; import org.jboss.marshalling.AnnotationClassExternalizerFactory; import org.jboss.marshalling.ClassExternalizerFactory; import org.jboss.marshalling.Externalizer; /** * JBoss Marshalling plugin class for {@link ClassExternalizerFactory} that * allows for Infinispan annotations to be used instead of JBoss Marshalling * ones in order to discover which classes are serializable with Infinispan * externalizers. * * @author Galder Zamarreño * @since 5.0 * @deprecated since 11.0. To be removed in 14.0 ISPN-11947. */ @Deprecated public class SerializeWithExtFactory implements ClassExternalizerFactory { final ClassExternalizerFactory jbmarExtFactory = new AnnotationClassExternalizerFactory(); @Override public Externalizer getExternalizer(Class<?> type) { SerializeWith serialWithAnn = type.getAnnotation(SerializeWith.class); SerializeFunctionWith lambdaSerialWithAnn = type.getAnnotation(SerializeFunctionWith.class); if (serialWithAnn == null && lambdaSerialWithAnn == null) { // Check for JBoss Marshaller's @Externalize return jbmarExtFactory.getExternalizer(type); } else { try { org.infinispan.commons.marshall.Externalizer ext = serialWithAnn != null ? serialWithAnn.value().newInstance() : lambdaSerialWithAnn.value().newInstance(); return new JBossExternalizerAdapter(ext); } catch (Exception e) { throw new IllegalArgumentException(String.format( "Cannot instantiate externalizer for %s", type), e); } } } }
1,769
39.227273
98
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/commons/GenericJBossMarshaller.java
package org.infinispan.jboss.marshalling.commons; import org.infinispan.commons.configuration.ClassAllowList; /** * A marshaller that makes use of <a href="http://www.jboss.org/jbossmarshalling">JBoss Marshalling</a> * to serialize and deserialize objects. This marshaller is oriented at external, * non-core Infinispan use, such as the Java Hot Rod client. * * @author Manik Surtani * @version 4.1 * @see <a href="http://www.jboss.org/jbossmarshalling">JBoss Marshalling</a> */ public final class GenericJBossMarshaller extends AbstractJBossMarshaller { public GenericJBossMarshaller() { this(null, null); } public GenericJBossMarshaller(ClassLoader classLoader) { this(classLoader, null); } public GenericJBossMarshaller(ClassAllowList classAllowList) { this(null, classAllowList); } public GenericJBossMarshaller(ClassLoader classLoader, ClassAllowList classAllowList) { super(); if (classLoader == null) { classLoader = classAllowList != null ? classAllowList.getClassLoader() : null; } if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } if (classLoader == null) { classLoader = getClass().getClassLoader(); } baseCfg.setClassResolver(classAllowList == null ? new DefaultContextClassResolver(classLoader) : new CheckedClassResolver(classAllowList, classLoader) ); } @Override public void initialize(ClassAllowList classAllowList) { ClassLoader classLoader = ((DefaultContextClassResolver) baseCfg.getClassResolver()).getClassLoader(); baseCfg.setClassResolver(new CheckedClassResolver(classAllowList, classLoader)); } }
1,747
33.27451
108
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/commons/ExtendedRiverMarshaller.java
package org.infinispan.jboss.marshalling.commons; import java.io.IOException; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.reflect.SerializableClassRegistry; import org.jboss.marshalling.river.RiverMarshaller; import org.jboss.marshalling.river.RiverMarshallerFactory; /** * {@link RiverMarshaller} extension that allows Infinispan code to directly * create instances of it. * * @author Galder Zamarreño * @since 5.1 * @deprecated since 11.0. To be removed in 14.0 ISPN-11947. */ @Deprecated public class ExtendedRiverMarshaller extends RiverMarshaller { private RiverCloseListener listener; public ExtendedRiverMarshaller(RiverMarshallerFactory factory, SerializableClassRegistry registry, MarshallingConfiguration cfg) throws IOException { super(factory, registry, cfg); } @Override public void finish() throws IOException { super.finish(); if (listener != null) { listener.closeMarshaller(); } } void setCloseListener(RiverCloseListener listener) { this.listener = listener; } }
1,108
26.04878
95
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/commons/AbstractJBossMarshaller.java
package org.infinispan.jboss.marshalling.commons; import static org.infinispan.commons.util.ReflectionUtil.EMPTY_CLASS_ARRAY; import static org.infinispan.commons.util.Util.EMPTY_OBJECT_ARRAY; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.OutputStream; import java.io.Serializable; import java.lang.reflect.Method; import java.net.URL; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.io.ByteBufferImpl; import org.infinispan.commons.io.LazyByteArrayOutputStream; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.infinispan.commons.marshall.AbstractMarshaller; import org.infinispan.commons.marshall.StreamingMarshaller; import org.jboss.marshalling.ExceptionListener; import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.TraceInformation; import org.jboss.marshalling.Unmarshaller; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; /** * Common parent for both embedded and standalone JBoss Marshalling-based marshallers. * * @author Galder Zamarreño * @author Sanne Grinovero * @author Dan Berindei * @since 5.0 * @deprecated since 11.0. To be removed in 14.0 ISPN-11947. */ @Deprecated public abstract class AbstractJBossMarshaller extends AbstractMarshaller implements StreamingMarshaller { protected static final Log log = LogFactory.getLog(AbstractJBossMarshaller.class); protected static final JBossMarshallerFactory factory = new JBossMarshallerFactory(); protected static final int DEF_INSTANCE_COUNT = 16; protected static final int DEF_CLASS_COUNT = 8; private static final int PER_THREAD_REUSABLE_INSTANCES = 6; private static final int RIVER_INTERNAL_BUFFER = 512; protected final MarshallingConfiguration baseCfg; /** * Marshaller thread local. In non-internal marshaller usages, such as Java * Hot Rod client, this is a singleton shared by all so no urgent need for * static here. JBMAR clears pretty much any state during finish(), so no * urgent need to clear the thread local since it shouldn't be leaking. * It might take a long time to warmup and pre-initialize all needed instances! */ private final Cache<Thread, PerThreadInstanceHolder> marshallerTL = Caffeine.newBuilder().weakKeys().build(); public AbstractJBossMarshaller() { // Class resolver now set when marshaller/unmarshaller will be created baseCfg = new MarshallingConfiguration(); baseCfg.setExceptionListener(new DebuggingExceptionListener()); baseCfg.setClassExternalizerFactory(new SerializeWithExtFactory()); baseCfg.setInstanceCount(DEF_INSTANCE_COUNT); baseCfg.setClassCount(DEF_CLASS_COUNT); baseCfg.setVersion(3); } @Override final public void objectToObjectStream(final Object obj, final ObjectOutput out) throws IOException { out.writeObject(obj); } @Override final protected ByteBuffer objectToBuffer(final Object o, final int estimatedSize) throws IOException { LazyByteArrayOutputStream baos = new LazyByteArrayOutputStream(estimatedSize); ObjectOutput marshaller = startObjectOutput(baos, false, estimatedSize); try { objectToObjectStream(o, marshaller); } finally { finishObjectOutput(marshaller); } return ByteBufferImpl.create(baos.getRawBuffer(), 0, baos.size()); } @Override final public ObjectOutput startObjectOutput(final OutputStream os, final boolean isReentrant, final int estimatedSize) throws IOException { PerThreadInstanceHolder instanceHolder = getPerThreadInstanceHolder(); org.jboss.marshalling.Marshaller marshaller = instanceHolder.getMarshaller(estimatedSize); marshaller.start(Marshalling.createByteOutput(os)); return marshaller; } @Override final public void finishObjectOutput(final ObjectOutput oo) { try { if (log.isTraceEnabled()) log.trace("Stop marshaller"); ((org.jboss.marshalling.Marshaller) oo).finish(); } catch (IOException ignored) { } } @Override final public Object objectFromByteBuffer(final byte[] buf, final int offset, final int length) throws IOException, ClassNotFoundException { ByteArrayInputStream is = new ByteArrayInputStream(buf, offset, length); ObjectInput unmarshaller = startObjectInput(is, false); Object o; try { o = objectFromObjectStream(unmarshaller); } finally { finishObjectInput(unmarshaller); } return o; } @Override final public ObjectInput startObjectInput(final InputStream is, final boolean isReentrant) throws IOException { PerThreadInstanceHolder instanceHolder = getPerThreadInstanceHolder(); Unmarshaller unmarshaller = instanceHolder.getUnmarshaller(); if (log.isTraceEnabled()) log.tracef("Start unmarshaller after retrieving marshaller from %s", isReentrant ? "factory" : "thread local"); unmarshaller.start(Marshalling.createByteInput(is)); return unmarshaller; } @Override final public Object objectFromObjectStream(final ObjectInput in) throws IOException, ClassNotFoundException { return in.readObject(); } @Override final public void finishObjectInput(final ObjectInput oi) { try { if (log.isTraceEnabled()) log.trace("Stop unmarshaller"); if (oi != null) ((Unmarshaller) oi).finish(); } catch (IOException ignored) { } } @Override public boolean isMarshallable(Object o) throws Exception { Class<?> clazz = o.getClass(); boolean containsMarshallable = marshallableTypeHints.isKnownMarshallable(clazz); if (containsMarshallable) { boolean marshallable = marshallableTypeHints.isMarshallable(clazz); if (log.isTraceEnabled()) log.tracef("Marshallable type '%s' known and is marshallable=%b", clazz.getName(), marshallable); return marshallable; } else { if (isMarshallableCandidate(o)) { boolean isMarshallable = true; try { objectToBuffer(o); } catch (Exception e) { isMarshallable = false; throw e; } finally { marshallableTypeHints.markMarshallable(clazz, isMarshallable); } return true; } return false; } } @Override public void start() { // No-op } @Override public void stop() { // Clear class cache marshallableTypeHints.clear(); marshallerTL.invalidateAll(); } protected boolean isMarshallableCandidate(Object o) { return o instanceof Serializable; } private PerThreadInstanceHolder getPerThreadInstanceHolder() { final Thread thread = Thread.currentThread(); PerThreadInstanceHolder holder = marshallerTL.getIfPresent(thread); if (holder == null) { holder = new PerThreadInstanceHolder(baseCfg.clone()); marshallerTL.put(thread, holder); } return holder; } protected static final class DebuggingExceptionListener implements ExceptionListener { private static final URL[] EMPTY_URLS = {}; @Override public void handleMarshallingException(final Throwable problem, final Object subject) { if (log.isDebugEnabled()) { TraceInformation.addUserInformation(problem, "toString = " + subject.toString()); } } @Override public void handleUnmarshallingException(final Throwable problem, final Class<?> subjectClass) { if (log.isDebugEnabled()) { StringBuilder builder = new StringBuilder(); ClassLoader cl = subjectClass.getClassLoader(); builder.append("classloader hierarchy:"); ClassLoader parent = cl; while (parent != null) { if (parent.equals(cl)) { builder.append("\n\t\t-> type classloader = ").append(parent); } else { builder.append("\n\t\t-> parent classloader = ").append(parent); } URL[] urls = getClassLoaderURLs(parent); if (urls != null) { for (URL u : urls) builder.append("\n\t\t->...").append(u); } parent = parent.getParent(); } TraceInformation.addUserInformation(problem, builder.toString()); } } @Override public void handleUnmarshallingException(Throwable problem) { // no-op } private static URL[] getClassLoaderURLs(final ClassLoader cl) { URL[] urls = EMPTY_URLS; try { Class<?> returnType = urls.getClass(); Method getURLs = cl.getClass().getMethod("getURLs", EMPTY_CLASS_ARRAY); if (returnType.isAssignableFrom(getURLs.getReturnType())) { urls = (URL[]) getURLs.invoke(cl, EMPTY_OBJECT_ARRAY); } } catch (Exception ignore) { } return urls; } } private static final class PerThreadInstanceHolder implements RiverCloseListener { final MarshallingConfiguration configuration; final ExtendedRiverMarshaller[] reusableMarshaller = new ExtendedRiverMarshaller[PER_THREAD_REUSABLE_INSTANCES]; int availableMarshallerIndex = 0; final ExtendedRiverUnmarshaller[] reusableUnMarshaller = new ExtendedRiverUnmarshaller[PER_THREAD_REUSABLE_INSTANCES]; int availableUnMarshallerIndex = 0; PerThreadInstanceHolder(final MarshallingConfiguration threadDedicatedConfiguration) { this.configuration = threadDedicatedConfiguration; } Unmarshaller getUnmarshaller() throws IOException { //as opposing to getMarshaller(int), in this case we don't have a good hint about initial buffer sizing if (availableUnMarshallerIndex == PER_THREAD_REUSABLE_INSTANCES) { //we're above the pool threshold: make a throw-away-after usage Marshaller configuration.setBufferSize(512);//reset to default as it might be changed by getMarshaller return factory.createUnmarshaller(configuration); } else { ExtendedRiverUnmarshaller unMarshaller = reusableUnMarshaller[availableUnMarshallerIndex]; if (unMarshaller != null) { availableUnMarshallerIndex++; return unMarshaller; } else { configuration.setBufferSize(RIVER_INTERNAL_BUFFER);//reset to default as it might be changed by getMarshaller unMarshaller = factory.createUnmarshaller(configuration); unMarshaller.setCloseListener(this); reusableUnMarshaller[availableUnMarshallerIndex] = unMarshaller; availableUnMarshallerIndex++; return unMarshaller; } } } ExtendedRiverMarshaller getMarshaller(int estimatedSize) throws IOException { if (availableMarshallerIndex == PER_THREAD_REUSABLE_INSTANCES) { //we're above the pool threshold: make a throw-away-after usage Marshaller //setting the buffer as cheap as possible: configuration.setBufferSize(estimatedSize); return factory.createMarshaller(configuration); } else { ExtendedRiverMarshaller marshaller = reusableMarshaller[availableMarshallerIndex]; if (marshaller != null) { availableMarshallerIndex++; return marshaller; } else { //we're going to pool this one, make sure the buffer size is set to a reasonable value //as we might have changed it previously: configuration.setBufferSize(RIVER_INTERNAL_BUFFER); marshaller = factory.createMarshaller(configuration); marshaller.setCloseListener(this); reusableMarshaller[availableMarshallerIndex] = marshaller; availableMarshallerIndex++; return marshaller; } } } @Override public void closeMarshaller() { availableMarshallerIndex--; } @Override public void closeUnmarshaller() { availableUnMarshallerIndex--; } } @Override public MediaType mediaType() { return MediaType.APPLICATION_JBOSS_MARSHALLING; } }
12,737
37.137725
142
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/commons/CheckedClassResolver.java
package org.infinispan.jboss.marshalling.commons; import java.io.IOException; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.jboss.marshalling.Unmarshaller; /* * @deprecated since 11.0. To be removed in 14.0 ISPN-11947. */ @Deprecated public final class CheckedClassResolver extends DefaultContextClassResolver { protected static final Log log = LogFactory.getLog(CheckedClassResolver.class); private final ClassAllowList classAllowList; public CheckedClassResolver(ClassAllowList classAllowList, ClassLoader defaultClassLoader) { super(defaultClassLoader); this.classAllowList = classAllowList; classAllowList.addClasses(JBossExternalizerAdapter.class); } @Override public Class<?> resolveClass(Unmarshaller unmarshaller, String name, long serialVersionUID) throws IOException, ClassNotFoundException { boolean safeClass = classAllowList.isSafeClass(name); if (!safeClass) throw log.classNotInAllowList(name); return super.resolveClass(unmarshaller, name, serialVersionUID); } }
1,173
32.542857
139
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/commons/DefaultContextClassResolver.java
package org.infinispan.jboss.marshalling.commons; import java.lang.ref.WeakReference; import org.jboss.marshalling.ContextClassResolver; /** * This class refines <code>ContextClassLoader</code> to add a default class loader. * The context class loader is only used when the default is <code>null</code>. * * @author Dan Berindei &lt;dberinde@redhat.com&gt; * @since 4.2 * @deprecated since 11.0. To be removed in 14.0 ISPN-11947. */ @Deprecated public class DefaultContextClassResolver extends ContextClassResolver { private final WeakReference<ClassLoader> defaultClassLoader; public DefaultContextClassResolver(ClassLoader defaultClassLoader) { this.defaultClassLoader = new WeakReference<>(defaultClassLoader); } @Override protected ClassLoader getClassLoader() { ClassLoader defaultLoader = defaultClassLoader.get(); return defaultLoader != null ? defaultLoader : super.getClassLoader(); } }
945
30.533333
84
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/commons/JBossExternalizerAdapter.java
package org.infinispan.jboss.marshalling.commons; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.infinispan.commons.marshall.Externalizer; /** * @deprecated since 11.0. To be removed in 14.0 ISPN-11947. */ @Deprecated public class JBossExternalizerAdapter implements org.jboss.marshalling.Externalizer { private static final long serialVersionUID = 8187679200599686076L; final Externalizer<? super Object> externalizer; public JBossExternalizerAdapter(Externalizer<? super Object> externalizer) { this.externalizer = externalizer; } @Override public void writeExternal(Object subject, ObjectOutput output) throws IOException { externalizer.writeObject(output, subject); } @Override public Object createExternal(Class<?> targetClass, ObjectInput input) throws IOException, ClassNotFoundException { return externalizer.readObject(input); } }
946
28.59375
117
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/dataconversion/JBossMarshallingTranscoder.java
package org.infinispan.jboss.marshalling.dataconversion; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JBOSS_MARSHALLING; 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.TEXT_PLAIN; import static org.infinispan.commons.dataconversion.StandardConversions.convertTextToObject; import java.io.IOException; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.OneToManyTranscoder; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Transcode between application/x-jboss-marshalling and commons formats * * @since 9.2 */ public class JBossMarshallingTranscoder extends OneToManyTranscoder { protected final static Log logger = LogFactory.getLog(JBossMarshallingTranscoder.class, Log.class); private final Marshaller marshaller; public JBossMarshallingTranscoder(Marshaller marshaller) { super(APPLICATION_JBOSS_MARSHALLING, APPLICATION_OCTET_STREAM, TEXT_PLAIN, APPLICATION_OBJECT, APPLICATION_UNKNOWN); if (!marshaller.mediaType().match(APPLICATION_JBOSS_MARSHALLING)) { throw new IllegalArgumentException("Provided Marshaller " + marshaller + " cannot handle: " + APPLICATION_JBOSS_MARSHALLING); } this.marshaller = marshaller; } @Override public Object doTranscode(Object content, MediaType contentType, MediaType destinationType) { if (destinationType.match(MediaType.APPLICATION_JBOSS_MARSHALLING)) { if (contentType.match(TEXT_PLAIN)) { content = convertTextToObject(content, contentType); } if (contentType.match(APPLICATION_UNKNOWN) || contentType.match(APPLICATION_JBOSS_MARSHALLING)) { return content; } return marshall(content); } if (destinationType.match(MediaType.APPLICATION_OCTET_STREAM)) { try { Object unmarshalled = unmarshall(content); if (unmarshalled instanceof byte[]) { return unmarshalled; } return marshaller.objectToByteBuffer(unmarshalled); } catch (IOException | InterruptedException e) { throw logger.unsupportedContent(JBossMarshallingTranscoder.class.getSimpleName(), content); } } if (destinationType.match(MediaType.TEXT_PLAIN)) { String unmarshalled = unmarshall(content).toString(); return unmarshalled.getBytes(destinationType.getCharset()); } if (destinationType.match(MediaType.APPLICATION_OBJECT)) { return unmarshall(content); } if (destinationType.equals(APPLICATION_UNKNOWN)) { return content; } throw logger.unsupportedContent(JBossMarshallingTranscoder.class.getSimpleName(), content); } private byte[] marshall(Object o) { try { return marshaller.objectToByteBuffer(o); } catch (InterruptedException | IOException e) { throw logger.errorTranscoding(JBossMarshallingTranscoder.class.getSimpleName(), e); } } private Object unmarshall(Object o) { try { return o instanceof byte[] ? marshaller.objectFromByteBuffer((byte[]) o) : o; } catch (IOException | ClassNotFoundException e) { throw logger.errorTranscoding(JBossMarshallingTranscoder.class.getSimpleName(), e); } } }
3,672
40.738636
134
java
null
infinispan-main/jboss-marshalling/src/main/java/org/infinispan/jboss/marshalling/dataconversion/GenericJbossMarshallerEncoder.java
package org.infinispan.jboss.marshalling.dataconversion; import org.infinispan.commons.dataconversion.EncoderIds; import org.infinispan.commons.dataconversion.MarshallerEncoder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.jboss.marshalling.commons.GenericJBossMarshaller; /** * @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 GenericJbossMarshallerEncoder extends MarshallerEncoder { public GenericJbossMarshallerEncoder(GenericJBossMarshaller marshaller) { super(marshaller); } public GenericJbossMarshallerEncoder(ClassLoader classLoader) { super(new GenericJBossMarshaller(classLoader)); } @Override public MediaType getStorageFormat() { return MediaType.APPLICATION_JBOSS_MARSHALLING; } @Override public short id() { return EncoderIds.GENERIC_MARSHALLER; } }
958
28.060606
107
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/configuration/ConfigurationTest.java
package org.infinispan.server.router.configuration; import static org.assertj.core.api.Assertions.assertThat; import java.net.InetAddress; import org.infinispan.server.core.ProtocolServer; import org.infinispan.server.router.configuration.builder.RouterConfigurationBuilder; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.RouteDestination; import org.infinispan.server.router.routes.RouteSource; import org.junit.Test; import org.mockito.Mockito; public class ConfigurationTest { @Test public void shouldBuildProperRouterConfiguration() { //given RouterConfigurationBuilder multiTenantConfigurationBuilder = new RouterConfigurationBuilder(); RouteSource s1 = new RouteSource() { }; RouteDestination d1 = new RouteDestination("test", Mockito.mock(ProtocolServer.class)) {}; //when multiTenantConfigurationBuilder .hotrod() .tcpKeepAlive(true) .receiveBufferSize(1) .sendBufferSize(1) .tcpNoDelay(false) .port(1010) .ip(InetAddress.getLoopbackAddress()) .rest() .port(1111) .ip(InetAddress.getLoopbackAddress()) .routing() .add(new Route(s1, d1)); RouterConfiguration routerConfiguration = multiTenantConfigurationBuilder.build(); HotRodRouterConfiguration hotRodRouterConfiguration = routerConfiguration.hotRodRouter(); RestRouterConfiguration restRouterConfiguration = routerConfiguration.restRouter(); //then assertThat(hotRodRouterConfiguration.getPort()).isEqualTo(1010); assertThat(hotRodRouterConfiguration.getIp()).isEqualTo(InetAddress.getLoopbackAddress()); assertThat(hotRodRouterConfiguration.tcpKeepAlive()).isTrue(); assertThat(hotRodRouterConfiguration.tcpNoDelay()).isFalse(); assertThat(hotRodRouterConfiguration.sendBufferSize()).isEqualTo(1); assertThat(hotRodRouterConfiguration.receiveBufferSize()).isEqualTo(1); assertThat(restRouterConfiguration.getPort()).isEqualTo(1111); assertThat(restRouterConfiguration.getIp()).isEqualTo(InetAddress.getLoopbackAddress()); assertThat(routerConfiguration.routingTable().routesCount()).isEqualTo(1); } }
2,384
39.423729
102
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/profiling/EndpointRouterPerfTest.java
package org.infinispan.server.router.profiling; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.commons.test.categories.Profiling; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.router.Router; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.RouteDestination; import org.infinispan.server.router.routes.RouteSource; import org.junit.Test; import org.junit.experimental.categories.Category; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import io.netty.util.internal.logging.InternalLoggerFactory; import io.netty.util.internal.logging.JdkLoggerFactory; /** * This class is responsible for performance tests against the router. It tests 3 configurations: <ul> <li>No SSL at * all</li> <li>HotRod with SSL only</li> <li>Multi tenant router with SSL+SNI</li> </ul> * <p> * <p> Note that this class is not triggered by Surefire by default (it doesn't end with "test"). We want to do * performance test on demand only. </p> */ public class EndpointRouterPerfTest { private static final int MEASUREMENT_ITERATIONS_COUNT = 1; private static final int WARMUP_ITERATIONS_COUNT = 1; @Test @Category(Profiling.class) public void performRouterBenchmark() throws Exception { Options opt = new OptionsBuilder() .include(this.getClass().getName() + ".*") .mode(Mode.AverageTime) .mode(Mode.SingleShotTime) .timeUnit(TimeUnit.MILLISECONDS) .warmupIterations(WARMUP_ITERATIONS_COUNT) .measurementIterations(MEASUREMENT_ITERATIONS_COUNT) .threads(1) .forks(1) .shouldFailOnError(true) .shouldDoGC(true) .build(); new Runner(opt).run(); } @State(Scope.Thread) public static class BenchmarkState { @Param({ "org.infinispan.server.router.performance.configuration.SingleServerNoSsl", "org.infinispan.server.router.performance.configuration.SingleServerWithSsl", "org.infinispan.server.router.performance.configuration.TwoServersWithSslSni" }) public String configurationClassName; private List<HotRodServer> hotRodServers; private Optional<Set<Route<? extends RouteSource, ? extends RouteDestination>>> routes; private RemoteCacheManager preloadedClient; private Optional<Router> router; private PerfTestConfiguration configuration; @Setup public void setup() throws Exception { //Netty uses SLF and SLF can redirect to all other logging frameworks. //Just to make sure we know what we are testing against - let's enforce one of them InternalLoggerFactory.setDefaultFactory(JdkLoggerFactory.INSTANCE); //Temporary to make the test equal System.setProperty("infinispan.server.channel.epoll", "false"); configuration = (PerfTestConfiguration) Class.forName(configurationClassName).getDeclaredConstructor(null).newInstance(null); hotRodServers = configuration.initServers(); routes = configuration.initRoutes(hotRodServers); router = configuration.initRouter(routes); preloadedClient = configuration.initClient(router, routes, hotRodServers); } @TearDown public void tearDown() { preloadedClient.stop(); configuration.shutdown(hotRodServers, router); } @Benchmark public void initConnectionOnly() { RemoteCacheManager client = configuration.initClient(router, routes, hotRodServers); client.stop(); } @Benchmark public void initConnectionAndPerform10Puts() { RemoteCacheManager client = configuration.initClient(router, routes, hotRodServers); configuration.performLoadTesting(client, 10); client.stop(); } @Benchmark public void initConnectionAndPerform10KPuts() { RemoteCacheManager client = configuration.initClient(router, routes, hotRodServers); configuration.performLoadTesting(client, 10_000); client.stop(); } @Benchmark public void perform10KPuts() { configuration.performLoadTesting(preloadedClient, 10_000); } } }
4,969
38.76
137
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/profiling/PerfTestConfiguration.java
package org.infinispan.server.router.profiling; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.IntStream; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.commons.util.Util; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.router.Router; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.RouteDestination; import org.infinispan.server.router.routes.RouteSource; public interface PerfTestConfiguration { List<HotRodServer> initServers(); RemoteCacheManager initClient(Optional<Router> router, Optional<Set<Route<? extends RouteSource, ? extends RouteDestination>>> routes, List<HotRodServer> servers); default Optional<Set<Route<? extends RouteSource, ? extends RouteDestination>>> initRoutes(List<HotRodServer> servers) { return Optional.empty(); } default Optional<Router> initRouter(Optional<Set<Route<? extends RouteSource, ? extends RouteDestination>>> routes) { return Optional.empty(); } default void shutdown(List<HotRodServer> servers, Optional<Router> router) { servers.forEach(s -> s.stop()); router.ifPresent(r -> r.stop()); } default void performLoadTesting(RemoteCacheManager client, int numberOfIterations) { String keyPrefix = Util.threadLocalRandomUUID().toString(); RemoteCache<String, String> cache = client.getCache(); IntStream.range(0, numberOfIterations).forEach(i -> cache.put(keyPrefix + i, "val" + i)); } }
1,638
37.116279
167
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/profiling/configuration/SingleServerNoSsl.java
package org.infinispan.server.router.profiling.configuration; import java.net.InetAddress; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Set; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.server.router.Router; import org.infinispan.server.router.profiling.PerfTestConfiguration; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.RouteDestination; import org.infinispan.server.router.routes.RouteSource; import org.infinispan.server.router.utils.HotRodClientTestingUtil; public class SingleServerNoSsl implements PerfTestConfiguration { @Override public List<HotRodServer> initServers() { HotRodServerConfigurationBuilder configuration = new HotRodServerConfigurationBuilder().port(0); return Arrays.asList(HotRodTestingUtil.startHotRodServer(new DefaultCacheManager(), configuration)); } @Override public RemoteCacheManager initClient(Optional<Router> router, Optional<Set<Route<? extends RouteSource, ? extends RouteDestination>>> routes, List<HotRodServer> servers) { int port = servers.get(0).getTransport().getPort(); return HotRodClientTestingUtil.createNoAuth(InetAddress.getLoopbackAddress(), port); } }
1,539
41.777778
175
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/profiling/configuration/SingleServerWithSsl.java
package org.infinispan.server.router.profiling.configuration; import java.net.InetAddress; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Set; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.server.router.Router; import org.infinispan.server.router.profiling.PerfTestConfiguration; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.RouteDestination; import org.infinispan.server.router.routes.RouteSource; import org.infinispan.server.router.utils.HotRodClientTestingUtil; public class SingleServerWithSsl implements PerfTestConfiguration { private final String KEYSTORE_LOCATION = getClass().getClassLoader().getResource("sni_server_keystore.jks").getPath(); private final String TRUSTSTORE_LOCATION = getClass().getClassLoader().getResource("sni_client_truststore.jks").getPath(); private final char[] PASSWORD = "secret".toCharArray(); @Override public List<HotRodServer> initServers() { HotRodServerConfigurationBuilder configuration = new HotRodServerConfigurationBuilder().port(0); configuration.ssl() .enable() .keyStoreFileName(KEYSTORE_LOCATION) .keyStorePassword(PASSWORD) .trustStoreFileName(TRUSTSTORE_LOCATION) .trustStorePassword(PASSWORD); return Arrays.asList(HotRodTestingUtil.startHotRodServer(new DefaultCacheManager(), configuration)); } @Override public RemoteCacheManager initClient(Optional<Router> router, Optional<Set<Route<? extends RouteSource, ? extends RouteDestination>>> routes, List<HotRodServer> servers) { int port = servers.get(0).getTransport().getPort(); return HotRodClientTestingUtil.createWithSsl(InetAddress.getLoopbackAddress(), port, TRUSTSTORE_LOCATION, PASSWORD); } }
2,139
45.521739
175
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/profiling/configuration/TwoServersWithSslSni.java
package org.infinispan.server.router.profiling.configuration; import java.net.InetAddress; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.server.router.Router; import org.infinispan.server.router.configuration.builder.RouterConfigurationBuilder; import org.infinispan.server.router.profiling.PerfTestConfiguration; import org.infinispan.server.router.router.EndpointRouter; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.RouteDestination; import org.infinispan.server.router.routes.RouteSource; import org.infinispan.server.router.routes.hotrod.HotRodServerRouteDestination; import org.infinispan.server.router.routes.hotrod.SniNettyRouteSource; import org.infinispan.server.router.utils.HotRodClientTestingUtil; public class TwoServersWithSslSni implements PerfTestConfiguration { private final String KEYSTORE_LOCATION_FOR_HOTROD_1 = getClass().getClassLoader().getResource("sni_server_keystore.jks").getPath(); private final String TRUSTSTORE_LOCATION_FOT_HOTROD_1 = getClass().getClassLoader().getResource("sni_client_truststore.jks").getPath(); private final String KEYSTORE_LOCATION_FOR_HOTROD_2 = getClass().getClassLoader().getResource("default_server_keystore.jks").getPath(); private final char[] KEYSTORE_PASSWORD = "secret".toCharArray(); @Override public List<HotRodServer> initServers() { HotRodServer hotrodServer1 = HotRodTestingUtil.startHotRodServerWithoutTransport(); HotRodServer hotrodServer2 = HotRodTestingUtil.startHotRodServerWithoutTransport(); return Arrays.asList(hotrodServer1, hotrodServer2); } @Override public Optional<Set<Route<? extends RouteSource, ? extends RouteDestination>>> initRoutes(List<HotRodServer> servers) { Set<Route<? extends RouteSource, ? extends RouteDestination>> routes = new HashSet<>(); HotRodServerRouteDestination hotrod1Destination = new HotRodServerRouteDestination("hotrod1", servers.get(0)); SniNettyRouteSource hotrod1Source = new SniNettyRouteSource("hotrod1", KEYSTORE_LOCATION_FOR_HOTROD_1, KEYSTORE_PASSWORD); routes.add(new Route<>(hotrod1Source, hotrod1Destination)); HotRodServerRouteDestination hotrod2Destination = new HotRodServerRouteDestination("hotrod2", servers.get(1)); SniNettyRouteSource hotrod2Source = new SniNettyRouteSource("hotrod2", KEYSTORE_LOCATION_FOR_HOTROD_2, KEYSTORE_PASSWORD); routes.add(new Route<>(hotrod2Source, hotrod2Destination)); return Optional.of(routes); } @Override public Optional<Router> initRouter(Optional<Set<Route<? extends RouteSource, ? extends RouteDestination>>> routes) { RouterConfigurationBuilder routerConfigurationBuilder = new RouterConfigurationBuilder(); routerConfigurationBuilder .hotrod() .port(0) .ip(InetAddress.getLoopbackAddress()); routes.get().stream().forEach(r -> routerConfigurationBuilder.routing().add(r)); Router router = new Router(routerConfigurationBuilder.build()); router.start(); return Optional.of(router); } @Override public RemoteCacheManager initClient(Optional<Router> router, Optional<Set<Route<? extends RouteSource, ? extends RouteDestination>>> routes, List<HotRodServer> servers) { InetAddress ip = router.flatMap(r -> r.getRouter(EndpointRouter.Protocol.HOT_ROD)).map(r -> r.getIp()).get(); int port = router.flatMap(r -> r.getRouter(EndpointRouter.Protocol.HOT_ROD)).map(r -> r.getPort()).get(); return HotRodClientTestingUtil.createWithSni(ip, port, "hotrod1", TRUSTSTORE_LOCATION_FOT_HOTROD_1, KEYSTORE_PASSWORD); } }
3,973
50.61039
175
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/integration/ProtocolServerEndpointRouterTest.java
package org.infinispan.server.router.integration; import static org.assertj.core.api.Assertions.assertThat; import java.net.InetAddress; import org.infinispan.Cache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.test.security.TestCertificates; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.server.router.Router; import org.infinispan.server.router.configuration.builder.RouterConfigurationBuilder; import org.infinispan.server.router.router.EndpointRouter; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.hotrod.HotRodServerRouteDestination; import org.infinispan.server.router.routes.hotrod.SniNettyRouteSource; import org.infinispan.server.router.utils.HotRodClientTestingUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class ProtocolServerEndpointRouterTest { private HotRodServer hotrodServer1; private HotRodServer hotrodServer2; private Router router; private RemoteCacheManager hotrod1Client; private RemoteCacheManager hotrod2Client; @BeforeClass public static void beforeClass() { TestResourceTracker.testStarted(ProtocolServerEndpointRouterTest.class.getName()); } @AfterClass public static void afterClass() { TestResourceTracker.testFinished(ProtocolServerEndpointRouterTest.class.getName()); } @After public void afterMethod() { if (router != null) { router.stop(); } if (hotrodServer1 != null) { hotrodServer1.stop(); hotrodServer1.getCacheManager().stop(); } if (hotrodServer2 != null) { hotrodServer2.stop(); hotrodServer2.getCacheManager().stop(); } if (hotrod1Client != null) { hotrod1Client.stop(); } if (hotrod2Client != null) { hotrod2Client.stop(); } } /** * In this scenario we create 2 HotRod servers, each one with different credentials and SNI name. We also create a * new client for each server. The clients use proper TrustStores as well as SNI names. * <p> * The router should match properly SNI based routes and connect clients to proper server instances. */ @Test public void shouldRouteToProperHotRodServerBasedOnSniHostName() { //given hotrodServer1 = HotRodTestingUtil.startHotRodServerWithoutTransport("default"); hotrodServer2 = HotRodTestingUtil.startHotRodServerWithoutTransport("default"); HotRodServerRouteDestination hotrod1Destination = new HotRodServerRouteDestination("HotRod1", hotrodServer1); SniNettyRouteSource hotrod1Source = new SniNettyRouteSource("server", TestCertificates.certificate("server"), TestCertificates.KEY_PASSWORD); Route<SniNettyRouteSource, HotRodServerRouteDestination> routeToHotrod1 = new Route<>(hotrod1Source, hotrod1Destination); HotRodServerRouteDestination hotrod2Destination = new HotRodServerRouteDestination("HotRod2", hotrodServer2); SniNettyRouteSource hotrod2Source = new SniNettyRouteSource("sni", TestCertificates.certificate("sni"), TestCertificates.KEY_PASSWORD); Route<SniNettyRouteSource, HotRodServerRouteDestination> routeToHotrod2 = new Route<>(hotrod2Source, hotrod2Destination); RouterConfigurationBuilder routerConfigurationBuilder = new RouterConfigurationBuilder(); routerConfigurationBuilder .hotrod() //use random port .port(0) .ip(InetAddress.getLoopbackAddress()) .routing() .add(routeToHotrod1) .add(routeToHotrod2); router = new Router(routerConfigurationBuilder.build()); router.start(); InetAddress routerIp = router.getRouter(EndpointRouter.Protocol.HOT_ROD).get().getIp(); int routerPort = router.getRouter(EndpointRouter.Protocol.HOT_ROD).get().getPort(); //when hotrod1Client = HotRodClientTestingUtil.createWithSni(routerIp, routerPort, "server", TestCertificates.certificate("ca"), TestCertificates.KEY_PASSWORD); hotrod2Client = HotRodClientTestingUtil.createWithSni(routerIp, routerPort, "sni", TestCertificates.certificate("ca"), TestCertificates.KEY_PASSWORD); hotrod1Client.getCache("default").put("test", "hotrod1"); hotrod2Client.getCache("default").put("test", "hotrod2"); //then Cache<String, String> hotrod1Cache = hotrodServer1.getCacheManager().getCache("default"); Cache<String, String> hotrod2Cache = hotrodServer2.getCacheManager().getCache("default"); assertThat(hotrod1Cache.size()).isEqualTo(1); assertThat(hotrod2Cache.size()).isEqualTo(1); assertThat(hotrod1Cache.get("test")).isEqualTo("hotrod1"); assertThat(hotrod2Cache.get("test")).isEqualTo("hotrod2"); } }
5,111
43.068966
161
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/integration/SinglePortTest.java
package org.infinispan.server.router.integration; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.net.InetAddress; import java.util.concurrent.CompletionStage; import org.assertj.core.api.Assertions; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.Protocol; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.test.security.TestCertificates; import org.infinispan.commons.util.SslContextFactory; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.RestServer; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.rest.configuration.RestServerConfigurationBuilder; import org.infinispan.server.core.DummyServerManagement; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.server.router.Router; import org.infinispan.server.router.configuration.builder.RouterConfigurationBuilder; import org.infinispan.server.router.router.EndpointRouter; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.hotrod.HotRodServerRouteDestination; import org.infinispan.server.router.routes.rest.RestServerRouteDestination; import org.infinispan.server.router.routes.singleport.SinglePortRouteSource; import org.infinispan.server.router.utils.RestTestingUtil; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.wildfly.openssl.OpenSSLEngine; import io.netty.util.CharsetUtil; public class SinglePortTest { public static final RestEntity VALUE = RestEntity.create(TEXT_PLAIN, "test".getBytes(CharsetUtil.UTF_8)); private Router router; private RestServer restServer; private HotRodServer hotrodServer; private RestClient httpClient; private RemoteCacheManager hotRodClient; @BeforeClass public static void beforeClass() { TestResourceTracker.testStarted(MethodHandles.lookup().lookupClass().toString()); } @AfterClass public static void afterClass() { TestResourceTracker.testFinished(MethodHandles.lookup().lookupClass().toString()); } @After public void afterMethod() throws IOException { if (httpClient != null) { httpClient.close(); } HotRodClientTestingUtil.killRemoteCacheManager(hotRodClient); RestTestingUtil.killRouter(router); HotRodClientTestingUtil.killServers(hotrodServer); if (hotrodServer != null) { TestingUtil.killCacheManagers(hotrodServer.getCacheManager()); } if (restServer != null) { restServer.stop(); TestingUtil.killCacheManagers(restServer.getCacheManager()); } hotRodClient = null; hotrodServer = null; restServer = null; } @Test public void shouldUpgradeThroughHTTP11UpgradeHeaders() { //given restServer = RestTestingUtil.createDefaultRestServer("rest", "default"); RestServerRouteDestination restDestination = new RestServerRouteDestination("rest1", restServer); SinglePortRouteSource singlePortSource = new SinglePortRouteSource(); Route<SinglePortRouteSource, RestServerRouteDestination> routeToRest = new Route<>(singlePortSource, restDestination); RouterConfigurationBuilder routerConfigurationBuilder = new RouterConfigurationBuilder(); routerConfigurationBuilder .singlePort() .port(0) .ip(InetAddress.getLoopbackAddress()) .routing() .add(routeToRest); router = new Router(routerConfigurationBuilder.build()); router.start(); int port = router.getRouter(EndpointRouter.Protocol.SINGLE_PORT).get().getPort(); //when RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.addServer().host("localhost").port(port).protocol(Protocol.HTTP_20); httpClient = RestClient.forConfiguration(builder.build()); CompletionStage<RestResponse> response = httpClient.cache("default").post("test", VALUE); //then ResponseAssertion.assertThat(response).hasNoContent(); } @Test public void shouldUpgradeToHotRodThroughHTTP11UpgradeHeaders() { //given EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); // Initialize a transport-less Hot Rod server HotRodServerConfigurationBuilder hotRodServerBuilder = new HotRodServerConfigurationBuilder(); hotRodServerBuilder.startTransport(false); hotRodServerBuilder.name(TestResourceTracker.getCurrentTestName()); hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager, hotRodServerBuilder); // Initialize a transport-less REST server restServer = new RestServer(); RestServerConfigurationBuilder restServerConfigurationBuilder = new RestServerConfigurationBuilder(); restServerConfigurationBuilder.startTransport(false); restServerConfigurationBuilder.name(TestResourceTracker.getCurrentTestName()); restServer.setServerManagement(new DummyServerManagement(), true); restServer.start(restServerConfigurationBuilder.build(), cacheManager); // Initialize a Single Port server with routes to the Hot Rod and REST servers HotRodServerRouteDestination hotrodDestination = new HotRodServerRouteDestination("hotrod", hotrodServer); RestServerRouteDestination restDestination = new RestServerRouteDestination("rest", restServer); SinglePortRouteSource singlePortSource = new SinglePortRouteSource(); Route<SinglePortRouteSource, HotRodServerRouteDestination> routeToHotRod = new Route<>(singlePortSource, hotrodDestination); Route<SinglePortRouteSource, RestServerRouteDestination> routeToRest = new Route<>(singlePortSource, restDestination); RouterConfigurationBuilder routerConfigurationBuilder = new RouterConfigurationBuilder(); routerConfigurationBuilder .singlePort() .port(0) .ip(InetAddress.getLoopbackAddress()) .routing() .add(routeToRest) .add(routeToHotRod); router = new Router(routerConfigurationBuilder.build()); router.start(); EndpointRouter endpointRouter = router.getRouter(EndpointRouter.Protocol.SINGLE_PORT).get(); String host = endpointRouter.getHost(); int port = endpointRouter.getPort(); // First off we verify that the HTTP side of things works RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.addServer().host(host).port(port).protocol(Protocol.HTTP_11); httpClient = RestClient.forConfiguration(builder.build()); CompletionStage<RestResponse> response = httpClient.cache(cacheManager.getCacheManagerConfiguration().defaultCacheName().get()).post("key", VALUE); ResponseAssertion.assertThat(response).hasNoContent(); Assertions.assertThat(restServer.getCacheManager().getCache().size()).isEqualTo(1); // Next up, the RemoteCacheManager ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.marshaller(new UTF8StringMarshaller()); configurationBuilder.addServer().host(host).port(port); hotRodClient = new RemoteCacheManager(configurationBuilder.build()); Object value = hotRodClient.getCache().withDataFormat(DataFormat.builder().keyType(TEXT_PLAIN).valueType(TEXT_PLAIN).build()).get("key"); Assertions.assertThat(value).isEqualTo("test"); } @Test public void shouldUpgradeThroughALPN() throws Exception { checkForOpenSSL(); //given restServer = RestTestingUtil.createDefaultRestServer("rest", "default"); RestServerRouteDestination restDestination = new RestServerRouteDestination("rest", restServer); SinglePortRouteSource singlePortSource = new SinglePortRouteSource(); Route<SinglePortRouteSource, RestServerRouteDestination> routeToRest = new Route<>(singlePortSource, restDestination); SslContextFactory sslContextFactory = new SslContextFactory(); RouterConfigurationBuilder routerConfigurationBuilder = new RouterConfigurationBuilder(); routerConfigurationBuilder .singlePort() .sslContext(sslContextFactory.keyStoreFileName(TestCertificates.certificate("server")).keyStorePassword(TestCertificates.KEY_PASSWORD).getContext()) .port(0) .ip(InetAddress.getLoopbackAddress()) .routing() .add(routeToRest); router = new Router(routerConfigurationBuilder.build()); router.start(); EndpointRouter singlePortRouter = router.getRouter(EndpointRouter.Protocol.SINGLE_PORT).get(); //when RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.addServer().host(singlePortRouter.getHost()).port(singlePortRouter.getPort()).protocol(Protocol.HTTP_20) .security().ssl().trustStoreFileName(TestCertificates.certificate("ca")).trustStorePassword(TestCertificates.KEY_PASSWORD) .hostnameVerifier((hostname, session) -> true); httpClient = RestClient.forConfiguration(builder.build()); CompletionStage<RestResponse> response = httpClient.cache("default").post("test", VALUE); //then ResponseAssertion.assertThat(response).hasNoContent(); } @Test public void shouldUpgradeToHotRodThroughALPN() { checkForOpenSSL(); //given hotrodServer = HotRodTestingUtil.startHotRodServerWithoutTransport("default"); restServer = RestTestingUtil.createDefaultRestServer("rest", "default"); HotRodServerRouteDestination hotrodDestination = new HotRodServerRouteDestination("hotrod", hotrodServer); RestServerRouteDestination restDestination = new RestServerRouteDestination("rest", restServer); SinglePortRouteSource singlePortSource = new SinglePortRouteSource(); Route<SinglePortRouteSource, RestServerRouteDestination> routeToRest = new Route<>(singlePortSource, restDestination); Route<SinglePortRouteSource, HotRodServerRouteDestination> routeToHotRod = new Route<>(singlePortSource, hotrodDestination); SslContextFactory sslContextFactory = new SslContextFactory(); RouterConfigurationBuilder routerConfigurationBuilder = new RouterConfigurationBuilder(); routerConfigurationBuilder .singlePort() .sslContext(sslContextFactory.keyStoreFileName(TestCertificates.certificate("server")).keyStorePassword(TestCertificates.KEY_PASSWORD).getContext()) .port(0) .ip(InetAddress.getLoopbackAddress()) .routing() .add(routeToRest) .add(routeToHotRod); router = new Router(routerConfigurationBuilder.build()); router.start(); EndpointRouter endpointRouter = router.getRouter(EndpointRouter.Protocol.SINGLE_PORT).get(); //when ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host(endpointRouter.getIp().getHostAddress()).port(endpointRouter.getPort()); builder.security().ssl().trustStoreFileName(TestCertificates.certificate("ca")).trustStorePassword(TestCertificates.KEY_PASSWORD); hotRodClient = new RemoteCacheManager(builder.build()); hotRodClient.getCache("default").put("test", "test"); } private void checkForOpenSSL() { if (!OpenSSLEngine.isAlpnSupported()) { throw new IllegalStateException("OpenSSL is not present, can not test TLS/ALPN support."); } } }
12,827
47.961832
162
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/integration/RestEndpointRouterTest.java
package org.infinispan.server.router.integration; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import static org.infinispan.util.concurrent.CompletionStages.join; import java.lang.invoke.MethodHandles; import java.net.InetAddress; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestRawClient; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.client.rest.configuration.ServerConfigurationBuilder; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.util.Util; import org.infinispan.rest.RestServer; import org.infinispan.server.router.Router; import org.infinispan.server.router.configuration.builder.RouterConfigurationBuilder; import org.infinispan.server.router.router.EndpointRouter; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.rest.RestRouteSource; import org.infinispan.server.router.routes.rest.RestServerRouteDestination; import org.infinispan.server.router.utils.RestTestingUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class RestEndpointRouterTest { private RestServer restServer1; private RestServer restServer2; private Router router; private RestClient restClient; @BeforeClass public static void beforeClass() { TestResourceTracker.testStarted(MethodHandles.lookup().lookupClass().toString()); } @AfterClass public static void afterClass() { TestResourceTracker.testFinished(MethodHandles.lookup().lookupClass().toString()); } @After public void tearDown() { Util.close(restClient); router.stop(); restServer1.getCacheManager().stop(); restServer1.stop(); restServer2.getCacheManager().stop(); restServer2.stop(); } /** * In this scenario we create 2 REST servers, each one with different REST Path: <ul> <li>REST1 - * http://127.0.0.1:8080/rest/rest1</li> <li>REST2 - http://127.0.0.1:8080/rest/rest2</li> </ul> * <p> * The router should match requests based on path and redirect them to proper server. */ @Test public void shouldRouteToProperRestServerBasedOnPath() { //given restServer1 = RestTestingUtil.createDefaultRestServer("rest1", "default"); restServer2 = RestTestingUtil.createDefaultRestServer("rest2", "default"); RestServerRouteDestination rest1Destination = new RestServerRouteDestination("rest1", restServer1); RestRouteSource rest1Source = new RestRouteSource("rest1"); Route<RestRouteSource, RestServerRouteDestination> routeToRest1 = new Route<>(rest1Source, rest1Destination); RestServerRouteDestination rest2Destination = new RestServerRouteDestination("rest2", restServer2); RestRouteSource rest2Source = new RestRouteSource("rest2"); Route<RestRouteSource, RestServerRouteDestination> routeToRest2 = new Route<>(rest2Source, rest2Destination); RouterConfigurationBuilder routerConfigurationBuilder = new RouterConfigurationBuilder(); routerConfigurationBuilder .rest() .port(8080) .ip(InetAddress.getLoopbackAddress()) .routing() .add(routeToRest1) .add(routeToRest2); router = new Router(routerConfigurationBuilder.build()); router.start(); int port = router.getRouter(EndpointRouter.Protocol.REST).get().getPort(); //when ServerConfigurationBuilder builder = new RestClientConfigurationBuilder().addServer().host("127.0.0.1").port(port); restClient = RestClient.forConfiguration(builder.build()); RestRawClient rawClient = restClient.raw(); String path1 = "/rest/rest1/v2/caches/default/test"; String path2 = "/rest/rest2/v2/caches/default/test"; join(rawClient.putValue(path1, emptyMap(), "rest1", TEXT_PLAIN_TYPE)); join(rawClient.putValue(path2, emptyMap(), "rest2", TEXT_PLAIN_TYPE)); String valueReturnedFromRest1 = join(rawClient.get(path1)).getBody(); String valueReturnedFromRest2 = join(rawClient.get(path2)).getBody(); //then assertThat(valueReturnedFromRest1).isEqualTo("rest1"); assertThat(valueReturnedFromRest2).isEqualTo("rest2"); } }
4,556
40.807339
123
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/utils/HotRodClientTestingUtil.java
package org.infinispan.server.router.utils; import java.net.InetAddress; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; public class HotRodClientTestingUtil { public static RemoteCacheManager createWithSni(InetAddress ip, int port, String sniHostName, String trustorePath, char[] password) { ConfigurationBuilder clientBuilder = new ConfigurationBuilder(); clientBuilder = withIpAndPort(clientBuilder, ip, port); clientBuilder = withSni(clientBuilder, sniHostName, trustorePath, password); clientBuilder = withSingleConnection(clientBuilder); return new RemoteCacheManager(clientBuilder.build()); } public static RemoteCacheManager createWithSsl(InetAddress ip, int port, String trustorePath, char[] password) { ConfigurationBuilder clientBuilder = new ConfigurationBuilder(); clientBuilder = withIpAndPort(clientBuilder, ip, port); clientBuilder = withSsl(clientBuilder, trustorePath, password); clientBuilder = withSingleConnection(clientBuilder); return new RemoteCacheManager(clientBuilder.build()); } public static RemoteCacheManager createNoAuth(InetAddress ip, int port) { ConfigurationBuilder clientBuilder = new ConfigurationBuilder(); clientBuilder = withIpAndPort(clientBuilder, ip, port); clientBuilder = withSingleConnection(clientBuilder); return new RemoteCacheManager(clientBuilder.build()); } private static ConfigurationBuilder withIpAndPort(ConfigurationBuilder cb, InetAddress ip, int port) { cb.addServer() .host(ip.getHostAddress()) .port(port); return cb; } private static ConfigurationBuilder withSsl(ConfigurationBuilder cb, String trustorePath, char[] password) { cb.security() .ssl() .enabled(true) .trustStoreFileName(trustorePath) .trustStorePassword(password); return cb; } private static ConfigurationBuilder withSingleConnection(ConfigurationBuilder cb) { cb.maxRetries(0); return cb; } private static ConfigurationBuilder withSni(ConfigurationBuilder cb, String sniHostName, String trustorePath, char[] password) { cb = withSsl(cb, trustorePath, password); cb.security().ssl().sniHostName(sniHostName); return cb; } }
2,478
40.316667
136
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/utils/RestTestingUtil.java
package org.infinispan.server.router.utils; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.rest.RestServer; import org.infinispan.rest.configuration.RestServerConfigurationBuilder; import org.infinispan.server.core.DummyServerManagement; import org.infinispan.server.router.Router; public class RestTestingUtil { public static RestServerConfigurationBuilder createDefaultRestConfiguration() { RestServerConfigurationBuilder builder = new RestServerConfigurationBuilder(); builder.startTransport(false); return builder; } public static RestServer createDefaultRestServer(String ctx, String... definedCaches) { return createRest(ctx, createDefaultRestConfiguration(), new GlobalConfigurationBuilder(), new ConfigurationBuilder(), definedCaches); } public static RestServer createRest(String ctx, RestServerConfigurationBuilder configuration, GlobalConfigurationBuilder globalConfigurationBuilder, ConfigurationBuilder cacheConfigurationBuilder, String... definedCaches) { configuration.contextPath(ctx); RestServer nettyRestServer = new RestServer(); Configuration cacheConfiguration = cacheConfigurationBuilder.build(); DefaultCacheManager cacheManager = new DefaultCacheManager(globalConfigurationBuilder.build(), false); for (String cache : definedCaches) { cacheManager.defineConfiguration(cache, cacheConfiguration); } cacheManager.start(); nettyRestServer.setServerManagement(new DummyServerManagement(), true); nettyRestServer.start(configuration.build(), cacheManager); return nettyRestServer; } public static void killRouter(Router router) { if (router != null) { router.stop(); } } }
2,014
43.777778
227
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/routes/rest/RestServerRouteDestinationTest.java
package org.infinispan.server.router.routes.rest; import org.infinispan.rest.RestServer; import org.junit.Test; public class RestServerRouteDestinationTest { @Test(expected = NullPointerException.class) public void shouldValidateName() { new RestServerRouteDestination(null, new RestServer()); } @Test(expected = NullPointerException.class) public void shouldValidateRestResource() { new RestServerRouteDestination("test", null); } }
479
24.263158
63
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/routes/rest/RestRouteSourceTest.java
package org.infinispan.server.router.routes.rest; import org.junit.Test; public class RestRouteSourceTest { @Test(expected = IllegalArgumentException.class) public void shouldValidatePath() { new RestRouteSource(null).validate(); } @Test(expected = IllegalArgumentException.class) public void shouldValidateWithWhiteCharacters() { new RestRouteSource("12312 234").validate(); } @Test(expected = IllegalArgumentException.class) public void shouldValidateStartingSlash() { new RestRouteSource("/test").validate(); } @Test public void shouldPassOnCorrectPath() { new RestRouteSource("correctPath").validate(); } }
697
24.851852
54
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/routes/hotrod/SniNettyRouteSourceTest.java
package org.infinispan.server.router.routes.hotrod; import javax.net.ssl.SSLContext; import org.junit.Test; public class SniNettyRouteSourceTest { @Test(expected = IllegalArgumentException.class) public void shouldValidateSniHostName() throws Exception { new SniNettyRouteSource(null, SSLContext.getDefault()).validate(); } @Test(expected = IllegalArgumentException.class) public void shouldValidateSSLContext() throws Exception { new SniNettyRouteSource("test", null).validate(); } }
531
25.6
74
java
null
infinispan-main/server/router/src/test/java/org/infinispan/server/router/routes/hotrod/HotRodServerRouteDestinationTest.java
package org.infinispan.server.router.routes.hotrod; import org.infinispan.server.hotrod.HotRodServer; import org.junit.Test; public class HotRodServerRouteDestinationTest { @Test(expected = NullPointerException.class) public void shouldValidateName() { new HotRodServerRouteDestination(null, new HotRodServer()); } @Test(expected = NullPointerException.class) public void shouldValidateChannelInitializer() { new HotRodServerRouteDestination("test", null); } }
506
25.684211
67
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/Router.java
package org.infinispan.server.router; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.infinispan.server.router.configuration.RouterConfiguration; import org.infinispan.server.router.logging.RouterLogger; import org.infinispan.server.router.router.EndpointRouter; import org.infinispan.server.router.router.impl.hotrod.HotRodEndpointRouter; import org.infinispan.server.router.router.impl.rest.RestEndpointRouter; import org.infinispan.server.router.router.impl.singleport.SinglePortEndpointRouter; /** * The main entry point for the router. * * @author Sebastian Łaskawiec */ public class Router { private final RouterConfiguration routerConfiguration; private final Set<EndpointRouter> endpointRouters = new HashSet<>(); /** * Creates new {@link Router} based on {@link RouterConfiguration}. * * @param routerConfiguration {@link RouterConfiguration} object. */ public Router(RouterConfiguration routerConfiguration) { this.routerConfiguration = routerConfiguration; if (routerConfiguration.hotRodRouter() != null) { endpointRouters.add(new HotRodEndpointRouter(routerConfiguration.hotRodRouter())); } if (routerConfiguration.restRouter() != null) { endpointRouters.add(new RestEndpointRouter(routerConfiguration.restRouter())); } if (routerConfiguration.singlePortRouter() != null) { endpointRouters.add(new SinglePortEndpointRouter(routerConfiguration.singlePortRouter())); } } /** * Starts the router. */ public void start() { endpointRouters.forEach(r -> r.start(routerConfiguration.routingTable(), null)); RouterLogger.SERVER.printOutRoutingTable(routerConfiguration.routingTable()); } /** * Stops the router. */ public void stop() { endpointRouters.forEach(r -> r.stop()); } /** * Gets internal {@link EndpointRouter} implementation for given protocol. * * @param protocol Protocol for obtaining the router. * @return The {@link EndpointRouter} implementation. */ public Optional<EndpointRouter> getRouter(EndpointRouter.Protocol protocol) { return endpointRouters.stream().filter(r -> r.getProtocol() == protocol).findFirst(); } }
2,275
33.484848
99
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/RoutingTable.java
package org.infinispan.server.router; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.RouteDestination; import org.infinispan.server.router.routes.RouteSource; /** * A container for routing information. * * @author Sebastian Łaskawiec */ public class RoutingTable { private Set<Route<? extends RouteSource, ? extends RouteDestination>> routes = new HashSet<>(); /** * Creates new {@link RoutingTable}. * * @param routes A set of {@link Route}s for the routing table. */ public RoutingTable(Set<Route<? extends RouteSource, ? extends RouteDestination>> routes) { this.routes.addAll(routes); } /** * Returns the number of {@link Route}s present in the routing table. */ public int routesCount() { return routes.size(); } /** * Returns a stream of all {@link Route}s in the routing table. */ public Stream<Route<? extends RouteSource, ? extends RouteDestination>> streamRoutes() { return routes.stream(); } /** * Returns a {@link Stream} of {@link Route}s matching the initial criteria * * @param sourceType Class of the <code>Source</code> type. * @param destinationType Class of the <code>Desitnation</code> type. * @param <Source> Type of the {@link RouteSource} * @param <Destination> Type of the {@link RouteDestination} * @return */ @SuppressWarnings("unchecked") public <Source extends RouteSource, Destination extends RouteDestination> Stream<Route<Source, Destination>> streamRoutes(Class<Source> sourceType, Class<Destination> destinationType) { //Unfortunately there is no nice way to do a cast here, so we need to un-generify this. Stream unGenerifiedStream = routes.stream() .filter(r -> sourceType.isAssignableFrom(r.getRouteSource().getClass())) .filter(r -> destinationType.isAssignableFrom(r.getRouteDestination().getClass())); return unGenerifiedStream; } @Override public String toString() { return "RoutingTable{" + "routes=" + routes + '}'; } }
2,288
31.7
115
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/SinglePortRouterConfiguration.java
package org.infinispan.server.router.configuration; import org.infinispan.commons.configuration.ConfigurationFor; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.server.core.configuration.IpFilterConfiguration; import org.infinispan.server.core.configuration.NoAuthenticationConfiguration; import org.infinispan.server.core.configuration.ProtocolServerConfiguration; import org.infinispan.server.core.configuration.SslConfiguration; import org.infinispan.server.router.Router; import org.infinispan.server.router.router.impl.singleport.SinglePortEndpointRouter; /** * {@link Router}'s configuration for Single Port. * * @author Sebastian Łaskawiec */ @ConfigurationFor(SinglePortEndpointRouter.class) public class SinglePortRouterConfiguration extends ProtocolServerConfiguration<SinglePortRouterConfiguration, NoAuthenticationConfiguration> { public static AttributeSet attributeDefinitionSet() { return new AttributeSet(SinglePortRouterConfiguration.class, ProtocolServerConfiguration.attributeDefinitionSet()); } /** * Creates new configuration based on the IP address and port. */ public SinglePortRouterConfiguration(AttributeSet attributes, SslConfiguration ssl, IpFilterConfiguration ipRules) { super("endpoint", attributes, null, ssl, ipRules); } }
1,354
42.709677
142
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/RouterConfiguration.java
package org.infinispan.server.router.configuration; import org.infinispan.server.router.Router; import org.infinispan.server.router.RoutingTable; /** * Global {@link Router}'s configuration. * * @author Sebastian Łaskawiec */ public class RouterConfiguration { private final RoutingTable routingTable; private final HotRodRouterConfiguration hotRodRouterConfiguration; private final RestRouterConfiguration restRouterConfiguration; private final SinglePortRouterConfiguration singlePortRouterConfiguration; /** * Creates new configuration based on protocol configurations and the {@link RoutingTable}. * * @param routingTable The {@link RoutingTable} for supplying {@link org.infinispan.server.router.routes.Route}s. * @param hotRodRouterConfiguration Hot Rod Configuration. * @param restRouterConfiguration REST Configuration. * @param singlePortRouterConfiguration */ public RouterConfiguration(RoutingTable routingTable, HotRodRouterConfiguration hotRodRouterConfiguration, RestRouterConfiguration restRouterConfiguration, SinglePortRouterConfiguration singlePortRouterConfiguration) { this.routingTable = routingTable; this.hotRodRouterConfiguration = hotRodRouterConfiguration; this.restRouterConfiguration = restRouterConfiguration; this.singlePortRouterConfiguration = singlePortRouterConfiguration; } /** * Gets the {@link RoutingTable}. */ public RoutingTable routingTable() { return routingTable; } /** * Gets Hot Rod Configuration. */ public HotRodRouterConfiguration hotRodRouter() { return hotRodRouterConfiguration; } /** * Gets REST Configuration. */ public RestRouterConfiguration restRouter() { return restRouterConfiguration; } /** * Gets Single Port Configuration. */ public SinglePortRouterConfiguration singlePortRouter() { return singlePortRouterConfiguration; } }
2,029
32.278689
222
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/HotRodRouterConfiguration.java
package org.infinispan.server.router.configuration; import java.net.InetAddress; import org.infinispan.server.router.Router; /** * {@link Router}'s configuration for Hot Rod. * * @author Sebastian Łaskawiec */ public class HotRodRouterConfiguration extends AbstractRouterConfiguration { private final int sendBufferSize; private final int receiveBufferSize; private final boolean tcpKeepAlive; private final boolean tcpNoDelay; /** * Creates new configuration based on the IP address and port. * * @param ip The IP address used for binding. Can not be <code>null</code>. * @param port Port used for binding. Can be 0, in that case a random port is assigned. * @param tcpKeepAlive Keep alive TCP setting. * @param receiveBufferSize Receive buffer size. * @param sendBufferSize Send buffer size * @param tcpNoDelay TCP No Delay setting. */ public HotRodRouterConfiguration(InetAddress ip, int port, int sendBufferSize, int receiveBufferSize, boolean tcpKeepAlive, boolean tcpNoDelay) { super(ip, port); this.sendBufferSize = sendBufferSize; this.receiveBufferSize = receiveBufferSize; this.tcpKeepAlive = tcpKeepAlive; this.tcpNoDelay = tcpNoDelay; } /** * Returns TCP No Delay setting. */ public boolean tcpNoDelay() { return tcpNoDelay; } /** * Returns TCP Keep Alive setting. */ public boolean tcpKeepAlive() { return tcpKeepAlive; } /** * Returns Send buffer size. */ public int sendBufferSize() { return sendBufferSize; } /** * Returns Receive buffer size. */ public int receiveBufferSize() { return receiveBufferSize; } }
1,818
26.984615
149
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/AbstractRouterConfiguration.java
package org.infinispan.server.router.configuration; import java.net.InetAddress; abstract class AbstractRouterConfiguration { private final int port; private final InetAddress ip; protected AbstractRouterConfiguration(InetAddress ip, int port) { this.port = port; this.ip = ip; } public int getPort() { return port; } public InetAddress getIp() { return ip; } }
433
17.083333
69
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/RestRouterConfiguration.java
package org.infinispan.server.router.configuration; import java.net.InetAddress; import org.infinispan.server.router.Router; /** * {@link Router}'s configuration for REST. * * @author Sebastian Łaskawiec */ public class RestRouterConfiguration extends AbstractRouterConfiguration { /** * Creates new configuration based on the IP address and port. * * @param ip The IP address used for binding. Can not be <code>null</code>. * @param port Port used for binding. Can be 0, in that case a random port is assigned. */ public RestRouterConfiguration(InetAddress ip, int port) { super(ip, port); } }
650
26.125
91
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/builder/SinglePortRouterBuilder.java
package org.infinispan.server.router.configuration.builder; import java.util.Collections; import javax.net.ssl.SSLContext; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.server.core.configuration.IpFilterConfiguration; import org.infinispan.server.core.configuration.ProtocolServerConfiguration; import org.infinispan.server.core.configuration.SslConfigurationBuilder; import org.infinispan.server.router.configuration.HotRodRouterConfiguration; import org.infinispan.server.router.configuration.SinglePortRouterConfiguration; import org.infinispan.server.router.logging.RouterLogger; /** * Configuration builder for Single Port. * * @author Sebastian Łaskawiec */ public class SinglePortRouterBuilder extends AbstractRouterBuilder { private int sendBufferSize = 0; private int receiveBufferSize = 0; private String name = "single-port"; private SSLContext sslContext; /** * Creates new {@link SinglePortRouterBuilder}. * * @param parent Parent {@link ConfigurationBuilderParent} */ public SinglePortRouterBuilder(ConfigurationBuilderParent parent) { super(parent); } /** * Builds {@link HotRodRouterConfiguration}. */ public SinglePortRouterConfiguration build() { if (this.enabled) { try { validate(); } catch (Exception e) { throw RouterLogger.SERVER.configurationValidationError(e); } SslConfigurationBuilder sslConfigurationBuilder = new SslConfigurationBuilder(null); if (sslContext != null) { sslConfigurationBuilder.sslContext(sslContext).enable(); } AttributeSet attributes = SinglePortRouterConfiguration.attributeDefinitionSet(); attributes.attribute(ProtocolServerConfiguration.NAME).set(name); attributes.attribute(ProtocolServerConfiguration.HOST).set(ip.getHostName()); attributes.attribute(ProtocolServerConfiguration.PORT).set(port); attributes.attribute(ProtocolServerConfiguration.IDLE_TIMEOUT).set(100); attributes.attribute(ProtocolServerConfiguration.RECV_BUF_SIZE).set(receiveBufferSize); attributes.attribute(ProtocolServerConfiguration.SEND_BUF_SIZE).set(sendBufferSize); return new SinglePortRouterConfiguration(attributes.protect(), sslConfigurationBuilder.create(), new IpFilterConfiguration(Collections.emptyList())); } return null; } /** * Sets Send buffer size * * @param sendBufferSize Send buffer size, must be greater than 0. */ public SinglePortRouterBuilder sendBufferSize(int sendBufferSize) { this.sendBufferSize = sendBufferSize; return this; } /** * Sets Receive buffer size. * * @param receiveBufferSize Receive buffer size, must be greater than 0. */ public SinglePortRouterBuilder receiveBufferSize(int receiveBufferSize) { this.receiveBufferSize = receiveBufferSize; return this; } /** * Sets this server name. * * @param name The name of the server. */ public SinglePortRouterBuilder name(String name) { this.name = name; return this; } public SinglePortRouterBuilder sslContext(SSLContext sslContext) { this.sslContext = sslContext; return this; } @Override protected void validate() { super.validate(); if (receiveBufferSize < 0) { throw new IllegalArgumentException("Receive buffer size can not be negative"); } if (sendBufferSize < 0) { throw new IllegalArgumentException("Send buffer size can not be negative"); } } }
3,790
34.101852
161
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/builder/RoutingBuilder.java
package org.infinispan.server.router.configuration.builder; import java.lang.invoke.MethodHandles; import java.util.HashSet; import java.util.Set; import org.infinispan.commons.logging.LogFactory; import org.infinispan.server.router.RoutingTable; import org.infinispan.server.router.configuration.RouterConfiguration; import org.infinispan.server.router.logging.RouterLogger; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.RouteDestination; import org.infinispan.server.router.routes.RouteSource; /** * Builder for constructing a {@link RoutingTable}. * * @author Sebastian Łaskawiec */ public class RoutingBuilder implements ConfigurationBuilderParent { protected static final RouterLogger logger = LogFactory.getLog(MethodHandles.lookup().lookupClass(), RouterLogger.class); private final ConfigurationBuilderParent parent; private Set<Route<? extends RouteSource, ? extends RouteDestination>> routes = new HashSet<>(); /** * Creates new {@link RoutingBuilder}. * * @param parent Parent {@link RouterConfiguration}. */ public RoutingBuilder(ConfigurationBuilderParent parent) { this.parent = parent; } /** * Adds a {@link Route} to the {@link RoutingTable}. * * @param route {@link Route} to be added. * @param <Source> {@link RouteSource} type. * @param <Destination> {@link RouteDestination} type. * @return This builder. */ public <Source extends RouteSource, Destination extends RouteDestination> RoutingBuilder add(Route<Source, Destination> route) { routes.add(route); return this; } protected RoutingTable build() { try { routes.forEach(r -> r.validate()); } catch (Exception e) { throw logger.configurationValidationError(e); } return new RoutingTable(routes); } @Override public RoutingBuilder routing() { return parent.routing(); } @Override public HotRodRouterBuilder hotrod() { return parent.hotrod(); } @Override public RestRouterBuilder rest() { return parent.rest(); } @Override public SinglePortRouterBuilder singlePort() { return parent.singlePort(); } }
2,308
28.602564
132
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/builder/AbstractRouterBuilder.java
package org.infinispan.server.router.configuration.builder; import java.net.InetAddress; public abstract class AbstractRouterBuilder implements ConfigurationBuilderParent { protected final ConfigurationBuilderParent parent; protected int port; protected InetAddress ip; protected boolean enabled; protected AbstractRouterBuilder(ConfigurationBuilderParent parent) { this.parent = parent; } public AbstractRouterBuilder port(int port) { this.port = port; return this; } public AbstractRouterBuilder ip(InetAddress ip) { this.ip = ip; return this; } public AbstractRouterBuilder enabled(boolean enabled) { this.enabled = enabled; return this; } protected void validate() { if (this.enabled) { if (ip == null) { throw new IllegalArgumentException("IP can not be null"); } if (port < 0) { throw new IllegalArgumentException("Port can not be negative"); } } } @Override public RoutingBuilder routing() { return parent.routing(); } @Override public HotRodRouterBuilder hotrod() { return parent.hotrod(); } @Override public RestRouterBuilder rest() { return parent.rest(); } @Override public SinglePortRouterBuilder singlePort() { return parent.singlePort(); } }
1,455
22.868852
83
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/builder/HotRodRouterBuilder.java
package org.infinispan.server.router.configuration.builder; import org.infinispan.server.router.configuration.HotRodRouterConfiguration; import org.infinispan.server.router.logging.RouterLogger; /** * Configuration builder for Hot Rod. * * @author Sebastian Łaskawiec */ public class HotRodRouterBuilder extends AbstractRouterBuilder { private int sendBufferSize = 0; private int receiveBufferSize = 0; private boolean tcpKeepAlive = false; private boolean tcpNoDelay = true; /** * Creates new {@link HotRodRouterBuilder}. * * @param parent Parent {@link ConfigurationBuilderParent} */ public HotRodRouterBuilder(ConfigurationBuilderParent parent) { super(parent); } /** * Builds {@link HotRodRouterConfiguration}. */ public HotRodRouterConfiguration build() { if (this.enabled) { try { validate(); } catch (Exception e) { throw RouterLogger.SERVER.configurationValidationError(e); } return new HotRodRouterConfiguration(ip, port, sendBufferSize, receiveBufferSize, tcpKeepAlive, tcpNoDelay); } return null; } /** * Sets TCP No Delay. */ public HotRodRouterBuilder tcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; return this; } /** * Sets TCP Keep Alive */ public HotRodRouterBuilder tcpKeepAlive(boolean tcpKeepAlive) { this.tcpKeepAlive = tcpKeepAlive; return this; } /** * Sets Send buffer size * * @param sendBufferSize Send buffer size, must be greater than 0. */ public HotRodRouterBuilder sendBufferSize(int sendBufferSize) { this.sendBufferSize = sendBufferSize; return this; } /** * Sets Receive buffer size. * * @param receiveBufferSize Receive buffer size, must be greater than 0. */ public HotRodRouterBuilder receiveBufferSize(int receiveBufferSize) { this.receiveBufferSize = receiveBufferSize; return this; } @Override protected void validate() { super.validate(); if (receiveBufferSize < 0) { throw new IllegalArgumentException("Receive buffer size can not be negative"); } if (sendBufferSize < 0) { throw new IllegalArgumentException("Send buffer size can not be negative"); } } }
2,457
26.617978
120
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/builder/RestRouterBuilder.java
package org.infinispan.server.router.configuration.builder; import org.infinispan.server.router.configuration.RestRouterConfiguration; import org.infinispan.server.router.logging.RouterLogger; /** * Configuration builder for REST. * * @author Sebastian Łaskawiec */ public class RestRouterBuilder extends AbstractRouterBuilder { /** * Creates new {@link RestRouterConfiguration}. * * @param parent Parent {@link ConfigurationBuilderParent}. */ public RestRouterBuilder(ConfigurationBuilderParent parent) { super(parent); } /** * Builds {@link RestRouterConfiguration}. */ public RestRouterConfiguration build() { if (this.enabled) { try { validate(); } catch (Exception e) { throw RouterLogger.SERVER.configurationValidationError(e); } return new RestRouterConfiguration(ip, port); } return null; } }
975
25.378378
74
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/builder/RouterConfigurationBuilder.java
package org.infinispan.server.router.configuration.builder; import org.infinispan.server.router.configuration.RouterConfiguration; /** * Multi tenant router configuration builder. * * @author Sebastian Łaskawiec */ public class RouterConfigurationBuilder implements ConfigurationBuilderParent { private RoutingBuilder routingBuilder = new RoutingBuilder(this); private HotRodRouterBuilder hotRodRouterBuilder = new HotRodRouterBuilder(this); private RestRouterBuilder restRouterBuilder = new RestRouterBuilder(this); private SinglePortRouterBuilder singlePortRouterBuilder = new SinglePortRouterBuilder(this); @Override public RoutingBuilder routing() { return routingBuilder; } @Override public HotRodRouterBuilder hotrod() { hotRodRouterBuilder.enabled(true); return hotRodRouterBuilder; } @Override public RestRouterBuilder rest() { restRouterBuilder.enabled(true); return restRouterBuilder; } @Override public SinglePortRouterBuilder singlePort() { singlePortRouterBuilder.enabled(true); return singlePortRouterBuilder; } /** * Returns assembled configuration. */ public RouterConfiguration build() { return new RouterConfiguration(routingBuilder.build(), hotRodRouterBuilder.build(), restRouterBuilder.build(), singlePortRouterBuilder.build()); } }
1,416
29.148936
152
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/configuration/builder/ConfigurationBuilderParent.java
package org.infinispan.server.router.configuration.builder; /** * Router configuration builder. * * @author Sebastian Łaskawiec */ public interface ConfigurationBuilderParent { /** * Returns builder for Routing Table. */ RoutingBuilder routing(); /** * Returns builder for Hot Rod. */ HotRodRouterBuilder hotrod(); /** * Returns builder for REST. */ RestRouterBuilder rest(); /** * Returns builder for Single Port. */ SinglePortRouterBuilder singlePort(); }
539
17
59
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/router/EndpointRouter.java
package org.infinispan.server.router.router; import java.net.InetAddress; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.router.RoutingTable; /** * The EndpointRouter interface. Currently the EndpointRouter is coupled closely with the the {@link Protocol} it implements. * * @author Sebastian Łaskawiec */ public interface EndpointRouter { /** * The protocol the router implements. */ enum Protocol { HOT_ROD, SINGLE_PORT, REST } /** * Starts the {@link EndpointRouter}. * * @param routingTable {@link RoutingTable} for supplying {@link org.infinispan.server.router.routes.Route}s. */ void start(RoutingTable routingTable, EmbeddedCacheManager cm); /** * Stops the {@link EndpointRouter}. */ void stop(); /** * Gets the {@link EndpointRouter}'s host. */ String getHost(); /** * Gets the {@link EndpointRouter}'s IP address. */ InetAddress getIp(); /** * Gets the {@link EndpointRouter}'s port. */ Integer getPort(); /** * Gets {@link Protocol} implemented by this {@link EndpointRouter}. */ Protocol getProtocol(); }
1,214
21.090909
125
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/router/impl/rest/RestEndpointRouter.java
package org.infinispan.server.router.router.impl.rest; import java.net.InetAddress; import java.net.InetSocketAddress; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.router.RoutingTable; import org.infinispan.server.router.configuration.RestRouterConfiguration; import org.infinispan.server.router.logging.RouterLogger; import org.infinispan.server.router.router.EndpointRouter; import org.infinispan.server.router.router.impl.rest.handlers.ChannelInboundHandlerDelegatorInitializer; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.Future; public class RestEndpointRouter implements EndpointRouter { private static final String THREAD_NAME_PREFIX = "EndpointRouter"; private final NioEventLoopGroup masterGroup = new NioEventLoopGroup(1, new DefaultThreadFactory(THREAD_NAME_PREFIX + "-ServerMaster")); private final NioEventLoopGroup workerGroup = new NioEventLoopGroup(0, new DefaultThreadFactory(THREAD_NAME_PREFIX + "-ServerWorker")); private final RestRouterConfiguration configuration; private Integer port = null; private InetAddress ip = null; public RestEndpointRouter(RestRouterConfiguration configuration) { this.configuration = configuration; } @Override public void start(RoutingTable routingTable, EmbeddedCacheManager ecm) { try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(masterGroup, workerGroup) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childHandler(new ChannelInboundHandlerDelegatorInitializer(routingTable)) .channel(NioServerSocketChannel.class); InetAddress ip = configuration.getIp(); int port = configuration.getPort(); Channel channel = bootstrap.bind(ip, port).sync().channel(); InetSocketAddress localAddress = (InetSocketAddress) channel.localAddress(); this.port = localAddress.getPort(); this.ip = localAddress.getAddress(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { throw RouterLogger.SERVER.restRouterStartFailed(e); } RouterLogger.SERVER.debugf("REST EndpointRouter listening on %s:%d", ip, port); } @Override public void stop() { Future<?> masterGroupShutdown = masterGroup.shutdownGracefully(); Future<?> workerGroupShutdown = workerGroup.shutdownGracefully(); try { masterGroupShutdown.get(); workerGroupShutdown.get(); } catch (Exception e) { RouterLogger.SERVER.errorWhileShuttingDown(e); } port = null; ip = null; } @Override public String getHost() { return ip.getHostAddress(); } @Override public InetAddress getIp() { return ip; } @Override public Integer getPort() { return port; } @Override public Protocol getProtocol() { return Protocol.REST; } }
3,299
34.106383
138
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/router/impl/rest/handlers/ChannelInboundHandlerDelegatorInitializer.java
package org.infinispan.server.router.router.impl.rest.handlers; import org.infinispan.server.router.RoutingTable; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; /** * Initializer for REST Handlers. * * @author Sebastian Łaskawiec */ public class ChannelInboundHandlerDelegatorInitializer extends ChannelInitializer<Channel> { private final RoutingTable routingTable; public ChannelInboundHandlerDelegatorInitializer(RoutingTable routingTable) { this.routingTable = routingTable; } @Override protected void initChannel(Channel channel) { channel.pipeline().addLast(new HttpRequestDecoder()); channel.pipeline().addLast(new HttpResponseEncoder()); channel.pipeline().addLast(new HttpObjectAggregator(1024*100)); channel.pipeline().addLast(new ChannelInboundHandlerDelegator(routingTable)); } }
1,048
31.78125
92
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/router/impl/rest/handlers/ChannelInboundHandlerDelegator.java
package org.infinispan.server.router.router.impl.rest.handlers; import java.util.Optional; import org.infinispan.rest.RestRequestHandler; import org.infinispan.server.router.RoutingTable; import org.infinispan.server.router.logging.RouterLogger; import org.infinispan.server.router.routes.PrefixedRouteSource; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.rest.RestServerRouteDestination; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpRequest; /** * Handler responsible for dispatching requests into proper REST handlers. * * @author Sebastian Łaskawiec */ public class ChannelInboundHandlerDelegator extends SimpleChannelInboundHandler<FullHttpRequest> { private final RoutingTable routingTable; public ChannelInboundHandlerDelegator(RoutingTable routingTable) { this.routingTable = routingTable; } @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) { String[] uriSplitted = msg.uri().split("/"); //we are paring something like this: /rest/<context or prefix>/... if (uriSplitted.length < 2) { throw RouterLogger.SERVER.noRouteFound(); } String context = uriSplitted[2]; RouterLogger.SERVER.debugf("Decoded context %s", context); Optional<Route<PrefixedRouteSource, RestServerRouteDestination>> route = routingTable.streamRoutes(PrefixedRouteSource.class, RestServerRouteDestination.class) .filter(r -> r.getRouteSource().getRoutePrefix().equals(context)) .findAny(); RestServerRouteDestination routeDestination = route.orElseThrow(RouterLogger.SERVER::noRouteFound).getRouteDestination(); RestRequestHandler restHandler = (RestRequestHandler) routeDestination.getProtocolServer().getRestChannelInitializer().getRestHandler(); //before passing it to REST Handler, we need to replace path. The handler should not be aware of additional context //used for multi-tenant prefixes StringBuilder uriWithoutMultiTenantPrefix = new StringBuilder(); for (int i = 0; i < uriSplitted.length; ++i) { if (i == 1) { //this is the main uri prefix - "rest", we want to get rid of that. continue; } uriWithoutMultiTenantPrefix.append(uriSplitted[i]); if (i < uriSplitted.length - 1) { uriWithoutMultiTenantPrefix.append("/"); } } msg.setUri(uriWithoutMultiTenantPrefix.toString()); restHandler.channelRead0(ctx, msg); } }
2,633
40.809524
165
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/router/impl/singleport/SinglePortEndpointRouter.java
package org.infinispan.server.router.router.impl.singleport; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.RestServer; import org.infinispan.security.actions.SecurityActions; import org.infinispan.server.core.AbstractProtocolServer; import org.infinispan.server.core.ProtocolServer; import org.infinispan.server.core.transport.NettyInitializers; import org.infinispan.server.core.transport.NettyTransport; import org.infinispan.server.router.RoutingTable; import org.infinispan.server.router.configuration.SinglePortRouterConfiguration; import org.infinispan.server.router.logging.RouterLogger; import org.infinispan.server.router.router.EndpointRouter; import org.infinispan.server.router.routes.hotrod.HotRodServerRouteDestination; import org.infinispan.server.router.routes.memcached.MemcachedServerRouteDestination; import org.infinispan.server.router.routes.resp.RespServerRouteDestination; import org.infinispan.server.router.routes.rest.RestServerRouteDestination; import org.infinispan.server.router.routes.singleport.SinglePortRouteSource; import io.netty.channel.Channel; import io.netty.channel.ChannelInboundHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOutboundHandler; import io.netty.channel.group.ChannelMatcher; public class SinglePortEndpointRouter extends AbstractProtocolServer<SinglePortRouterConfiguration> implements EndpointRouter { private RoutingTable routingTable; public SinglePortEndpointRouter(SinglePortRouterConfiguration configuration) { super("SinglePort"); this.configuration = configuration; } @Override public void start(RoutingTable routingTable, EmbeddedCacheManager ecm) { this.routingTable = routingTable; this.routingTable.streamRoutes().forEach(r -> r.getRouteDestination().getProtocolServer().setEnclosingProtocolServer(this)); this.cacheManager = ecm; InetSocketAddress address = new InetSocketAddress(configuration.host(), configuration.port()); transport = new NettyTransport(address, configuration, getQualifiedName(), cacheManager); transport.initializeHandler(getInitializer()); if (cacheManager != null) { BasicComponentRegistry bcr = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(BasicComponentRegistry.class); bcr.replaceComponent(getQualifiedName(), this, false); } registerServerMBeans(); try { transport.start(); } catch (Throwable re) { try { unregisterServerMBeans(); } catch (Exception e) { re.addSuppressed(e); } throw re; } registerMetrics(); RouterLogger.SERVER.debugf("REST EndpointRouter listening on %s:%d", transport.getHostName(), transport.getPort()); } @Override public void stop() { super.stop(); } @Override public InetAddress getIp() { try { return InetAddress.getByName(getHost()); } catch (UnknownHostException e) { throw new IllegalStateException("Unknown host", e); } } @Override public ChannelOutboundHandler getEncoder() { return null; } @Override public ChannelInboundHandler getDecoder() { return null; } @Override public ChannelMatcher getChannelMatcher() { return channel -> true; } @Override public void installDetector(Channel ch) { // NOOP } @Override public ChannelInitializer<Channel> getInitializer() { Map<String, ProtocolServer<?>> upgradeServers = new HashMap<>(); RestServer restServer = routingTable.streamRoutes(SinglePortRouteSource.class, RestServerRouteDestination.class) .findFirst() .map(r -> r.getRouteDestination().getProtocolServer()) .orElseThrow(() -> new IllegalStateException("There must be a REST route!")); routingTable.streamRoutes(SinglePortRouteSource.class, HotRodServerRouteDestination.class) .findFirst() .ifPresent(r -> upgradeServers.put("HR", r.getRouteDestination().getProtocolServer())); routingTable.streamRoutes(SinglePortRouteSource.class, RespServerRouteDestination.class) .findFirst() .ifPresent(r -> upgradeServers.put("RP", r.getRouteDestination().getProtocolServer())); routingTable.streamRoutes(SinglePortRouteSource.class, MemcachedServerRouteDestination.class) .findFirst() .ifPresent(r -> upgradeServers.put("MB", r.getRouteDestination().getProtocolServer())); SinglePortChannelInitializer restChannelInitializer = new SinglePortChannelInitializer(this, transport, restServer, upgradeServers); return new NettyInitializers(restChannelInitializer); } @Override public Protocol getProtocol() { return Protocol.SINGLE_PORT; } }
5,079
36.62963
138
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/router/impl/singleport/SinglePortChannelInitializer.java
package org.infinispan.server.router.router.impl.singleport; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.infinispan.rest.ALPNHandler; import org.infinispan.rest.RestServer; import org.infinispan.server.core.ProtocolServer; import org.infinispan.server.core.transport.NettyChannelInitializer; import org.infinispan.server.core.transport.NettyTransport; import org.infinispan.server.router.configuration.SinglePortRouterConfiguration; import io.netty.channel.Channel; import io.netty.handler.ssl.ApplicationProtocolConfig; import io.netty.handler.ssl.ApplicationProtocolNames; /** * Netty pipeline initializer for Single Port * * @author Sebastian Łaskawiec */ class SinglePortChannelInitializer extends NettyChannelInitializer<SinglePortRouterConfiguration> { private final RestServer restServer; private final Map<String, ProtocolServer<?>> upgradeServers; public SinglePortChannelInitializer(SinglePortEndpointRouter server, NettyTransport transport, RestServer restServer, Map<String, ProtocolServer<?>> upgradeServers) { super(server, transport, null, null); this.restServer = restServer; this.upgradeServers = upgradeServers; } @Override public void initializeChannel(Channel ch) throws Exception { super.initializeChannel(ch); for(ProtocolServer<?> ps : upgradeServers.values()) { ps.installDetector(ch); } if (server.getConfiguration().ssl().enabled()) { ch.pipeline().addLast(new ALPNHandler(restServer)); } else { ALPNHandler.configurePipeline(ch.pipeline(), ApplicationProtocolNames.HTTP_1_1, restServer, upgradeServers); } } @Override protected ApplicationProtocolConfig getAlpnConfiguration() { if (server.getConfiguration().ssl().enabled()) { List<String> supportedProtocols = new ArrayList<>(); supportedProtocols.add(ApplicationProtocolNames.HTTP_2); supportedProtocols.add(ApplicationProtocolNames.HTTP_1_1); supportedProtocols.addAll(upgradeServers.keySet()); return new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, supportedProtocols); } return null; } }
2,613
38.014925
169
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/router/impl/hotrod/HotRodEndpointRouter.java
package org.infinispan.server.router.router.impl.hotrod; import java.net.InetAddress; import java.net.InetSocketAddress; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.router.RoutingTable; import org.infinispan.server.router.configuration.HotRodRouterConfiguration; import org.infinispan.server.router.logging.RouterLogger; import org.infinispan.server.router.router.EndpointRouter; import org.infinispan.server.router.router.impl.hotrod.handlers.SniHandlerInitializer; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.Future; public class HotRodEndpointRouter implements EndpointRouter { private static final String THREAD_NAME_PREFIX = "EndpointRouter"; private final NioEventLoopGroup masterGroup = new NioEventLoopGroup(1, new DefaultThreadFactory(THREAD_NAME_PREFIX + "-ServerMaster")); private final NioEventLoopGroup workerGroup = new NioEventLoopGroup(0, new DefaultThreadFactory(THREAD_NAME_PREFIX + "-ServerWorker")); private final HotRodRouterConfiguration configuration; private Integer port = null; private InetAddress ip = null; public HotRodEndpointRouter(HotRodRouterConfiguration configuration) { this.configuration = configuration; } @Override public void start(RoutingTable routingTable, EmbeddedCacheManager ecm) { try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(masterGroup, workerGroup) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.TCP_NODELAY, configuration.tcpNoDelay()) .childOption(ChannelOption.SO_KEEPALIVE, configuration.tcpKeepAlive()) .childHandler(new SniHandlerInitializer(routingTable)) .channel(NioServerSocketChannel.class); if (configuration.sendBufferSize() > 0) bootstrap.childOption(ChannelOption.SO_SNDBUF, configuration.sendBufferSize()); if (configuration.receiveBufferSize() > 0) bootstrap.childOption(ChannelOption.SO_RCVBUF, configuration.receiveBufferSize()); InetAddress ip = configuration.getIp(); int port = configuration.getPort(); Channel channel = bootstrap.bind(ip, port).sync().channel(); InetSocketAddress localAddress = (InetSocketAddress) channel.localAddress(); this.port = localAddress.getPort(); this.ip = localAddress.getAddress(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { throw RouterLogger.SERVER.hotrodRouterStartFailed(e); } RouterLogger.SERVER.debugf("Hot Rod EndpointRouter listening on %s:%d", ip, port); } @Override public void stop() { Future<?> masterGroupShutdown = masterGroup.shutdownGracefully(); Future<?> workerGroupShutdown = workerGroup.shutdownGracefully(); try { masterGroupShutdown.get(); workerGroupShutdown.get(); } catch (Exception e) { RouterLogger.SERVER.errorWhileShuttingDown(e); } port = null; ip = null; } @Override public String getHost() { return ip.getHostAddress(); } @Override public InetAddress getIp() { return ip; } @Override public Integer getPort() { return port; } @Override public Protocol getProtocol() { return Protocol.HOT_ROD; } }
3,738
36.39
138
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/router/impl/hotrod/handlers/SniRouteHandler.java
package org.infinispan.server.router.router.impl.hotrod.handlers; import java.util.List; import java.util.Optional; import org.infinispan.server.router.RoutingTable; import org.infinispan.server.router.logging.RouterLogger; import org.infinispan.server.router.routes.Route; import org.infinispan.server.router.routes.SniRouteSource; import org.infinispan.server.router.routes.hotrod.HotRodServerRouteDestination; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.handler.ssl.SniHandler; import io.netty.handler.ssl.SslContext; import io.netty.util.DomainNameMapping; /** * Handler responsible for routing requests to proper backend based on SNI Host Name. * * @author Sebastian Łaskawiec */ public class SniRouteHandler extends SniHandler { private final RoutingTable routingTable; /** * Creates new {@link SniRouteHandler} based on SNI Domain mapping and the {@link RoutingTable}. * * @param mapping SNI Host Name mapping. * @param routingTable The {@link RoutingTable} for supplying the {@link Route}s. */ public SniRouteHandler(DomainNameMapping<? extends SslContext> mapping, RoutingTable routingTable) { super(mapping); this.routingTable = routingTable; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { super.decode(ctx, in, out); if (isHandShaked()) { // At this point Netty has replaced SNIHandler (formally this) with SSLHandler in the pipeline. // Now we need to add other handlers at the tail of the queue RouterLogger.SERVER.debugf("Handshaked with hostname %s", hostname()); Optional<Route<SniRouteSource, HotRodServerRouteDestination>> route = routingTable.streamRoutes(SniRouteSource.class, HotRodServerRouteDestination.class) .filter(r -> r.getRouteSource().getSniHostName().equals(this.hostname())) .findAny(); HotRodServerRouteDestination routeDestination = route.orElseThrow(() -> RouterLogger.SERVER.noRouteFound()).getRouteDestination(); ChannelInitializer<Channel> channelInitializer = routeDestination.getProtocolServer().getInitializer(); ctx.pipeline().addLast(channelInitializer); RouterLogger.SERVER.debug("Replaced with route destination's handlers"); } } /** * Return <code>true</code> if handshake was successful. */ public boolean isHandShaked() { return this.hostname() != null; } }
2,675
39.545455
165
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/router/impl/hotrod/handlers/SniHandlerInitializer.java
package org.infinispan.server.router.router.impl.hotrod.handlers; import java.util.Optional; import org.infinispan.server.router.RoutingTable; import org.infinispan.server.router.logging.RouterLogger; import org.infinispan.server.router.router.impl.hotrod.handlers.util.SslUtils; import org.infinispan.server.router.routes.RouteDestination; import org.infinispan.server.router.routes.SniRouteSource; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.handler.ssl.SslContext; import io.netty.util.DomainNameMapping; import io.netty.util.DomainNameMappingBuilder; /** * Initializer for SNI Handlers. * * @author Sebastian Łaskawiec */ public class SniHandlerInitializer extends ChannelInitializer<Channel> { private final RoutingTable routingTable; /** * Creates new {@link SniHandlerInitializer} based on the routing table. * * @param routingTable {@link RoutingTable} for supplying the {@link org.infinispan.server.router.routes.Route}s. */ public SniHandlerInitializer(RoutingTable routingTable) { this.routingTable = routingTable; } @Override protected void initChannel(Channel channel) { SslContext defaultContext = SslUtils.INSTANCE.toNettySslContext(Optional.empty()); DomainNameMappingBuilder<SslContext> domainMappingBuilder = new DomainNameMappingBuilder<>(defaultContext); routingTable.streamRoutes(SniRouteSource.class, RouteDestination.class) .map(r -> r.getRouteSource()) .forEach(r -> domainMappingBuilder.add(r.getSniHostName(), SslUtils.INSTANCE.toNettySslContext(Optional.of(r.getSslContext())))); DomainNameMapping<SslContext> domainNameMapping = domainMappingBuilder.build(); RouterLogger.SERVER.debugf("Using SNI Handler with domain mapping %s", domainNameMapping); channel.pipeline().addLast(new SniRouteHandler(domainNameMapping, routingTable)); } }
1,964
38.3
145
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/router/impl/hotrod/handlers/util/SslUtils.java
package org.infinispan.server.router.router.impl.hotrod.handlers.util; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Optional; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import org.infinispan.commons.util.SslContextFactory; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.IdentityCipherSuiteFilter; import io.netty.handler.ssl.JdkSslContext; import io.netty.handler.ssl.SslContext; /** * A simple utility class for managing SSL Contexts * * @author Sebastian Łaskawiec */ public enum SslUtils { INSTANCE; /** * Creates Netty's {@link SslContext} based on optional standard JDK's {@link SSLContext}. If {@link * Optional#empty()} is passed as an argument, this method will return the default {@link SslContext}. * * @param context Optional {@link SSLContext}. * @return Netty's {@link SslContext}. */ public SslContext toNettySslContext(Optional<SSLContext> context) { try { SSLContext jdkContext = context.orElse(SSLContext.getDefault()); SSLEngine engine = SslContextFactory.getEngine(jdkContext, false, false); String[] ciphers = engine.getEnabledCipherSuites(); return new JdkSslContext(jdkContext, false, Arrays.asList(ciphers), IdentityCipherSuiteFilter.INSTANCE, null, ClientAuth.OPTIONAL, null, false); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } }
1,516
34.27907
156
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/logging/RouterLogger.java
package org.infinispan.server.router.logging; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.INFO; import org.infinispan.server.router.RoutingTable; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * Log abstraction for the Hot Rod server module. For this module, message ids ranging from 14000 to 15000 inclusively * have been reserved. * * @author Sebastian Łaskawiec */ @MessageLogger(projectCode = "ISPN") public interface RouterLogger extends BasicLogger { RouterLogger SERVER = Logger.getMessageLogger(RouterLogger.class, org.infinispan.util.logging.Log.LOG_ROOT + "SERVER"); @Message(value = "Could not find matching route", id = 14002) IllegalArgumentException noRouteFound(); @LogMessage(level = INFO) @Message(value = "Routing table: %s", id = 14005) void printOutRoutingTable(RoutingTable routingTable); @Message(value = "Configuration validation error", id = 14007) IllegalStateException configurationValidationError(@Cause Exception e); @Message(value = "Unable to start HotRod router", id = 14008) IllegalStateException hotrodRouterStartFailed(@Cause Exception e); @Message(value = "Unable to start REST router", id = 14009) IllegalStateException restRouterStartFailed(@Cause Exception e); @LogMessage(level = ERROR) @Message(value = "Error while shutting down the router", id = 14010) void errorWhileShuttingDown(@Cause Exception e); }
1,692
37.477273
123
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/PrefixedRouteSource.java
package org.infinispan.server.router.routes; public interface PrefixedRouteSource extends RouteSource { String getRoutePrefix(); }
136
21.833333
58
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/RouteSource.java
package org.infinispan.server.router.routes; public interface RouteSource { default void validate() { } }
116
13.625
44
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/SniRouteSource.java
package org.infinispan.server.router.routes; import javax.net.ssl.SSLContext; public interface SniRouteSource extends RouteSource { SSLContext getSslContext(); String getSniHostName(); }
200
15.75
53
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/RouteDestination.java
package org.infinispan.server.router.routes; import java.util.Objects; import org.infinispan.server.core.ProtocolServer; public abstract class RouteDestination<T extends ProtocolServer> { private final String name; private final T server; protected RouteDestination(String name, T server) { this.name = Objects.requireNonNull(name); this.server = Objects.requireNonNull(server); } public String getName() { return name; } public T getProtocolServer() { return server; } @Override public String toString() { return getClass().getSimpleName() + "name='" + name + "\'}"; } }
663
21.896552
68
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/Route.java
package org.infinispan.server.router.routes; public class Route<Source extends RouteSource, Destination extends RouteDestination> { private final Source routeSource; private final Destination routeDestination; public Route(Source routeSource, Destination routeDestination) { this.routeSource = routeSource; this.routeDestination = routeDestination; } public Destination getRouteDestination() { return routeDestination; } public Source getRouteSource() { return routeSource; } @Override public String toString() { return "Route{" + "routeSource=" + routeSource + ", routeDestination=" + routeDestination + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Route route = (Route) o; if (!getRouteSource().equals(route.getRouteSource())) return false; if (!routeDestination.equals(route.routeDestination)) return false; return true; } @Override public int hashCode() { int result = getRouteSource().hashCode(); result = 31 * result + routeDestination.hashCode(); return result; } public void validate() { } }
1,342
24.339623
86
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/rest/RestServerRouteDestination.java
package org.infinispan.server.router.routes.rest; import org.infinispan.rest.RestServer; import org.infinispan.server.router.routes.RouteDestination; public class RestServerRouteDestination extends RouteDestination<RestServer> { public RestServerRouteDestination(String name, RestServer restServer) { super(name, restServer); } }
349
28.166667
78
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/rest/RestRouteSource.java
package org.infinispan.server.router.routes.rest; import org.infinispan.server.router.routes.PrefixedRouteSource; public class RestRouteSource implements PrefixedRouteSource { private final String pathPrefix; public RestRouteSource(String pathPrefix) { this.pathPrefix = pathPrefix; } @Override public String getRoutePrefix() { return pathPrefix; } @Override public String toString() { return "RestRouteSource{" + "pathPrefix='" + pathPrefix + '\'' + '}'; } @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } }
752
22.53125
68
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/singleport/SinglePortRouteSource.java
package org.infinispan.server.router.routes.singleport; import org.infinispan.server.router.routes.RouteSource; /** * A source route for Single Port. * * @author Sebastian Łaskawiec */ public class SinglePortRouteSource implements RouteSource { }
253
20.166667
59
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/hotrod/HotRodServerRouteDestination.java
package org.infinispan.server.router.routes.hotrod; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.router.routes.RouteDestination; public class HotRodServerRouteDestination extends RouteDestination<HotRodServer> { public HotRodServerRouteDestination(String name, HotRodServer hotRodServer) { super(name, hotRodServer); } }
370
29.916667
82
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/hotrod/SniNettyRouteSource.java
package org.infinispan.server.router.routes.hotrod; import java.util.Optional; import javax.net.ssl.SSLContext; import org.infinispan.commons.util.SslContextFactory; import org.infinispan.server.router.router.impl.hotrod.handlers.util.SslUtils; import org.infinispan.server.router.routes.SniRouteSource; import io.netty.handler.ssl.SslContext; public class SniNettyRouteSource implements SniRouteSource { private final SslContext nettyContext; private final SSLContext jdkContext; private final String sniHostName; public SniNettyRouteSource(String sniHostName, SSLContext sslContext) { this.sniHostName = sniHostName; this.jdkContext = sslContext; nettyContext = SslUtils.INSTANCE.toNettySslContext(Optional.ofNullable(jdkContext)); } public SniNettyRouteSource(String sniHostName, String keyStoreFileName, char[] keyStorePassword) { this(sniHostName, new SslContextFactory().keyStoreFileName(keyStoreFileName).keyStorePassword(keyStorePassword).getContext()); } @Override public SSLContext getSslContext() { return jdkContext; } @Override public String getSniHostName() { return sniHostName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SniNettyRouteSource that = (SniNettyRouteSource) o; if (!getSniHostName().equals(that.getSniHostName())) return false; return true; } @Override public int hashCode() { return getSniHostName().hashCode(); } @Override public String toString() { return "SniNettyRouteSource{" + "sniHostName='" + sniHostName + '\'' + '}'; } @Override public void validate() { if (sniHostName == null || "".equals(sniHostName)) { throw new IllegalArgumentException("SNI Host name can not be null"); } if (jdkContext == null) { throw new IllegalArgumentException("JDK SSL Context must not be null"); } } }
2,047
27.054795
132
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/memcached/MemcachedServerRouteDestination.java
package org.infinispan.server.router.routes.memcached; import org.infinispan.server.memcached.MemcachedServer; import org.infinispan.server.router.routes.RouteDestination; public class MemcachedServerRouteDestination extends RouteDestination<MemcachedServer> { public MemcachedServerRouteDestination(String name, MemcachedServer memcachedServer) { super(name, memcachedServer); } }
396
35.090909
89
java
null
infinispan-main/server/router/src/main/java/org/infinispan/server/router/routes/resp/RespServerRouteDestination.java
package org.infinispan.server.router.routes.resp; import org.infinispan.server.resp.RespServer; import org.infinispan.server.router.routes.RouteDestination; public class RespServerRouteDestination extends RouteDestination<RespServer> { public RespServerRouteDestination(String name, RespServer respServer) { super(name, respServer); } }
352
28.416667
78
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/VariableLengthTest.java
package org.infinispan.server.core; import static org.infinispan.server.core.transport.ExtendedByteBuf.readUnsignedInt; import static org.infinispan.server.core.transport.ExtendedByteBuf.readUnsignedLong; import static org.infinispan.server.core.transport.ExtendedByteBuf.writeUnsignedInt; import static org.infinispan.server.core.transport.ExtendedByteBuf.writeUnsignedLong; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.commons.util.Util; import org.testng.annotations.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; /** * Variable length number test. * * @author Galder Zamarreño * @since 4.1 */ @Test(groups = "functional", testName = "server.hotrod.VariableLengthTest") public class VariableLengthTest { public void test2pow7minus1() { writeReadInt(127, 1); } public void test2pow7() { writeReadInt(128, 2); } public void test2pow14minus1() { writeReadInt(16383, 2); } public void test2pow14() { writeReadInt(16384, 3); } public void test2pow21minus1() { writeReadInt(2097151, 3); } public void test2pow21() { writeReadInt(2097152, 4); } public void test2pow28minus1() { writeReadInt(268435455, 4); } public void test2pow28() { writeReadInt(268435456, 5); } public void test2pow35minus1() { writeReadLong(34359738367L, 5); } public void test2pow35() { writeReadLong(34359738368L, 6); } public void test2pow42minus1() { writeReadLong(4398046511103L, 6); } public void test2pow42() { writeReadLong(4398046511104L, 7); } public void test2pow49minus1() { writeReadLong(562949953421311L, 7); } public void test2pow49() { writeReadLong(562949953421312L, 8); } public void test2pow56minus1() { writeReadLong(72057594037927935L, 8); } public void test2pow56() { writeReadLong(72057594037927936L, 9); } public void test2pow63minus1() { writeReadLong(9223372036854775807L, 9); } @Test(expectedExceptions = IllegalStateException.class) public void testTooLongInt() { ByteBuf buffer = Unpooled.directBuffer(1024); assert(buffer.writerIndex() == 0); writeUnsignedLong(9223372036854775807L, buffer); readUnsignedInt(buffer); buffer.release(); } @Test(groups = "unstable") public void testPrintHexadecimalVint() { ByteBuf buffer = Unpooled.directBuffer(1024); assert(buffer.writerIndex() == 0); writeUnsignedLong(512, buffer); System.out.println(Util.hexDump(buffer.nioBuffer())); System.out.println(); buffer.release(); } // public void test2pow63() { // writeReadLong(9223372036854775808L, 10) // } private void writeReadInt(int num, int expected) { ByteBuf buffer = Unpooled.directBuffer(1024); assert(buffer.writerIndex() == 0); writeUnsignedInt(num, buffer); assertEquals(buffer.writerIndex(), expected); assertEquals(readUnsignedInt(buffer), num); buffer.release(); } private void writeReadLong(long num, int expected) { ByteBuf buffer = Unpooled.directBuffer(1024); assert(buffer.writerIndex() == 0); writeUnsignedLong(num, buffer); assertEquals(buffer.writerIndex(), expected); assertEquals(readUnsignedLong(buffer), num); buffer.release(); } }
3,406
24.425373
85
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/DummyServerManagement.java
package org.infinispan.server.core; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.security.Principal; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import javax.sql.DataSource; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.tasks.TaskManager; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 13.0 **/ public class DummyServerManagement implements ServerManagement { private DefaultCacheManager defaultCacheManager; private Map<String, ProtocolServer> protocolServers; private ServerStateManager serverStateManager; public DummyServerManagement() { } public DummyServerManagement(EmbeddedCacheManager defaultCacheManager, Map<String, ProtocolServer> protocolServers) { this.defaultCacheManager = (DefaultCacheManager) defaultCacheManager; this.protocolServers = protocolServers; serverStateManager = new DummyServerStateManager(); } @Override public ComponentStatus getStatus() { return ComponentStatus.RUNNING; } @Override public void serializeConfiguration(ConfigurationWriter writer) { } @Override public void serverStop(List<String> servers) { } @Override public void clusterStop() { } @Override public void containerStop() { } @Override public DefaultCacheManager getCacheManager() { return defaultCacheManager; } @Override public ServerStateManager getServerStateManager() { return serverStateManager; } @Override public Map<String, String> getLoginConfiguration(ProtocolServer protocolServer) { return Collections.emptyMap(); } @Override public Map<String, ProtocolServer> getProtocolServers() { return protocolServers; } @Override public TaskManager getTaskManager() { return null; } @Override public CompletionStage<Path> getServerReport() { try { return CompletableFuture.completedFuture(Files.createTempFile("report", ".gz")); } catch (IOException e) { throw new RuntimeException(e); } } @Override public BackupManager getBackupManager() { return null; } @Override public Map<String, DataSource> getDataSources() { return null; } @Override public Path getServerDataPath() { return null; } @Override public Map<String, List<Principal>> getPrincipalList() { return Collections.emptyMap(); } @Override public CompletionStage<Void> flushSecurityCaches() { return CompletableFutures.completedNull(); } }
3,008
22.880952
89
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/DummyServerStateManager.java
package org.infinispan.server.core; import java.util.Collection; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.server.core.transport.IpSubnetFilterRule; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.1 **/ public class DummyServerStateManager implements ServerStateManager { Set<String> ignoredCaches = ConcurrentHashMap.newKeySet(); @Override public CompletableFuture<Void> unignoreCache(String cacheName) { ignoredCaches.remove(cacheName); return CompletableFuture.completedFuture(null); } @Override public CompletableFuture<Void> ignoreCache(String cacheName) { ignoredCaches.add(cacheName); return CompletableFuture.completedFuture(null); } @Override public boolean isCacheIgnored(String cache) { return ignoredCaches.contains(cache); } @Override public Set<String> getIgnoredCaches() { return ignoredCaches; } @Override public CompletableFuture<Boolean> connectorStatus(String name) { return CompletableFuture.completedFuture(true); } @Override public CompletableFuture<Boolean> connectorStart(String name) { return CompletableFuture.completedFuture(true); } @Override public CompletableFuture<Void> connectorStop(String name) { return CompletableFuture.completedFuture(null); } @Override public CompletableFuture<Void> setConnectorIpFilterRule(String name, Collection<IpSubnetFilterRule> filterRule) { return CompletableFuture.completedFuture(null); } @Override public CompletableFuture<Void> clearConnectorIpFilterRules(String name) { return CompletableFuture.completedFuture(null); } @Override public CompletableFuture<Json> listConnections() { return CompletableFuture.completedFuture(Json.array()); } @Override public ServerManagement managedServer() { return null; } @Override public void start() { } @Override public void stop() { } }
2,142
24.819277
116
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/MarshallingTest.java
package org.infinispan.server.core; import java.io.IOException; import java.util.Arrays; import org.testng.AssertJUnit; import org.testng.annotations.Test; /** * Marshalling test for server core classes. * * @author Galder Zamarreño * @since 4.1 */ @Test(groups = "functional", testName = "server.core.MarshallingTest") public class MarshallingTest extends AbstractMarshallingTest { public void testMarshallingBigByteArrayValue() throws IOException, InterruptedException, ClassNotFoundException { byte[] cacheValue = getBigByteArray(); byte[] bytes = marshaller.objectToByteBuffer(cacheValue); byte[] readValue = (byte[]) marshaller.objectFromByteBuffer(bytes); AssertJUnit.assertTrue(Arrays.equals(readValue, cacheValue)); } }
767
29.72
116
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/AbstractProtocolServerTest.java
package org.infinispan.server.core; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.core.configuration.MockServerConfiguration; import org.infinispan.server.core.configuration.MockServerConfigurationBuilder; import org.infinispan.server.core.configuration.ProtocolServerConfiguration; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.Assert; import org.testng.annotations.Test; import io.netty.channel.Channel; import io.netty.channel.ChannelInboundHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOutboundHandler; import io.netty.channel.group.ChannelMatcher; /** * Abstract protocol server test. * * @author Galder Zamarreño * @since 4.1 */ @Test(groups = "functional", testName = "server.core.AbstractProtocolServerTest") public class AbstractProtocolServerTest extends AbstractInfinispanTest { public void testValidateNegativeIdleTimeout() { MockServerConfigurationBuilder b = new MockServerConfigurationBuilder(); b.idleTimeout(-2); expectIllegalArgument(b, new MockProtocolServer()); } public void testValidateNegativeSendBufSize() { MockServerConfigurationBuilder b = new MockServerConfigurationBuilder(); b.sendBufSize(-1); expectIllegalArgument(b, new MockProtocolServer()); } public void testValidateNegativeRecvBufSize() { MockServerConfigurationBuilder b = new MockServerConfigurationBuilder(); b.recvBufSize(-1); expectIllegalArgument(b, new MockProtocolServer()); } public void testStartingWithoutTransport() { MockServerConfigurationBuilder b = new MockServerConfigurationBuilder(); b.startTransport(false); AbstractProtocolServer<MockServerConfiguration> server = new MockProtocolServer(); EmbeddedCacheManager manager = TestCacheManagerFactory.createCacheManager(); try { server.start(b.build(), manager); Assert.assertFalse(server.isTransportEnabled()); } finally { server.stop(); manager.stop(); } } private void expectIllegalArgument(MockServerConfigurationBuilder builder, MockProtocolServer server) { try { // Stoppable.useCacheManager(TestCacheManagerFactory.createCacheManager()) { cm => // server.start(builder.build(), cm) // } } catch (IllegalArgumentException e) { // case i: IllegalArgumentException => // expected } finally { server.stop(); } } class MockProtocolServer extends AbstractProtocolServer { protected MockProtocolServer() { super(null); } @Override public ChannelOutboundHandler getEncoder() { return null; } @Override public ChannelInboundHandler getDecoder() { return null; } @Override public ChannelMatcher getChannelMatcher() { return channel -> true; } @Override public void installDetector(Channel ch) { } @Override public ProtocolServerConfiguration getConfiguration() { return configuration; } @Override public ChannelInitializer<Channel> getInitializer() { return null; } } }
3,303
29.592593
106
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/AbstractMarshallingTest.java
package org.infinispan.server.core; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.Random; import org.infinispan.commons.CacheException; import org.infinispan.commons.marshall.StreamingMarshaller; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; /** * Abstract class to help marshalling tests in different server modules. * * @author Galder Zamarreño * @since 4.1 */ public abstract class AbstractMarshallingTest extends AbstractInfinispanTest { protected StreamingMarshaller marshaller; protected EmbeddedCacheManager cm; @BeforeClass(alwaysRun=true) public void setUp() { // Manual addition of externalizers to replication what happens in fully functional tests cm = TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder()); marshaller = TestingUtil.extractGlobalMarshaller(cm.getCache().getCacheManager()); } @AfterClass(alwaysRun=true) public void tearDown() { if (cm != null) cm.stop(); } protected byte[] getBigByteArray() { String value = new String(randomByteArray(1000)); ByteArrayOutputStream result = new ByteArrayOutputStream(1000); try { ObjectOutputStream oos = new ObjectOutputStream(result); oos.writeObject(value); return result.toByteArray(); } catch (IOException e) { throw new CacheException(e); } } private byte[] randomByteArray(int i) { Random r = new Random(); byte[] result = new byte[i]; r.nextBytes(result); return result; } }
1,900
30.683333
95
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/MockProtocolServer.java
package org.infinispan.server.core; import org.infinispan.server.core.configuration.MockServerConfiguration; import org.infinispan.server.core.configuration.MockServerConfigurationBuilder; import org.infinispan.server.core.transport.NettyTransport; import io.netty.channel.Channel; import io.netty.channel.ChannelInboundHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOutboundHandler; import io.netty.channel.group.ChannelMatcher; public class MockProtocolServer extends AbstractProtocolServer<MockServerConfiguration> { public static final String DEFAULT_CACHE_NAME = "dummyCache"; public static final int DEFAULT_PORT = 1245; public MockProtocolServer(String protocolName, NettyTransport transport) { super(protocolName); configuration = new MockServerConfigurationBuilder() .defaultCacheName(DEFAULT_CACHE_NAME) .port(DEFAULT_PORT) .build(); this.transport = transport; } public MockProtocolServer() { super(null); } @Override public ChannelOutboundHandler getEncoder() { return null; } @Override public ChannelInboundHandler getDecoder() { return null; } @Override public ChannelMatcher getChannelMatcher() { return channel -> true; } @Override public void installDetector(Channel ch) { } @Override public ChannelInitializer<Channel> getInitializer() { return null; } }
1,468
25.709091
89
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/configuration/MockServerConfigurationBuilder.java
package org.infinispan.server.core.configuration; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * @author Tristan Tarrant * @since 5.3 */ public class MockServerConfigurationBuilder extends ProtocolServerConfigurationBuilder<MockServerConfiguration, MockServerConfigurationBuilder, MockAuthenticationConfiguration> { public MockServerConfigurationBuilder() { super(12345, MockServerConfiguration.attributeDefinitionSet()); } @Override public AttributeSet attributes() { return attributes; } @Override public MockServerConfigurationBuilder self() { return this; } @Override public AuthenticationConfigurationBuilder<MockAuthenticationConfiguration> authentication() { return new MockAuthenticationConfigurationBuilder(); } @Override public MockServerConfiguration build() { return build(true); } public MockServerConfiguration build(boolean validate) { if (validate) { validate(); } return create(); } @Override public MockServerConfiguration create() { return new MockServerConfiguration(attributes.protect(), authentication().create(), ssl.create(), ipFilter.create()); } }
1,235
24.75
178
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/configuration/MockAuthenticationConfigurationBuilder.java
package org.infinispan.server.core.configuration; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * @since 15.0 **/ public class MockAuthenticationConfigurationBuilder implements AuthenticationConfigurationBuilder<MockAuthenticationConfiguration> { @Override public MockAuthenticationConfiguration create() { return new MockAuthenticationConfiguration(); } @Override public Builder<?> read(MockAuthenticationConfiguration template, Combine combine) { return this; } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } @Override public MockAuthenticationConfigurationBuilder enable() { return this; } @Override public String securityRealm() { return "default"; } }
900
24.027778
132
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/configuration/MockAuthenticationConfiguration.java
package org.infinispan.server.core.configuration; /** * @since 15.0 **/ public class MockAuthenticationConfiguration implements AuthenticationConfiguration { @Override public String securityRealm() { return "default"; } @Override public boolean enabled() { return false; } }
309
17.235294
85
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/configuration/IpSubnetFilterRuleTest.java
package org.infinispan.server.core.configuration; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import org.infinispan.server.core.transport.IpSubnetFilterRule; import org.testng.annotations.Test; import io.netty.handler.ipfilter.IpFilterRuleType; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.1 **/ @Test(groups = "unit", testName = "server.configuration.IpSubnetFilterRuleTest") public class IpSubnetFilterRuleTest { public void testIpSubnetFilterRule() throws UnknownHostException { IpSubnetFilterRule rule = new IpSubnetFilterRule("192.168.0.0/16", IpFilterRuleType.ACCEPT); assertTrue(rule.matches(new InetSocketAddress(InetAddress.getByName("192.168.0.1"), 11222))); assertFalse(rule.matches(new InetSocketAddress(InetAddress.getByName("10.11.12.13"), 11222))); rule = new IpSubnetFilterRule("/0", IpFilterRuleType.REJECT); assertTrue(rule.matches(new InetSocketAddress(InetAddress.getByName("192.168.0.1"), 11222))); assertTrue(rule.matches(new InetSocketAddress(InetAddress.getByName("10.11.12.13"), 11222))); rule = new IpSubnetFilterRule("fe80::/64", IpFilterRuleType.ACCEPT); assertTrue(rule.matches(new InetSocketAddress(InetAddress.getByName("fe80::9656:d028:8652:66b6"), 11222))); assertFalse(rule.matches(new InetSocketAddress(InetAddress.getByName("2001:0db8:0123:4567:89ab:fcde:1234:5670"), 11222))); } }
1,572
45.264706
128
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/configuration/MockServerConfiguration.java
package org.infinispan.server.core.configuration; import org.infinispan.commons.configuration.attributes.AttributeSet; public class MockServerConfiguration extends ProtocolServerConfiguration<MockServerConfiguration, MockAuthenticationConfiguration> { public static AttributeSet attributeDefinitionSet() { return new AttributeSet(MockServerConfiguration.class, ProtocolServerConfiguration.attributeDefinitionSet()); } protected MockServerConfiguration(AttributeSet attributes, MockAuthenticationConfiguration authentication, SslConfiguration ssl, IpFilterConfiguration ipRules) { super("mock-connector", attributes, authentication, ssl, ipRules); } }
679
44.333333
164
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/backup/BackupManagerImplTest.java
package org.infinispan.server.core.backup; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_UNKNOWN_TYPE; import static org.infinispan.functional.FunctionalTestUtils.MAX_WAIT_SECS; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.server.core.BackupManager.Resources.Type.CACHES; import static org.infinispan.server.core.BackupManager.Resources.Type.TEMPLATES; import static org.infinispan.server.core.backup.Constants.CONTAINERS_PROPERTIES_FILE; import static org.infinispan.server.core.backup.Constants.CONTAINER_KEY; import static org.infinispan.server.core.backup.Constants.GLOBAL_CONFIG_FILE; import static org.infinispan.server.core.backup.Constants.MANIFEST_PROPERTIES_FILE; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.EncodingConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.globalstate.ConfigurationStorage; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.core.BackupManager; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.util.function.TriConsumer; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author Ryan Emerson * @since 12.0 */ @Test(groups = "functional", testName = "server.core.BackupManagerImplTest") public class BackupManagerImplTest extends AbstractInfinispanTest { private static File workingDir; @BeforeMethod void setup() { workingDir = new File(CommonsTestingUtil.tmpDirectory(BackupManagerImplTest.class)); Util.recursiveFileRemove(workingDir); workingDir.mkdirs(); } @AfterMethod static void teardown() { Util.recursiveFileRemove(workingDir); } public void testMissingCacheOnBackup() { invalidWriteTest("'example-cache' does not exist", new BackupManagerResources.Builder() .addCaches("example-cache") .build() ); } public void testMissingCacheConfigOnBackup() { invalidWriteTest("'template' does not exist", new BackupManagerResources.Builder() .addCacheConfigurations("template") .build() ); } private void invalidWriteTest(String msg, BackupManager.Resources params) { withBackupManager((cm, backupManager) -> { try { CompletionStage<Path> stage = backupManager.create("invalidWriteTest", null, Collections.singletonMap("default", params)); stage.toCompletableFuture().get(MAX_WAIT_SECS, TimeUnit.SECONDS); fail(); } catch (TimeoutException | InterruptedException e) { fail(); } catch (ExecutionException e) { Throwable t = e.getCause(); assertTrue(t instanceof CacheException); assertTrue(t.getMessage().contains("Cannot create cluster backup")); t = t.getCause(); assertTrue(t instanceof CompletionException); t = t.getCause(); assertTrue(t instanceof CacheException); assertTrue(t.getMessage().contains(msg)); } return CompletableFutures.completedNull(); }); } public void testMissingCacheOnRestore() throws Exception { String resource = "example-cache"; invalidRestoreTest(resource, new BackupManagerResources.Builder().addCaches(resource).build()); } public void testMissingCacheConfigOnRestore() throws Exception { String resource = "template"; invalidRestoreTest(resource, new BackupManagerResources.Builder().addCacheConfigurations(resource).build()); } private void invalidRestoreTest(String resourceName, BackupManager.Resources params) throws Exception { String name = "invalidRestoreTest"; createAndRestore( (source, backupManager) -> backupManager.create(name, null), (target, backupManager, backup) -> { assertTrue(target.getCacheNames().isEmpty()); assertNull(target.getCacheConfiguration("cache-config")); Map<String, BackupManager.Resources> paramMap = Collections.singletonMap("default", params); CompletableFuture<Void> stage = backupManager.restore(name, backup, paramMap).toCompletableFuture(); try { stage.get(MAX_WAIT_SECS, TimeUnit.SECONDS); } catch (ExecutionException e) { assertTrue(stage.isCompletedExceptionally()); Throwable t = e.getCause(); assertTrue(t instanceof CacheException); assertTrue(t.getMessage().contains("Cannot restore cluster backup")); t = t.getCause(); assertTrue(t instanceof CompletionException); t = t.getCause(); assertTrue(t instanceof CacheException); assertTrue(t.getMessage().contains(String.format("'[%s]' not found in the backup archive", resourceName))); } catch (Exception e) { fail(); } } ); } public void testBackupAndRestoreJson() { ConfigurationBuilder builder = new ConfigurationBuilder(); EncodingConfigurationBuilder encoding = builder.encoding(); encoding.key().mediaType("application/x-java-object;type=java.lang.String"); encoding.value().mediaType(MediaType.APPLICATION_JSON_TYPE); Configuration config = builder.build(); String name = "testBackupAndRestoreJson"; String cacheName = "cache"; int numEntries = 1; createAndRestore( (source, backupManager) -> { Cache<String, String> cache = source.administration().getOrCreateCache(cacheName, config); for (int i = 0; i < numEntries; i++) cache.put(""+i, String.format("{\"value\":\"%d\"}", i)); return backupManager.create(name, null); }, (target, backupManager, backup) -> { assertTrue(target.getCacheNames().isEmpty()); await(backupManager.restore(name, backup)); assertTrue(target.cacheExists(cacheName)); assertEquals(numEntries, target.getCache(cacheName).size()); }); } public void testBackupAndRestoreEntryExceeding256Bytes() { String name = "testBackupAndRestoreEntryExceeding256Bytes"; String cacheName = "cache"; createAndRestore( (source, backupManager) -> { Cache<byte[], byte[]> cache = source.administration().getOrCreateCache(cacheName, config(APPLICATION_OCTET_STREAM_TYPE)); cache.put(new byte[1], new byte[256]); return backupManager.create(name, null); }, (target, backupManager, backup) -> { assertTrue(target.getCacheNames().isEmpty()); Map<String, BackupManager.Resources> paramMap = Collections.singletonMap("default", new BackupManagerResources.Builder() .includeAll() .build() ); await(backupManager.restore(name, backup, paramMap)); assertTrue(target.cacheExists(cacheName)); assertEquals(1, target.getCache(cacheName).size()); }); } public void testBackupAndRestoreIgnoreResources() throws Exception { String name = "testBackupAndRestoreIgnoreResources"; createAndRestore( (source, backupManager) -> { source.defineConfiguration("cache-config", config(APPLICATION_OBJECT_TYPE, true)); Cache<String, String> cache = source.createCache("cache", config(APPLICATION_OBJECT_TYPE)); cache.put("key", "value"); return backupManager.create(name, null); }, (target, backupManager, backup) -> { assertTrue(target.getCacheNames().isEmpty()); assertNull(target.getCacheConfiguration("cache-config")); Map<String, BackupManager.Resources> paramMap = Collections.singletonMap("default", new BackupManagerResources.Builder() .includeAll() .ignore(CACHES) .build() ); await(backupManager.restore(name, backup, paramMap)); assertTrue(target.getCacheNames().isEmpty()); assertNotNull(target.getCacheConfiguration("cache-config")); }); } public void testBackupAndRestoreWildcardResources() throws Exception { String name = "testBackupAndRestoreWildcardResources"; createAndRestore( (source, backupManager) -> { source.defineConfiguration("cache-config", config(APPLICATION_OBJECT_TYPE, true)); Cache<String, String> cache = source.createCache("cache", config(APPLICATION_OBJECT_TYPE)); cache.put("key", "value"); return backupManager.create(name, null); }, (target, backupManager, backup) -> { assertTrue(target.getCacheNames().isEmpty()); assertNull(target.getCacheConfiguration("cache-config")); await(backupManager.restore(name, backup)); assertFalse(target.getCacheNames().isEmpty()); assertNotNull(target.getCacheConfiguration("cache-config")); Cache<String, String> cache = target.getCache("cache"); assertNotNull(cache); assertEquals("value", cache.get("key")); }); } public void testCustomWorkingDirectory() throws IOException { String backupName = "customDir"; Path customDir = new File(workingDir, "custom-dir").toPath(); Files.createDirectory(customDir); Path zip = withBackupManager((cm, bm) -> bm.create(backupName, customDir)); assertEquals(customDir.resolve(backupName).resolve(backupName + ".zip"), zip); } private void createAndRestore(BiFunction<DefaultCacheManager, BackupManager, CompletionStage<Path>> backup, TriConsumer<DefaultCacheManager, BackupManager, Path> restore) { Path zip = withBackupManager(backup); // Remove all source files, such as caches.xml from overlay for (File f : workingDir.listFiles()) if (!f.isDirectory()) f.delete(); withBackupManager((cm, bm) -> { restore.accept(cm, bm, zip); return CompletableFutures.completedNull(); }); } private <T> T withBackupManager(BiFunction<DefaultCacheManager, BackupManager, CompletionStage<T>> function) { try (DefaultCacheManager cm = createManager()) { BlockingManager blockingManager = cm.getGlobalComponentRegistry().getComponent(BlockingManager.class); BackupManager backupManager = new BackupManagerImpl(blockingManager, cm, workingDir.toPath()); backupManager.init(); return await(function.apply(cm, backupManager)); } catch (IOException e) { throw new RuntimeException(e); } } public void testBackupAndRestoreMultipleContainers() throws Exception { int numEntries = 100; String container1 = "container1"; String container2 = "container2"; Map<String, DefaultCacheManager> readerManagers = createManagerMap(container1, container2); Map<String, DefaultCacheManager> writerManagers = createManagerMap(container1, container2); try { DefaultCacheManager sourceManager1 = writerManagers.get(container1); DefaultCacheManager sourceManager2 = writerManagers.get(container2); sourceManager1.defineConfiguration("example-template", config(APPLICATION_OBJECT_TYPE, true)); sourceManager1.defineConfiguration("object-cache", config(APPLICATION_OBJECT_TYPE)); sourceManager1.defineConfiguration("protostream-cache", config(APPLICATION_PROTOSTREAM_TYPE)); sourceManager1.defineConfiguration("empty-cache", config(APPLICATION_UNKNOWN_TYPE)); sourceManager2.defineConfiguration("container2-cache", config(APPLICATION_UNKNOWN_TYPE)); IntStream.range(0, numEntries).forEach(i -> sourceManager1.getCache("object-cache").put(i, i)); IntStream.range(0, numEntries).forEach(i -> sourceManager1.getCache("protostream-cache").put(i, i)); ParserRegistry parserRegistry = new ParserRegistry(); BlockingManager blockingManager = writerManagers.values().iterator().next().getGlobalComponentRegistry().getComponent(BlockingManager.class); String name = "testBackupAndRestoreMultipleContainers"; BackupWriter writer = new BackupWriter(name, blockingManager, writerManagers, parserRegistry, workingDir.toPath()); Map<String, BackupManager.Resources> paramMap = new HashMap<>(2); paramMap.put(container1, new BackupManagerResources.Builder() .addCaches("object-cache", "protostream-cache", "empty-cache") .addCacheConfigurations("example-template") .build() ); paramMap.put(container2, new BackupManagerResources.Builder() .addCaches("container2-cache") .build() ); Path backupZip = await(writer.create(paramMap)); assertNotNull(backupZip); Path extractedRoot = workingDir.toPath().resolve("extracted"); File extractedDir = extractedRoot.toFile(); extractedDir.mkdir(); extractBackup(backupZip.toFile(), extractedDir); assertFileExists(extractedRoot, MANIFEST_PROPERTIES_FILE); Path containerPath = path(extractedRoot, CONTAINER_KEY, container1); assertFileExists(containerPath, CONTAINERS_PROPERTIES_FILE); assertFileExists(containerPath, GLOBAL_CONFIG_FILE); assertFileExists(containerPath, TEMPLATES.toString(), "example-template.xml"); assertFileExists(containerPath, CACHES.toString(), "object-cache", "object-cache.xml"); assertFileExists(containerPath, CACHES.toString(), "object-cache", "object-cache.dat"); assertFileExists(containerPath, CACHES.toString(), "protostream-cache", "protostream-cache.xml"); assertFileExists(containerPath, CACHES.toString(), "protostream-cache", "protostream-cache.dat"); assertFileExists(containerPath, CACHES.toString(), "empty-cache", "empty-cache.xml"); assertFileExists(containerPath, CACHES.toString(), "empty-cache", "empty-cache.dat"); containerPath = path(extractedRoot, CONTAINER_KEY, container2); assertFileExists(containerPath, GLOBAL_CONFIG_FILE); assertFileExists(containerPath, CONTAINERS_PROPERTIES_FILE); assertFileExists(containerPath, CACHES.toString(), "container2-cache", "container2-cache.xml"); assertFileDoesNotExist(containerPath, CACHES.toString(), "object-cache"); assertFileDoesNotExist(containerPath, CACHES.toString(), "protostream-cache"); BackupReader reader = new BackupReader(blockingManager, readerManagers, parserRegistry); CompletionStage<Void> restoreStage = reader.restore(backupZip, paramMap); await(restoreStage); DefaultCacheManager targetManager1 = readerManagers.get(container1); DefaultCacheManager targetManager2 = readerManagers.get(container2); Configuration template = targetManager1.getCacheConfiguration("example-template"); assertNotNull(template); assertTrue(template.isTemplate()); Cache<Integer, Integer> objectCache = targetManager1.getCache("object-cache"); assertFalse(objectCache.isEmpty()); assertEquals(100, objectCache.size()); assertEquals(Integer.valueOf(50), objectCache.get(50)); Cache<Integer, Integer> protoCache = targetManager1.getCache("protostream-cache"); assertFalse(protoCache.isEmpty()); assertEquals(100, protoCache.size()); assertEquals(Integer.valueOf(1), protoCache.get(1)); Cache<Object, Object> emptyCache = targetManager1.getCache("empty-cache"); assertTrue(emptyCache.isEmpty()); Cache<Object, Object> container2Cache = targetManager2.getCache("container2-cache"); assertTrue(container2Cache.isEmpty()); } finally { writerManagers.values().forEach(EmbeddedCacheManager::stop); readerManagers.values().forEach(EmbeddedCacheManager::stop); } } private Map<String, DefaultCacheManager> createManagerMap(String... containers) { return Arrays.stream(containers) .collect(Collectors.toMap(Function.identity(), name -> createManager())); } private DefaultCacheManager createManager() { GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder(); gcb.cacheManagerName("default") .globalState().enable() .configurationStorage(ConfigurationStorage.OVERLAY) .persistentLocation(workingDir.getAbsolutePath()); return (DefaultCacheManager) TestCacheManagerFactory.newDefaultCacheManager(true, gcb, null); } private Configuration config(String type) { return config(type, false); } private Configuration config(String type, boolean template) { ConfigurationBuilder builder = new ConfigurationBuilder(); EncodingConfigurationBuilder encoding = builder.encoding(); encoding.key().mediaType(type); encoding.value().mediaType(type); builder.template(template); return builder.build(); } private Path path(Path root, String... paths) { return Paths.get(root.toString(), paths); } private void assertFileExists(Path root, String... paths) { Path path = path(root, paths); assertTrue(path.toFile().exists()); } private void assertFileDoesNotExist(Path root, String... paths) { Path path = path(root, paths); assertFalse(path.toFile().exists()); } private void extractBackup(File backup, File destDir) throws IOException { try (ZipFile zip = new ZipFile(backup)) { Enumeration<? extends ZipEntry> zipEntries = zip.entries(); while (zipEntries.hasMoreElements()) { ZipEntry entry = zipEntries.nextElement(); File file = new File(destDir, entry.getName()); if (entry.isDirectory()) { file.mkdirs(); } else { file.getParentFile().mkdirs(); Files.copy(zip.getInputStream(entry), file.toPath()); } } } } }
20,653
45.102679
150
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/test/Stoppable.java
package org.infinispan.server.core.test; import java.util.function.Consumer; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.core.AbstractProtocolServer; import org.infinispan.test.TestingUtil; /** * Stoppable implements simple wrappers for objects which need to be stopped in certain way after being used * @author Galder Zamarreño * @author wburns */ public class Stoppable { public static <T extends EmbeddedCacheManager> void useCacheManager(T stoppable, Consumer<? super T> consumer) { try { consumer.accept(stoppable); } finally { TestingUtil.killCacheManagers(stoppable); } } public static <T extends AbstractProtocolServer<?>> void useServer(T stoppable, Consumer<? super T> consumer) { try { consumer.accept(stoppable); } finally { ServerTestingUtil.killServer(stoppable); } } }
914
27.59375
115
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/test/ServerTestingUtil.java
package org.infinispan.server.core.test; import java.io.IOException; import java.net.BindException; import java.net.ServerSocket; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.infinispan.server.core.AbstractProtocolServer; import io.netty.channel.unix.Errors; /** * Infinispan servers testing util * * @author Galder Zamarreño * @author wburns */ public class ServerTestingUtil { private static final AtomicInteger DEFAULT_UNIQUE_PORT = new AtomicInteger(15232); private static Log LOG = LogFactory.getLog(ServerTestingUtil.class); public static void killServer(AbstractProtocolServer<?> server) { try { if (server != null) server.stop(); } catch (Throwable t) { LOG.error("Error stopping server", t); } } private static boolean isBindException(Throwable e) { if (e instanceof BindException) return true; if (e instanceof Errors.NativeIoException) { Errors.NativeIoException nativeIoException = (Errors.NativeIoException) e; return nativeIoException.getMessage().contains("bind"); } return false; } public static int findFreePort() { try { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } } catch (IOException e) { LOG.debugf("Error finding free port, falling back to auto-generated port. Error message: ", e.getMessage()); } return DEFAULT_UNIQUE_PORT.incrementAndGet(); } public static <S extends AbstractProtocolServer<?>> S startProtocolServer(int initialPort, Function<Integer, S> serverStarter) { S server = null; int maxTries = 10; int currentTries = 0; Throwable lastError = null; while (server == null && currentTries < maxTries) { try { server = serverStarter.apply(initialPort); } catch (Throwable t) { if (!isBindException(t)) { throw t; } else { LOG.debug("Address already in use: [" + t.getMessage() + "], retrying"); currentTries++; initialPort = findFreePort(); lastError = t; } } } if (server == null && lastError != null) throw new AssertionError(lastError); return server; } }
2,491
28.666667
131
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/dataconversion/DeserializerTest.java
package org.infinispan.server.core.dataconversion; import static org.testng.AssertJUnit.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import org.infinispan.server.core.dataconversion.deserializer.Deserializer; import org.infinispan.server.core.dataconversion.deserializer.SEntity; import org.testng.annotations.Test; /** * @since 15.0 **/ @Test(groups = "functional", testName = "server.core.dataconversion.DeserializerTest") public class DeserializerTest { public enum MyEnum { A, B } public static class MyPojo implements Serializable { String s; boolean b; short sh; int i; long l; float f; double d; MyEnum e; MyPojo pojo; } public void testJavaDeserialization() throws IOException { MyPojo pojo = new MyPojo(); pojo.s = "a string"; pojo.b = true; pojo.sh = Short.MAX_VALUE / 2; pojo.i = Integer.MAX_VALUE / 2; pojo.l = Long.MAX_VALUE / 2; pojo.f = 1.234F; pojo.d = 3.141; pojo.e = MyEnum.A; pojo.pojo = new MyPojo(); pojo.pojo.pojo = pojo; // test recursion ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ObjectOutputStream os = new ObjectOutputStream(baos)) { os.writeObject(pojo); } Deserializer deserializer = new Deserializer(new ByteArrayInputStream(baos.toByteArray()), true); SEntity entity = deserializer.readObject(); assertEquals("{\"b\":true,\"d\":3.141,\"f\":1.234,\"i\":1073741823,\"l\":4611686018427387903,\"sh\":16383,\"e\":{\"<name>\":\"A\"},\"pojo\":{\"b\":false,\"d\":0.0,\"f\":0.0,\"i\":0,\"l\":0,\"sh\":0,\"e\":null,\"pojo\":{},\"s\":null},\"s\":\"a string\"}", entity.json().toString()); } }
1,875
29.754098
287
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/dataconversion/JsonTranscoderTest.java
package org.infinispan.server.core.dataconversion; import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.UTF_8; 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_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.dataconversion.StandardConversions.convertCharset; import static org.infinispan.server.core.dataconversion.JsonTranscoder.TYPE_PROPERTY; import static org.testng.AssertJUnit.assertEquals; import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.nio.charset.Charset; import java.util.Collections; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.dataconversion.EncodingException; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.util.Util; import org.infinispan.test.data.Address; import org.infinispan.test.data.Person; import org.infinispan.test.dataconversion.AbstractTranscoderTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * @since 9.2 */ @Test(groups = "functional", testName = "server.core.dataconversion.JsonTranscoderTest") public class JsonTranscoderTest extends AbstractTranscoderTest { protected Person dataSrc; @BeforeClass(alwaysRun = true) public void setUp() { dataSrc = new Person("joe"); Address address = new Address(); address.setCity("London"); dataSrc.setAddress(address); transcoder = new JsonTranscoder(new ClassAllowList(Collections.singletonList(".*"))); supportedMediaTypes = transcoder.getSupportedMediaTypes(); } @Override public void testTranscoderTranscode() { MediaType jsonMediaType = APPLICATION_JSON; MediaType personMediaType = MediaType.fromString("application/x-java-object;type=org.infinispan.test.data.Person"); Object result = transcoder.transcode(dataSrc, personMediaType, jsonMediaType); assertEquals( String.format("{\"" + TYPE_PROPERTY + "\":\"%s\",\"name\":\"%s\",\"address\":{\"" + TYPE_PROPERTY + "\":\"%s\",\"street\":null,\"city\":\"%s\",\"zip\":0},\"picture\":null,\"sex\":null,\"birthDate\":null,\"acceptedToS\":false,\"moneyOwned\":1.1,\"moneyOwed\":0.4,\"decimalField\":10.3,\"realField\":4.7}", Person.class.getName(), "joe", Address.class.getName(), "London"), new String((byte[]) result) ); Object fromJson = transcoder.transcode(result, jsonMediaType, personMediaType); assertEquals(fromJson, dataSrc); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ObjectOutputStream os = new ObjectOutputStream(baos)) { os.writeObject(dataSrc); } catch (IOException e) { // Won't happen } result = transcoder.transcode(baos.toByteArray(), MediaType.APPLICATION_SERIALIZED_OBJECT, jsonMediaType); assertEquals("{\"acceptedToS\":false,\"decimalField\":10.3,\"moneyOwed\":0.4,\"moneyOwned\":1.1,\"realField\":4.7,\"address\":{\"zip\":0,\"city\":\"London\",\"street\":null},\"birthDate\":null,\"name\":\"joe\",\"picture\":null,\"sex\":null}", new String((byte[]) result)); } @Test public void testEmptyContent() { byte[] empty = Util.EMPTY_BYTE_ARRAY; assertArrayEquals(empty, (byte[]) transcoder.transcode(empty, APPLICATION_JSON, APPLICATION_JSON.withCharset(US_ASCII))); assertArrayEquals(empty, (byte[]) transcoder.transcode(empty, APPLICATION_UNKNOWN, APPLICATION_JSON)); assertArrayEquals(empty, (byte[]) transcoder.transcode(empty, APPLICATION_OCTET_STREAM, APPLICATION_JSON)); assertArrayEquals(empty, (byte[]) transcoder.transcode(empty, APPLICATION_WWW_FORM_URLENCODED, APPLICATION_JSON)); assertArrayEquals(empty, (byte[]) transcoder.transcode(empty, TEXT_PLAIN, APPLICATION_JSON)); assertArrayEquals(empty, (byte[]) transcoder.transcode(empty, APPLICATION_OBJECT, APPLICATION_JSON)); } @Test public void testWWWFormUrlEncoded() { byte[] transcoded = (byte[]) transcoder.transcode("%7B%22k%22%3A%22v%22%7D", APPLICATION_WWW_FORM_URLENCODED, APPLICATION_JSON); assertEquals("{\"k\":\"v\"}", new String(transcoded)); } @Test public void testCharset() { Charset korean = Charset.forName("EUC-KR"); MediaType textPlainKorean = TEXT_PLAIN.withCharset(korean); MediaType jsonKorean = APPLICATION_JSON.withCharset(korean); MediaType textPlainAsString = TEXT_PLAIN.withClassType(String.class); MediaType jsonAsString = APPLICATION_JSON.withClassType(String.class); String content = "{\"city_kr\":\"서울\"}"; byte[] contentUTF = content.getBytes(UTF_8); byte[] contentKorean = convertCharset(contentUTF, UTF_8, korean); byte[] result = (byte[]) transcoder.transcode(contentKorean, jsonKorean, TEXT_PLAIN); assertArrayEquals(result, contentUTF); String strResult = (String) transcoder.transcode(contentKorean, jsonKorean, textPlainAsString); assertEquals(strResult, content); result = (byte[]) transcoder.transcode(contentKorean, jsonKorean, textPlainKorean); assertArrayEquals(result, contentKorean); result = (byte[]) transcoder.transcode(contentKorean, textPlainKorean, APPLICATION_JSON); assertArrayEquals(result, contentUTF); strResult = (String) transcoder.transcode(contentKorean, jsonKorean, jsonAsString); assertEquals(strResult, content); result = (byte[]) transcoder.transcode(contentKorean, textPlainKorean, jsonKorean); assertArrayEquals(result, contentKorean); result = (byte[]) transcoder.transcode(contentUTF, TEXT_PLAIN, jsonKorean); assertArrayEquals(result, contentKorean); result = (byte[]) transcoder.transcode(content, textPlainAsString, jsonKorean); assertArrayEquals(result, contentKorean); result = (byte[]) transcoder.transcode(contentUTF, APPLICATION_JSON, TEXT_PLAIN); assertArrayEquals(result, contentUTF); result = (byte[]) transcoder.transcode(contentUTF, APPLICATION_JSON, textPlainKorean); assertArrayEquals(result, contentKorean); } private void assertTextToJsonConversion(String content) { final Object transcode = transcoder.transcode(content, TEXT_PLAIN, APPLICATION_JSON); assertArrayEquals((byte[]) transcode, content.getBytes(UTF_8)); } @Test public void testTextToJson() { assertTextToJsonConversion("{\"a\":1}"); assertTextToJsonConversion("1.5"); assertTextToJsonConversion("\"test\""); } @Test(expectedExceptions = EncodingException.class) public void testPreventInvalidJson() { byte[] invalidContent = "\"field\" : value".getBytes(UTF_8); transcoder.transcode(invalidContent, TEXT_PLAIN, APPLICATION_JSON); } @Test(expectedExceptions = EncodingException.class) public void testPreventInvalidJson2() { byte[] invalidContent = "text".getBytes(UTF_8); transcoder.transcode(invalidContent, TEXT_PLAIN, APPLICATION_JSON); } @Test(expectedExceptions = EncodingException.class) public void testPreventInvalidJson3() { byte[] invalidContent = "{a:1}".getBytes(UTF_8); transcoder.transcode(invalidContent, TEXT_PLAIN, APPLICATION_JSON); } }
7,821
45.011765
316
java
null
infinispan-main/server/core/src/test/java/org/infinispan/server/core/dataconversion/XMLTranscoderTest.java
package org.infinispan.server.core.dataconversion; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.singletonList; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_WWW_FORM_URLENCODED; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN; import static org.testng.AssertJUnit.assertArrayEquals; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.test.data.Address; import org.infinispan.test.data.Person; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @Test(groups = "functional", testName = "server.XMLTranscoderTest") public class XMLTranscoderTest { private Person person; private XMLTranscoder xmlTranscoder = new XMLTranscoder(new ClassAllowList(singletonList(".*"))); @BeforeClass(alwaysRun = true) public void setUp() { person = new Person("Joe"); Address address = new Address(); address.setCity("London"); person.setAddress(address); } public void testObjectToXML() { String xmlString = new String((byte[]) xmlTranscoder.transcode(person, APPLICATION_OBJECT, APPLICATION_XML)); Object transcodedBack = xmlTranscoder.transcode(xmlString, APPLICATION_XML, APPLICATION_OBJECT); assertEquals("Must be an equal objects", person, transcodedBack); } @Test public void testWWWFormUrlEncoded() { byte[] transcoded = (byte[]) xmlTranscoder.transcode("%3Cstring%3EHello%20World%21%3C%2Fstring%3E", APPLICATION_WWW_FORM_URLENCODED, APPLICATION_XML); assertEquals("<string>Hello World!</string>", new String(transcoded)); } public void testTextToXML() { byte[] value = "Hello World!".getBytes(UTF_8); Object asXML = xmlTranscoder.transcode(value, TEXT_PLAIN, APPLICATION_XML); assertEquals("<string>Hello World!</string>", new String((byte[]) asXML)); Object xmlAsText = xmlTranscoder.transcode(asXML, APPLICATION_XML, TEXT_PLAIN); assertArrayEquals("<string>Hello World!</string>".getBytes(), (byte[]) xmlAsText); } }
2,307
41.740741
156
java
null
infinispan-main/server/core/src/main/java/org/infinispan/server/core/PersistenceContextInitializer.java
package org.infinispan.server.core; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.server.core.backup.resources.CacheResource; import org.infinispan.server.core.backup.resources.CounterResource; @AutoProtoSchemaBuilder( dependsOn = { org.infinispan.commons.marshall.PersistenceContextInitializer.class, org.infinispan.marshall.persistence.impl.PersistenceContextInitializer.class }, includeClasses = { CacheResource.CacheBackupEntry.class, CounterResource.CounterBackupEntry.class }, schemaFileName = "persistence.server.core.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.persistence.server.core", service = false ) interface PersistenceContextInitializer extends SerializationContextInitializer { }
944
38.375
88
java
null
infinispan-main/server/core/src/main/java/org/infinispan/server/core/ExternalizerIds.java
package org.infinispan.server.core; /** * Externalizer ids used by Server module {@link org.infinispan.commons.marshall.AdvancedExternalizer} implementations. * TODO: update URL below * Information about the valid id range can be found <a href="http://community.jboss.org/docs/DOC-16198">here</a> * * @author Galder Zamarreño * @author wburns * @since 9.0 */ public final class ExternalizerIds { private ExternalizerIds() { } public static final int SERVER_ENTRY_VERSION = 1100; public static final int MEMCACHED_METADATA = 1101; public static final int TOPOLOGY_ADDRESS = 1102; public static final int TOPOLOGY_VIEW = 1103; public static final int SINGLE_HOMED_SERVER_ADDRESS = 1104; public static final int MIME_METADATA = 1105; public static final int BINARY_FILTER = 1106; public static final int BINARY_CONVERTER = 1107; public static final int KEY_VALUE_VERSION_CONVERTER = 1108; public static final int BINARY_FILTER_CONVERTER = 1109; public static final int KEY_VALUE_WITH_PREVIOUS_CONVERTER = 1110; public static final int ITERATION_FILTER = 1111; public static final int QUERY_ITERATION_FILTER = 1112; public static final int TX_STATE = 1113; public static final int CACHE_XID = 1114; public static final int CLIENT_ADDRESS = 1115; public static final int CREATE_STATE_FUNCTION = 1116; public static final int PREPARING_FUNCTION = 1117; public static final int COMPLETE_FUNCTION = 1118; public static final int DECISION_FUNCTION = 1119; public static final int PREPARED_FUNCTION = 1120; public static final int XID_PREDICATE = 1121; public static final int CONDITIONAL_MARK_ROLLBACK_FUNCTION = 1122; public static final int MULTI_HOMED_SERVER_ADDRESS = 1123; }
1,757
41.878049
119
java