repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
infinispan-main/server/runtime/src/main/java/org/infinispan/server/tasks/ServerTaskWrapper.java
package org.infinispan.server.tasks; import java.util.Optional; import java.util.Set; import java.util.function.Function; import org.infinispan.commons.CacheException; import org.infinispan.commons.util.Util; import org.infinispan.server.logging.Log; import org.infinispan.tasks.ServerTask; import org.infinispan.tasks.Task; import org.infinispan.tasks.TaskContext; import org.infinispan.tasks.TaskExecutionMode; import org.infinispan.tasks.TaskInstantiationMode; import org.infinispan.util.logging.LogFactory; /** * @author Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com */ public class ServerTaskWrapper<T> implements Task, Function<TaskContext, T> { private static final Log log = LogFactory.getLog(ServerTaskWrapper.class, Log.class); private final ServerTask<T> task; public ServerTaskWrapper(ServerTask<T> task) { this.task = task; } @Override public String getName() { return task.getName(); } public T run(TaskContext context) throws Exception { final ServerTask<T> t; if (task.getInstantiationMode() == TaskInstantiationMode.ISOLATED) { t = Util.getInstance(task.getClass()); } else { t = task; } t.setTaskContext(context); if (log.isTraceEnabled()) { log.tracef("Executing task '%s' in '%s' mode using context %s", getName(), getInstantiationMode(), context); } return t.call(); } @Override public T apply(TaskContext context) { try { return run(context); } catch (Exception e) { throw new CacheException(e); } } @Override public String getType() { return "Java"; } @Override public TaskExecutionMode getExecutionMode() { return task.getExecutionMode(); } @Override public TaskInstantiationMode getInstantiationMode() { return task.getInstantiationMode(); } public Optional<String> getRole() { return task.getAllowedRole(); } @Override public Set<String> getParameters() { return task.getParameters(); } }
2,065
24.825
117
java
null
infinispan-main/server/runtime/src/main/java/org/infinispan/server/tasks/ServerTaskRunner.java
package org.infinispan.server.tasks; import java.util.concurrent.CompletableFuture; import org.infinispan.tasks.TaskContext; /** * Used by ServerTaskEngine to executed ServerTasks * * @author Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com */ public interface ServerTaskRunner { /** * Trigger execution of a ServerTask with given name. Returns a CompletableFuture, from which the result of execution * can be obtained. * * @param taskName name of the task to be executed * @param context task context injected into task upon execution * @param <T> task return type * @return completable future providing a way to get the result */ <T> CompletableFuture<T> execute(String taskName, TaskContext context); }
759
30.666667
120
java
null
infinispan-main/server/runtime/src/main/java/org/infinispan/server/tasks/DistributedServerTaskRunner.java
package org.infinispan.server.tasks; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.manager.ClusterExecutor; import org.infinispan.remoting.transport.Address; import org.infinispan.security.Security; import org.infinispan.security.actions.SecurityActions; import org.infinispan.tasks.TaskContext; import org.infinispan.util.function.TriConsumer; /** * @author Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com */ public class DistributedServerTaskRunner implements ServerTaskRunner { public DistributedServerTaskRunner() { } @Override public <T> CompletableFuture<T> execute(String taskName, TaskContext context) { String cacheName = context.getCache().map(Cache::getName).orElse(null); ClusterExecutor clusterExecutor = SecurityActions.getClusterExecutor(context.getCacheManager()); List<T> results = new ArrayList<>(); TriConsumer<Address, T, Throwable> triConsumer = (a, v, t) -> { if (t != null) { throw new CacheException(t); } synchronized (results) { results.add(v); } }; CompletableFuture<Void> future = Security.doAs(context.subject(), () -> clusterExecutor.submitConsumer( new DistributedServerTask<>(taskName, cacheName, context), triConsumer )); return (CompletableFuture<T>) future.thenApply(ignore -> results); } }
1,535
31.680851
109
java
null
infinispan-main/server/runtime/src/main/java/org/infinispan/server/tasks/admin/ServerAdminOperationsHandler.java
package org.infinispan.server.tasks.admin; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.server.core.admin.AdminOperationsHandler; import org.infinispan.server.core.admin.AdminServerTask; import org.infinispan.server.core.admin.embeddedserver.CacheNamesTask; import org.infinispan.server.core.admin.embeddedserver.CacheReindexTask; import org.infinispan.server.core.admin.embeddedserver.CacheRemoveTask; import org.infinispan.server.core.admin.embeddedserver.CacheUpdateConfigurationAttributeTask; import org.infinispan.server.core.admin.embeddedserver.CacheUpdateIndexSchemaTask; import org.infinispan.server.core.admin.embeddedserver.TemplateCreateTask; import org.infinispan.server.core.admin.embeddedserver.TemplateRemoveTask; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class ServerAdminOperationsHandler extends AdminOperationsHandler { public ServerAdminOperationsHandler(ConfigurationBuilderHolder defaultsHolder) { super(generateTasks(defaultsHolder)); } // This method is referenced by quarkus, if method declaration is changed or moved it must be updated in Quarkus // Infinispan as well private static AdminServerTask<?>[] generateTasks(ConfigurationBuilderHolder defaultsHolder) { String includeLoggingResource = System.getProperty("infinispan.server.resource.logging", "true"); if (Boolean.parseBoolean(includeLoggingResource)) { return new AdminServerTask[]{ new CacheCreateTask(defaultsHolder), new CacheGetOrCreateTask(defaultsHolder), new CacheNamesTask(), new CacheRemoveTask(), new CacheReindexTask(), new CacheUpdateConfigurationAttributeTask(), new CacheUpdateIndexSchemaTask(), new LoggingSetTask(), new LoggingRemoveTask(), new TemplateCreateTask(), new TemplateRemoveTask() }; } else { return generateTasksWithoutLogging(defaultsHolder); } } // This method is referenced by quarkus, if method declaration is changed or moved it must be updated in Quarkus // Infinispan as well private static AdminServerTask<?>[] generateTasksWithoutLogging(ConfigurationBuilderHolder defaultsHolder) { return new AdminServerTask[]{ new CacheCreateTask(defaultsHolder), new CacheGetOrCreateTask(defaultsHolder), new CacheNamesTask(), new CacheRemoveTask(), new CacheReindexTask(), new CacheUpdateConfigurationAttributeTask(), new CacheUpdateIndexSchemaTask(), new TemplateCreateTask(), new TemplateRemoveTask() }; } }
2,796
43.396825
115
java
null
infinispan-main/server/runtime/src/main/java/org/infinispan/server/tasks/admin/CacheGetOrCreateTask.java
package org.infinispan.server.tasks.admin; import java.util.EnumSet; import java.util.List; import java.util.Map; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.manager.EmbeddedCacheManager; /** * Admin operation to create a cache * Parameters: * <ul> * <li><strong>name</strong> the name of the cache to create</li> * <li><strong>template</strong> the name of the template to use</li> * <li><strong>configuration</strong> the XML configuration to use</li> * <li><strong>flags</strong> any flags, e.g. PERMANENT</li> * </ul> * * @author Tristan Tarrant * @since 9.2 */ public class CacheGetOrCreateTask extends CacheCreateTask { public CacheGetOrCreateTask(ConfigurationBuilderHolder defaultsHolder) { super(defaultsHolder); } @Override public String getTaskContextName() { return "cache"; } @Override public String getTaskOperationName() { return "getorcreate"; } @Override protected Void execute(EmbeddedCacheManager cacheManager, Map<String, List<String>> parameters, EnumSet<CacheContainerAdmin.AdminFlag> flags) { String name = requireParameter(parameters, "name"); String template = getParameter(parameters, "template"); String configuration = getParameter(parameters, "configuration"); if (configuration != null) { Configuration config = getConfigurationBuilder(name, configuration).build(); cacheManager.administration().withFlags(flags).getOrCreateCache(name, config); } else { cacheManager.administration().withFlags(flags).getOrCreateCache(name, template); } return null; } }
1,798
31.125
146
java
null
infinispan-main/server/runtime/src/main/java/org/infinispan/server/tasks/admin/LoggingSetTask.java
package org.infinispan.server.tasks.admin; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.LoggerConfig; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.actions.SecurityActions; import org.infinispan.server.Server; import org.infinispan.server.core.admin.AdminServerTask; import org.infinispan.tasks.TaskExecutionMode; /** * Admin operation to add/modify a logger * * @author Tristan Tarrant * @since 11.0 */ public class LoggingSetTask extends AdminServerTask<byte[]> { private static final Set<String> PARAMETERS = Stream.of("loggerName", "level", "appenders", "create").collect(Collectors.toSet()); @Override public String getTaskContextName() { return "logging"; } @Override public String getTaskOperationName() { return "set"; } @Override public TaskExecutionMode getExecutionMode() { return TaskExecutionMode.ALL_NODES; } @Override public Set<String> getParameters() { return PARAMETERS; } @Override protected byte[] execute(EmbeddedCacheManager cacheManager, Map<String, List<String>> parameters, EnumSet<CacheContainerAdmin.AdminFlag> adminFlags) { SecurityActions.checkPermission(cacheManager, AuthorizationPermission.ADMIN); String loggerName = getParameter(parameters, "loggerName"); List<String> appenders = parameters.get("appenders"); LoggerContext context = (LoggerContext) LogManager.getContext(false); String pLevel = getParameter(parameters, "level"); Level level; if (pLevel == null) { level = null; } else { level = Level.getLevel(pLevel); if (level == null) { throw Server.log.invalidLevel(pLevel); } } Configuration configuration = context.getConfiguration(); LoggerConfig loggerConfig = loggerName == null ? configuration.getRootLogger() : configuration.getLoggerConfig(loggerName); if (level == null) { // If no level was specified use the existing one or the root one level = loggerConfig.getLevel(); } LoggerConfig specificConfig = loggerConfig; if (loggerName != null && !loggerConfig.getName().equals(loggerName)) { specificConfig = new LoggerConfig(loggerName, level, true); specificConfig.setParent(loggerConfig); configuration.addLogger(loggerName, specificConfig); } if (appenders != null) { Map<String, Appender> rootAppenders = context.getRootLogger().getAppenders(); Map<String, Appender> loggerAppenders = specificConfig.getAppenders(); // Remove all unwanted appenders loggerAppenders.keySet().removeAll(appenders); for (String appender : loggerAppenders.keySet()) { specificConfig.removeAppender(appender); } // Add any missing appenders for (String appender : appenders) { Appender app = rootAppenders.get(appender); if (app != null) { specificConfig.addAppender(app, level, null); } else { throw Server.log.unknownAppender(appender); } } } specificConfig.setLevel(level); context.updateLoggers(); return null; } }
3,777
33.981481
153
java
null
infinispan-main/server/runtime/src/main/java/org/infinispan/server/tasks/admin/LoggingRemoveTask.java
package org.infinispan.server.tasks.admin; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.actions.SecurityActions; import org.infinispan.server.core.admin.AdminServerTask; import org.infinispan.tasks.TaskExecutionMode; /** * Admin operation to remove a logger * * @author Tristan Tarrant * @since 11.0 */ public class LoggingRemoveTask extends AdminServerTask<byte[]> { @Override public String getTaskContextName() { return "logging"; } @Override public String getTaskOperationName() { return "remove"; } @Override public TaskExecutionMode getExecutionMode() { return TaskExecutionMode.ALL_NODES; } @Override public Set<String> getParameters() { return Collections.singleton("loggerName"); } @Override protected byte[] execute(EmbeddedCacheManager cacheManager, Map<String, List<String>> parameters, EnumSet<CacheContainerAdmin.AdminFlag> adminFlags) { SecurityActions.checkPermission(cacheManager, AuthorizationPermission.ADMIN); String loggerName = requireParameter(parameters, "loggerName"); LoggerContext logContext = (LoggerContext) LogManager.getContext(false); Configuration configuration = logContext.getConfiguration(); if (configuration.getLoggers().containsKey(loggerName)) { configuration.removeLogger(loggerName); logContext.updateLoggers(); } else { throw new NoSuchElementException(loggerName); } return null; } }
1,951
30.483871
153
java
null
infinispan-main/server/runtime/src/main/java/org/infinispan/server/tasks/admin/CacheCreateTask.java
package org.infinispan.server.tasks.admin; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; /** * Admin operation to create a cache. This Parameters: * <ul> * <li><strong>name</strong> the name of the cache to create</li> * <li><strong>flags</strong> any flags, e.g. PERMANENT</li> * </ul> * * @author Tristan Tarrant * @since 10.0 */ public class CacheCreateTask extends org.infinispan.server.core.admin.embeddedserver.CacheCreateTask { final protected ConfigurationBuilderHolder defaultsHolder; public CacheCreateTask(ConfigurationBuilderHolder defaultsHolder) { this.defaultsHolder = defaultsHolder; } protected ConfigurationBuilder getConfigurationBuilder(String name, String configuration) { Configuration cfg = super.getConfigurationBuilder(name, configuration).build(); // Rebase the configuration on top of the defaults ConfigurationBuilder defaultCfg = defaultsHolder.getNamedConfigurationBuilders().get("org.infinispan." + cfg.clustering().cacheMode().name()); ConfigurationBuilder rebased = new ConfigurationBuilder().read(defaultCfg.build()); rebased.read(cfg); return rebased; } }
1,314
38.848485
148
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/RestTestSCI.java
package org.infinispan.rest; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.rest.search.entity.Address; import org.infinispan.rest.search.entity.Gender; import org.infinispan.rest.search.entity.Person; import org.infinispan.rest.search.entity.PhoneNumber; @AutoProtoSchemaBuilder( includeClasses = { Address.class, Gender.class, Person.class, PhoneNumber.class, TestClass.class }, schemaFileName = "test.rest.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.test.rest", service = false ) public interface RestTestSCI extends SerializationContextInitializer { RestTestSCI INSTANCE = new RestTestSCIImpl(); }
851
31.769231
70
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/Http2Test.java
package org.infinispan.rest; import static org.infinispan.client.rest.configuration.Protocol.HTTP_11; import static org.infinispan.client.rest.configuration.Protocol.HTTP_20; import static org.infinispan.util.concurrent.CompletionStages.join; import java.util.concurrent.CompletionStage; import org.assertj.core.api.Assertions; 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.dataconversion.MediaType; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.test.security.TestCertificates; import org.infinispan.commons.util.Util; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import io.netty.util.CharsetUtil; /** * Most of the REST Server functionality is tested elsewhere. We can do that since * most of the implementation is exactly the same for both HTTP/1.1 and HTTP/2.0. Here we just do some basic sanity tests. * * @author Sebastian Łaskawiec */ @Test(groups = "functional", testName = "rest.Http2Test") public final class Http2Test extends AbstractInfinispanTest { private RestClient client; private RestServerHelper restServer; @AfterMethod(alwaysRun = true) public void afterMethod() { if (restServer != null) { restServer.stop(); } Util.close(client); } @Test public void shouldUseHTTP1WithALPN() { secureUpgradeTest(HTTP_11); } @Test public void shouldUseHTTP2WithALPN() { secureUpgradeTest(Protocol.HTTP_20); } @Test public void shouldUseHTTP2WithUpgrade() { clearTextUpgrade(false); } @Test public void shouldUseHTTP2WithPriorKnowledge() { clearTextUpgrade(true); } @Test public void shouldReportErrorCorrectly() { restServer = RestServerHelper.defaultRestServer() .withKeyStore(TestCertificates.certificate("server"), TestCertificates.KEY_PASSWORD, TestCertificates.KEYSTORE_TYPE) .withTrustStore(TestCertificates.certificate("trust"), TestCertificates.KEY_PASSWORD, TestCertificates.KEYSTORE_TYPE) .start(TestResourceTracker.getCurrentTestShortName()); RestClientConfigurationBuilder config = new RestClientConfigurationBuilder(); config.addServer().host(restServer.getHost()).port(restServer.getPort()) .protocol(HTTP_20).priorKnowledge(true) .security().ssl().enable() .trustStoreFileName(TestCertificates.certificate("ca")).trustStorePassword(TestCertificates.KEY_PASSWORD).trustStoreType(TestCertificates.KEYSTORE_TYPE) .keyStoreFileName(TestCertificates.certificate("client")).keyStorePassword(TestCertificates.KEY_PASSWORD).keyStoreType(TestCertificates.KEYSTORE_TYPE) .hostnameVerifier((hostname, session) -> true); client = RestClient.forConfiguration(config.build()); CompletionStage<RestResponse> response = client.raw().get("/invalid"); ResponseAssertion.assertThat(response).isNotFound(); } @Test public void shouldUseHTTP1() { restServer = RestServerHelper.defaultRestServer().start(TestResourceTracker.getCurrentTestShortName()); RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.addServer().host(restServer.getHost()).port(restServer.getPort()).protocol(HTTP_11); client = RestClient.forConfiguration(builder.build()); CompletionStage<RestResponse> response = client.cacheManager("default").info(); ResponseAssertion.assertThat(response).isOk(); RestEntity value = RestEntity.create(MediaType.APPLICATION_OCTET_STREAM, "test".getBytes(CharsetUtil.UTF_8)); response = client.cache("defaultcache").put("test", value); Assertions.assertThat(join(response).getStatus()).isEqualTo(204); Assertions.assertThat(restServer.getCacheManager().getCache().size()).isEqualTo(1); } private void clearTextUpgrade(boolean previousKnowledge) { restServer = RestServerHelper.defaultRestServer().start(TestResourceTracker.getCurrentTestShortName()); RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.addServer().host(restServer.getHost()).port(restServer.getPort()) .priorKnowledge(previousKnowledge).protocol(Protocol.HTTP_20); client = RestClient.forConfiguration(builder.build()); CompletionStage<RestResponse> response = client.cacheManager("default").info(); ResponseAssertion.assertThat(response).isOk(); RestEntity value = RestEntity.create(MediaType.APPLICATION_OCTET_STREAM, "test".getBytes(CharsetUtil.UTF_8)); response = client.cache("defaultcache").post("test", value); Assertions.assertThat(join(response).getStatus()).isEqualTo(204); Assertions.assertThat(restServer.getCacheManager().getCache().size()).isEqualTo(1); } private void secureUpgradeTest(Protocol choice) { //given restServer = RestServerHelper.defaultRestServer() .withKeyStore(TestCertificates.certificate("server"), TestCertificates.KEY_PASSWORD, TestCertificates.KEYSTORE_TYPE) .start(TestResourceTracker.getCurrentTestShortName()); RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.addServer().host(restServer.getHost()).port(restServer.getPort()).protocol(choice) .security().ssl().trustStoreFileName(TestCertificates.certificate("ca")).trustStorePassword(TestCertificates.KEY_PASSWORD).trustStoreType(TestCertificates.KEYSTORE_TYPE) .hostnameVerifier((hostname, session) -> true); client = RestClient.forConfiguration(builder.build()); RestEntity value = RestEntity.create(MediaType.APPLICATION_OCTET_STREAM, "test".getBytes(CharsetUtil.UTF_8)); CompletionStage<RestResponse> response = client.cache("defaultcache").post("test", value); //then ResponseAssertion.assertThat(response).isOk(); Assertions.assertThat(restServer.getCacheManager().getCache().size()).isEqualTo(1); } }
6,408
43.2
181
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/AuthenticationTest.java
package org.infinispan.rest; import static io.netty.handler.codec.http.HttpHeaderNames.AUTHORIZATION; import static java.util.Collections.singletonMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import java.io.IOException; import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import javax.security.auth.Subject; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.rest.authentication.SecurityDomain; import org.infinispan.rest.authentication.impl.BasicAuthenticator; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.AuthenticationTest") public class AuthenticationTest extends AbstractInfinispanTest { public static final String REALM = "ApplicationRealm"; private static final String URL = String.format("/rest/v2/caches/%s/%s", "default", "test"); private RestClient client; private RestServerHelper restServer; @BeforeMethod(alwaysRun = true) public void beforeMethod() { SecurityDomain securityDomainMock = mock(SecurityDomain.class); Subject user = TestingUtil.makeSubject("test"); doReturn(user).when(securityDomainMock).authenticate(eq("test"), eq("test")); BasicAuthenticator basicAuthenticator = new BasicAuthenticator(securityDomainMock, REALM); restServer = RestServerHelper.defaultRestServer().withAuthenticator(basicAuthenticator).start(TestResourceTracker.getCurrentTestShortName()); RestClientConfigurationBuilder configurationBuilder = new RestClientConfigurationBuilder(); configurationBuilder.addServer().host(restServer.getHost()).port(restServer.getPort()); client = RestClient.forConfiguration(configurationBuilder.build()); } @AfterMethod(alwaysRun = true) public void afterMethod() throws IOException { restServer.clear(); if (restServer != null) { restServer.stop(); client.close(); } } @Test public void shouldAuthenticateWhenProvidingProperCredentials() { Map<String, String> headers = singletonMap(AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString("test:test".getBytes())); CompletionStage<RestResponse> response = client.raw().head(URL, headers); ResponseAssertion.assertThat(response).isNotFound(); } @Test public void shouldRejectNotValidAuthorizationString() { Map<String, String> headers = new HashMap<>(); headers.put(AUTHORIZATION.toString(), "Invalid string"); CompletionStage<RestResponse> response = client.raw().get(URL, headers); ResponseAssertion.assertThat(response).isUnauthorized(); } @Test public void shouldRejectNoAuthentication() { CompletionStage<RestResponse> response = client.raw().get(URL); //then ResponseAssertion.assertThat(response).isUnauthorized(); } @Test public void shouldAllowHealthAnonymously() { CompletionStage<RestResponse> response = client.cacheManager("default").healthStatus(); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType("text/plain"); ResponseAssertion.assertThat(response).hasReturnedText("HEALTHY"); } }
3,781
38.395833
147
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/TestModule.java
package org.infinispan.rest; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.lifecycle.ModuleLifecycle; /** * {@link InfinispanModule} annotation is required for component annotation processing */ @InfinispanModule(name = "server-rest-tests", requiredModules = {"server-rest"}) public class TestModule implements ModuleLifecycle { }
373
30.166667
86
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/TestClass.java
package org.infinispan.rest; import java.io.Serializable; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.dataconversion.internal.JsonSerialization; import org.infinispan.protostream.annotations.ProtoField; public class TestClass implements Serializable, JsonSerialization { private String name; @ProtoField(number = 1) public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "TestClass{" + "name='" + name + '\'' + '}'; } @Override public Json toJson() { return Json.object() .set("_type", TestClass.class.getName()) .set("name", name); } }
784
20.805556
72
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/ServerRestTestBlockHoundIntegration.java
package org.infinispan.rest; import org.kohsuke.MetaInfServices; import com.arjuna.ats.internal.arjuna.coordinator.ReaperThread; import com.arjuna.ats.internal.arjuna.coordinator.ReaperWorkerThread; import reactor.blockhound.BlockHound; import reactor.blockhound.integration.BlockHoundIntegration; @MetaInfServices public class ServerRestTestBlockHoundIntegration implements BlockHoundIntegration { @Override public void applyTo(BlockHound.Builder builder) { // Let arjuna block - sometimes its thread will be put in our non blocking thread group builder.allowBlockingCallsInside(ReaperThread.class.getName(), "run"); builder.allowBlockingCallsInside(ReaperWorkerThread.class.getName(), "run"); // `DistributedStream` is blocking. builder.markAsBlocking("io.reactivex.rxjava3.internal.operators.flowable.BlockingFlowableIterable$BlockingFlowableIterator", "next", "()Ljava/lang/Object;"); builder.markAsBlocking("io.reactivex.rxjava3.internal.operators.flowable.BlockingFlowableIterable$BlockingFlowableIterator", "hasNext", "()Z"); } }
1,087
44.333333
163
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/CertificateTest.java
package org.infinispan.rest; import static org.testng.AssertJUnit.assertEquals; import java.util.Collections; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.test.security.TestCertificates; import org.infinispan.rest.authentication.impl.ClientCertAuthenticator; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.CertificateTest") public class CertificateTest extends AbstractInfinispanTest { private RestClient client; private RestServerHelper restServer; @AfterSuite public void afterSuite() { restServer.stop(); } @AfterMethod public void afterMethod() throws Exception { if (restServer != null) { restServer.stop(); } client.close(); } @Test public void shouldAllowProperCertificate() throws Exception { restServer = RestServerHelper.defaultRestServer() .withAuthenticator(new ClientCertAuthenticator()) .withKeyStore(TestCertificates.certificate("server"), TestCertificates.KEY_PASSWORD, TestCertificates.KEYSTORE_TYPE) .withTrustStore(TestCertificates.certificate("trust"), TestCertificates.KEY_PASSWORD, TestCertificates.KEYSTORE_TYPE) .withClientAuth() .start(TestResourceTracker.getCurrentTestShortName()); RestClientConfigurationBuilder config = new RestClientConfigurationBuilder(); config.security().ssl().enable() .trustStoreFileName(TestCertificates.certificate("ca")) .trustStorePassword(TestCertificates.KEY_PASSWORD) .trustStoreType(TestCertificates.KEYSTORE_TYPE) .keyStoreFileName(TestCertificates.certificate("client")) .keyStorePassword(TestCertificates.KEY_PASSWORD) .keyStoreType(TestCertificates.KEYSTORE_TYPE) .hostnameVerifier((hostname, session) -> true) .addServer().host("localhost").port(restServer.getPort()); client = RestClient.forConfiguration(config.build()); //when CompletionStage<RestResponse> response = client.raw().get("/rest/v2/caches/default/test", Collections.emptyMap()); //then assertEquals(404, response.toCompletableFuture().get(10, TimeUnit.MINUTES).getStatus()); } }
2,712
38.897059
129
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/PipelineInitializationTest.java
package org.infinispan.rest; import static java.util.concurrent.CompletableFuture.supplyAsync; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.assertFalse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.stream.Collectors; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Test Netty pipeline initialization with multiple simultaneous clients. */ @Test(groups = "functional", testName = "rest.PipelineInitializationTest") public class PipelineInitializationTest extends AbstractInfinispanTest { private RestServerHelper restServer; private RestClient client1, client2; @BeforeMethod(alwaysRun = true) public void beforeMethod() { restServer = RestServerHelper.defaultRestServer().start(TestResourceTracker.getCurrentTestShortName()); RestClientConfigurationBuilder configurationBuilder = new RestClientConfigurationBuilder(); configurationBuilder.addServer().host(restServer.getHost()).port(restServer.getPort()); client1 = RestClient.forConfiguration(configurationBuilder.build()); client2 = RestClient.forConfiguration(configurationBuilder.build()); } @AfterMethod(alwaysRun = true) public void afterMethod() throws IOException { restServer.clear(); if (restServer != null) { restServer.stop(); client1.close(); client2.close(); } } private Supplier<Integer> createTask(RestClient client, CountDownLatch latch) { return () -> { try { latch.await(); } catch (InterruptedException ignored) { } RestResponse response = await(client.caches()); return response.getStatus(); }; } @Test public void testInitializationRules() throws InterruptedException, ExecutionException { int numTasks = 5; ExecutorService executorService = Executors.newFixedThreadPool(numTasks); CountDownLatch startLatch = new CountDownLatch(1); List<Supplier<Integer>> suppliers = new ArrayList<>(); for (int i = 0; i < numTasks; i++) { RestClient client = i % 2 == 0 ? client1 : client2; suppliers.add(createTask(client, startLatch)); } List<CompletableFuture<Integer>> results = suppliers.stream().map(s -> supplyAsync(s, executorService)) .collect(Collectors.toList()); startLatch.countDown(); executorService.shutdown(); assertTrue(executorService.awaitTermination(5, TimeUnit.SECONDS)); for (CompletableFuture<Integer> result : results) { assertFalse(result.isCompletedExceptionally()); assertEquals((int) result.get(), 200); } } }
3,529
35.020408
109
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/expiration/DistributedQueryExpiredEntitiesTest.java
package org.infinispan.rest.expiration; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import static org.testng.AssertJUnit.assertFalse; import java.io.IOException; import java.util.List; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import org.assertj.core.api.Assertions; import org.infinispan.Cache; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.commons.time.ControlledTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.model.Game; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.expiration.DistributedQueryExpiredEntitiesTest") @TestForIssue(jiraKey = "ISPN-14119") public class DistributedQueryExpiredEntitiesTest extends MultipleCacheManagersTest { private static final String CACHE_NAME = "games"; private static final int TIME = 100; private static final ControlledTimeService timeService = new ControlledTimeService(); private RestServerHelper restServer; private RestClient restClient; @Override protected void createCacheManagers() { GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); ConfigurationBuilder config = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); createClusteredCaches(3, global, config, true, "default"); EmbeddedCacheManager cacheManager = cacheManagers.get(0); // use the first one TestingUtil.replaceComponent(cacheManager, TimeService.class, timeService, true); Cache<String, String> metadataCache = cacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.putIfAbsent(Game.GameSchema.INSTANCE.getProtoFileName(), Game.GameSchema.INSTANCE.getProtoFile()); assertFalse(metadataCache.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX)); config.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); config.expiration() .lifespan(TIME, TimeUnit.MILLISECONDS) .maxIdle(TIME, TimeUnit.MILLISECONDS); config.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("Game"); config.statistics().enable(); cacheManager.createCache(CACHE_NAME, config.build()); restServer = new RestServerHelper(cacheManager); restServer.start(TestResourceTracker.getCurrentTestShortName()); restClient = RestClient.forConfiguration(new RestClientConfigurationBuilder().addServer() .host(restServer.getHost()).port(restServer.getPort()) .build()); } @Test public void testQueryExpiredEntities() throws Exception { RestCacheClient cacheClient = restClient.cache(CACHE_NAME); Json game = Json.object() .set("_type", "Game") .set("name", "Ultima IV: Quest of the Avatar") .set("description", "It is the first in the \"Age of Enlightenment\" trilogy ..."); CompletionStage<RestResponse> response = cacheClient.put( "ultima-iv", RestEntity.create(MediaType.APPLICATION_JSON, game.toString())); assertThat(response).isOk(); response = cacheClient.query("from Game g where g.description : 'enlightenment'", 5, 0); assertThat(response).isOk(); Json body = Json.read(response.toCompletableFuture().get().getBody()); List<?> hits = (List<?>) body.at("hits").getValue(); Assertions.assertThat(hits).isNotEmpty(); timeService.advance(TIME * 2); response = cacheClient.query("from Game g where g.description : 'enlightenment'", 5, 0); assertThat(response).isOk(); body = Json.read(response.toCompletableFuture().get().getBody()); hits = (List<?>) body.at("hits").getValue(); Assertions.assertThat(hits).isEmpty(); } @AfterClass(alwaysRun = true) public void tearDown() throws Exception { try { restClient.close(); } catch (IOException ex) { // ignore it } finally { restServer.stop(); } } }
5,108
40.877049
129
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/profiling/BenchmarkHttpClient.java
package org.infinispan.rest.profiling; import java.io.IOException; import java.util.Random; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.configuration.RestClientConfiguration; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.test.Eventually; import org.infinispan.commons.util.Util; import io.netty.util.CharsetUtil; /** * Benchmarking HTTP/1.1 and HTTP/2 is always comparing apples to bananas. Those protocols are totally different and it * doesn't really whether we will use the same or other clients. * <p> * Unfortunately currently there is no good support for HTTP/2 with TLS/ALPN clients. The only implementation which was * reasonably good in testing was Netty (even though a lot of boilerplate code had to be generated). On the other hand * HTTP/1.1 is tested using Jetty client. This client unifies the API for both of them. */ public class BenchmarkHttpClient { private static final RestEntity CACHE_VALUE = RestEntity.create(MediaType.APPLICATION_OCTET_STREAM, "test".getBytes(CharsetUtil.UTF_8)); private final RestCacheClient cacheClient; private final ExecutorCompletionService executorCompletionService; private final ExecutorService executor; private final RestClient client; public BenchmarkHttpClient(RestClientConfiguration configuration, int threads) { client = RestClient.forConfiguration(configuration); cacheClient = client.cache("default"); executor = Executors.newFixedThreadPool(threads); executorCompletionService = new ExecutorCompletionService(executor); } public void performGets(int pertentageOfMisses, int numberOfGets, String existingKey, String nonExistingKey) throws Exception { Random r = ThreadLocalRandom.current(); AtomicInteger count = new AtomicInteger(); for (int i = 0; i < numberOfGets; ++i) { String key = r.nextInt(100) < pertentageOfMisses ? nonExistingKey : existingKey; executorCompletionService.submit(() -> { count.incrementAndGet(); cacheClient.get(key).whenComplete((resp, e) -> count.decrementAndGet()); return 1; }); } Eventually.eventually(() -> count.get() == 0); } public void performPuts(int numberOfInserts) { AtomicInteger count = new AtomicInteger(); for (int i = 0; i < numberOfInserts; ++i) { String randomKey = Util.threadLocalRandomUUID().toString(); executorCompletionService.submit(() -> { count.incrementAndGet(); cacheClient.post(randomKey, CACHE_VALUE).whenComplete((response, e) -> count.decrementAndGet()); return 1; }); } Eventually.eventually(() -> count.get() == 0); } public void stop() throws IOException { client.close(); executor.shutdownNow(); } }
3,208
39.620253
139
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/profiling/Http11VsHttp20Benchmark.java
package org.infinispan.rest.profiling; import java.util.concurrent.TimeUnit; import org.infinispan.client.rest.configuration.Protocol; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.test.security.TestCertificates; import org.infinispan.rest.helper.RestServerHelper; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OperationsPerInvocation; 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 org.testng.annotations.Test; import io.netty.util.internal.logging.InternalLoggerFactory; import io.netty.util.internal.logging.JdkLoggerFactory; /** * This benchmark checks how faster is HTTP/2 compared to HTTP/1.1 * * @author Sebastian Łaskawiec */ @Test(testName = "rest.profiling.Http11VsHttp20Benchmark") public class Http11VsHttp20Benchmark { private static final int MEASUREMENT_ITERATIONS_COUNT = 10; private static final int WARMUP_ITERATIONS_COUNT = 10; @Test public void performHttp11VsHttp20Test() throws Exception { Options opt = new OptionsBuilder() .include(this.getClass().getName() + ".*") .mode(Mode.AverageTime) .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.Benchmark) public static class BenchmarkState { private final String EXISTING_KEY = "existing_key"; private final String NON_EXISTING_KEY = "non_existing_key"; @Param({"1", "2", "4", "8"}) public int httpClientThreads; @Param({"true", "false"}) public boolean useTLS; @Param({"true", "false"}) public boolean useHttp2; private RestServerHelper restServer; private BenchmarkHttpClient client; @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"); restServer = RestServerHelper.defaultRestServer(); if (useTLS) { restServer.withKeyStore(TestCertificates.certificate("server"), TestCertificates.KEY_PASSWORD, TestCertificates.KEYSTORE_TYPE); } restServer.start(this.getClass().getSimpleName()); restServer.getCacheManager().getCache().put(EXISTING_KEY, "test"); RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.addServer().host(restServer.getHost()).port(restServer.getPort()); if (useTLS) { builder.security().ssl().trustStoreFileName(TestCertificates.certificate("ca")).trustStorePassword(TestCertificates.KEY_PASSWORD) .keyStoreFileName(TestCertificates.certificate("client")).keyStorePassword(TestCertificates.KEY_PASSWORD); } builder.protocol(useHttp2 ? Protocol.HTTP_20 : Protocol.HTTP_11); client = new BenchmarkHttpClient(builder.build(), httpClientThreads); } @TearDown public void tearDown() throws Exception { restServer.stop(); client.stop(); } @Benchmark @OperationsPerInvocation(100) public void measure_put() throws Exception { if (useHttp2 && httpClientThreads > 1) { return; } client.performPuts(100); } @Benchmark @OperationsPerInvocation(100) public void measure_get() throws Exception { if (useHttp2 && httpClientThreads > 1) { return; } client.performGets(0, 100, EXISTING_KEY, NON_EXISTING_KEY); } } }
4,388
34.682927
141
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/profiling/MediaTypeParsingBenchmark.java
package org.infinispan.rest.profiling; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.infinispan.commons.dataconversion.MediaType; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; /** * This benchmark tests the performance of media type parsing * * @author Dan Berindei */ public class MediaTypeParsingBenchmark { private static final int MEASUREMENT_ITERATIONS_COUNT = 10; private static final int WARMUP_ITERATIONS_COUNT = 10; public static void main(String[] args) throws Exception { Options opt = new OptionsBuilder() .include(MediaTypeParsingBenchmark.class.getName() + ".State.*") // .include(MediaTypeParsingBenchmark.class.getName() + ".State.parseOneQuotedParameter") .mode(Mode.AverageTime) .timeUnit(TimeUnit.NANOSECONDS) .warmupIterations(WARMUP_ITERATIONS_COUNT) .measurementIterations(MEASUREMENT_ITERATIONS_COUNT) .threads(1) .forks(3) .shouldFailOnError(true) // .jvmArgsAppend("-agentpath:/home/dan/Tools/async-profiler/build/libasyncProfiler.so=start,file=profile-%t.svg") // .addProfiler("perfasm") .build(); new Runner(opt).run(); } @org.openjdk.jmh.annotations.State(Scope.Benchmark) public static class State { private final String mediaTypeNoParameter = "application/json"; private final String mediaTypeOneQuotedParameter = "application/json; charset=\"UTF-8\""; private String mediaTypeOneParameter = "application/x-java-object; type=ByteArray"; private String mediaTypeTwoParameters = "application/x-java-object; q=0.2; type=java.lang.Integer"; private String mediaTypeList = String.join(", ", mediaTypeNoParameter, mediaTypeOneParameter, mediaTypeOneQuotedParameter, mediaTypeTwoParameters); @Benchmark @OperationsPerInvocation(100) public MediaType parseNoParameter() throws Exception { return MediaType.fromString(mediaTypeNoParameter); } @Benchmark @OperationsPerInvocation(100) public MediaType parseOneParameter() throws Exception { return MediaType.fromString(mediaTypeOneParameter); } @Benchmark @OperationsPerInvocation(100) public MediaType parseOneQuotedParameter() throws Exception { return MediaType.fromString(mediaTypeOneQuotedParameter); } @Benchmark @OperationsPerInvocation(100) public MediaType parseTwoParameters() throws Exception { return MediaType.fromString(mediaTypeTwoParameters); } @Benchmark @OperationsPerInvocation(100) public List<MediaType> parseList() throws Exception { return MediaType.parseList(mediaTypeList).collect(Collectors.toList()); } } }
3,145
36.452381
128
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/cachemanager/RestCacheManagerTest.java
package org.infinispan.rest.cachemanager; import static org.mockito.Mockito.never; import static org.testng.Assert.assertEquals; import java.util.Map; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.framework.impl.SimpleRequest; import org.infinispan.server.core.CacheInfo; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.mockito.Mockito; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * @since 9.2 */ @Test(groups = "functional", testName = "rest.RestCacheManagerTest") public class RestCacheManagerTest extends SingleCacheManagerTest { @BeforeClass public void prepare() { Configuration config = new ConfigurationBuilder().build(); cacheManager.createCache("cache1", config); cacheManager.createCache("cache2", config); } @Test public void shouldReuseEncodedCaches() { EmbeddedCacheManager embeddedCacheManager = Mockito.spy(cacheManager); RestCacheManager<Object> restCacheManager = new RestCacheManager<>(embeddedCacheManager, c -> Boolean.FALSE); Map<String, CacheInfo<Object, Object>> knownCaches = TestingUtil.extractField(restCacheManager, "knownCaches"); // Request cache by simple name SimpleRequest request = new SimpleRequest.Builder().setPath("/test").build(); restCacheManager.getCache("cache1", request); restCacheManager.getCache("cache2", request); // Verify they are stored internally assertEquals(knownCaches.size(), 2); assertEquals(cachesSize(knownCaches.get("cache1")), 1); assertEquals(cachesSize(knownCaches.get("cache2")), 1); // Requesting again should not cause interaction with the cache manager Mockito.reset(embeddedCacheManager); restCacheManager.getCache("cache1", request); restCacheManager.getCache("cache2", request); Mockito.verify(embeddedCacheManager, never()).getCache("cache1"); Mockito.verify(embeddedCacheManager, never()).getCache("cache2"); assertEquals(cachesSize(knownCaches.get("cache1")), 1); assertEquals(cachesSize(knownCaches.get("cache2")), 1); // Request caches with a different media type restCacheManager.getCache("cache1", MediaType.MATCH_ALL, MediaType.APPLICATION_JSON, request); restCacheManager.getCache("cache2", MediaType.MATCH_ALL, MediaType.TEXT_PLAIN, request); // Verify they are stored internally assertEquals(knownCaches.size(), 2); assertEquals(cachesSize(knownCaches.get("cache1")), 2); assertEquals(cachesSize(knownCaches.get("cache2")), 2); // Requesting again with same media type but different parameters should not reuse internal instance Mockito.reset(embeddedCacheManager); restCacheManager.getCache("cache1", MediaType.MATCH_ALL, MediaType.fromString("application/json; charset=UTF-8"), request); restCacheManager.getCache("cache2", MediaType.MATCH_ALL, MediaType.fromString("text/plain; charset=SHIFT-JIS"), request); assertEquals(knownCaches.size(), 2); assertEquals(cachesSize(knownCaches.get("cache1")), 3); assertEquals(cachesSize(knownCaches.get("cache2")), 3); Mockito.verify(embeddedCacheManager, never()).getCache("cache1"); Mockito.verify(embeddedCacheManager, never()).getCache("cache2"); // Requesting with same params should reuse restCacheManager.getCache("cache1", MediaType.MATCH_ALL, MediaType.fromString("application/json; charset=UTF-8"), request); restCacheManager.getCache("cache2", MediaType.MATCH_ALL, MediaType.fromString("text/plain; charset=SHIFT-JIS"), request); assertEquals(cachesSize(knownCaches.get("cache1")), 3); assertEquals(cachesSize(knownCaches.get("cache2")), 3); Mockito.verify(embeddedCacheManager, never()).getCache("cache1"); Mockito.verify(embeddedCacheManager, never()).getCache("cache2"); } private int cachesSize(CacheInfo<Object, Object> cacheInfo) { Map<?, ?> caches = TestingUtil.extractField(cacheInfo, "encodedCaches"); return caches.size(); } @Override protected EmbeddedCacheManager createCacheManager() { return TestCacheManagerFactory.createCacheManager(getDefaultStandaloneCacheConfig(false)); } }
4,527
44.28
129
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/metric/MetricsRestTest.java
package org.infinispan.rest.metric; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "unit", testName = "rest.metric.MetricsRestTest") public class MetricsRestTest extends SingleCacheManagerTest { private RestServerHelper restServer; private RestClient restClient; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(); restServer = new RestServerHelper(cacheManager); restServer.start(TestResourceTracker.getCurrentTestShortName()); restClient = RestClient.forConfiguration(new RestClientConfigurationBuilder().addServer() .host(restServer.getHost()).port(restServer.getPort()) .build()); return cacheManager; } @Test public void smokeTest() { String response = restClient.metrics().metrics().toCompletableFuture().join().getBody(); assertThat(response).contains("#"); } @Override protected void teardown() { try { restClient.close(); } catch (IOException ex) { // ignore it } finally { try { restServer.stop(); } finally { super.teardown(); } } } }
1,742
30.125
95
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/logging/RestAccessLoggingTest.java
package org.infinispan.rest.logging; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertTrue; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.layout.PatternLayout; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.test.skip.StringLogAppender; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @since 9.2 */ @Test(groups = "functional", testName = "rest.RestAccessLoggingTest") public class RestAccessLoggingTest extends SingleCacheManagerTest { private static final String LOG_FORMAT = "%X{address} %X{user} [%d{dd/MMM/yyyy:HH:mm:ss Z}] \"%X{method} %m %X{protocol}\" %X{status} %X{requestSize} %X{responseSize} %X{duration} %X{h:User-Agent}"; private StringLogAppender logAppender; private String testShortName; private RestServerHelper restServer; private RestClient restClient; private RestCacheClient cacheClient; @Override protected EmbeddedCacheManager createCacheManager() { return TestCacheManagerFactory.createCacheManager(); } @Override protected void setup() throws Exception { super.setup(); testShortName = TestResourceTracker.getCurrentTestShortName(); logAppender = new StringLogAppender("org.infinispan.REST_ACCESS_LOG", Level.TRACE, t -> t.getName().startsWith("non-blocking-thread-" + testShortName), PatternLayout.newBuilder().withPattern(LOG_FORMAT).build()); logAppender.install(); restServer = new RestServerHelper(cacheManager); restServer.start(TestResourceTracker.getCurrentTestShortName()); RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.addServer().host(restServer.getHost()).port(restServer.getPort()); restClient = RestClient.forConfiguration(builder.create()); cacheClient = restClient.cache("default"); } @Override protected void teardown() { try { logAppender.uninstall(); restClient.close(); restServer.stop(); } catch (Exception ignored) { } super.teardown(); } public void testRestAccessLog() { join(cacheClient.put("key", "value")); restServer.stop(); String logline = logAppender.getLog(0); assertTrue(logline, logline.matches("^127\\.0\\.0\\.1 - \\[\\d+/\\w+/\\d+:\\d+:\\d+:\\d+ [+-]?\\d+] \"PUT /rest/v2/caches/default/key HTTP/1\\.1\" 404 \\d+ \\d+ \\d+ Infinispan/\\p{Graph}+$")); } }
2,910
38.337838
201
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/dataconversion/TextBinaryTranscoderTest.java
package org.infinispan.rest.dataconversion; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.infinispan.commons.dataconversion.DefaultTranscoder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.test.dataconversion.AbstractTranscoderTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.TextBinaryTranscoderTest") public class TextBinaryTranscoderTest extends AbstractTranscoderTest { protected String dataSrc; @BeforeClass(alwaysRun = true) public void setUp() { dataSrc = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; transcoder = new DefaultTranscoder(new ProtoStreamMarshaller()); supportedMediaTypes = transcoder.getSupportedMediaTypes(); } @Override public void testTranscoderTranscode() { Object transcoded = transcoder.transcode(dataSrc, MediaType.TEXT_PLAIN, MediaType.APPLICATION_OCTET_STREAM); assertTrue(transcoded instanceof byte[], "Must be byte[]"); Object transcodedBack = transcoder.transcode(transcoded, MediaType.APPLICATION_OCTET_STREAM, MediaType.TEXT_PLAIN); assertEquals(transcodedBack, dataSrc.getBytes(), "Must be an equal objects"); } }
1,408
41.69697
121
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/dataconversion/TextObjectTranscoderTest.java
package org.infinispan.rest.dataconversion; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.infinispan.commons.dataconversion.DefaultTranscoder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.rest.RestTestSCI; import org.infinispan.test.TestingUtil; 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; @Test(groups = "functional", testName = "rest.TextObjectTranscoderTest") public class TextObjectTranscoderTest 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 DefaultTranscoder(TestingUtil.createProtoStreamMarshaller(RestTestSCI.INSTANCE)); supportedMediaTypes = transcoder.getSupportedMediaTypes(); } @Override public void testTranscoderTranscode() { Object transcoded = transcoder.transcode(dataSrc, MediaType.APPLICATION_OBJECT, MediaType.TEXT_PLAIN); assertEquals(new String((byte[]) transcoded), dataSrc.toString()); transcoded = transcoder.transcode(transcoded, MediaType.APPLICATION_OBJECT, MediaType.TEXT_PLAIN); assertTrue(transcoded instanceof byte[], "Must be byte[]"); } }
1,535
34.72093
108
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/helper/RestServerHelper.java
package org.infinispan.rest.helper; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.registry.InternalCacheRegistry; import org.infinispan.rest.RestServer; import org.infinispan.rest.TestClass; import org.infinispan.rest.authentication.RestAuthenticator; import org.infinispan.rest.configuration.RestServerConfiguration; import org.infinispan.rest.configuration.RestServerConfigurationBuilder; import org.infinispan.server.core.DummyServerManagement; import org.infinispan.server.core.MockProtocolServer; import org.infinispan.server.core.ProtocolServer; import org.infinispan.test.fwk.TestCacheManagerFactory; import java.net.URISyntaxException; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; /** * A small utility class which helps managing REST server. * * @author Sebastian Łaskawiec */ public class RestServerHelper { private final EmbeddedCacheManager cacheManager; private final RestServer restServer = new RestServer(); private final RestServerConfigurationBuilder restServerConfigurationBuilder = new RestServerConfigurationBuilder(); public RestServerHelper(EmbeddedCacheManager cacheManager) { this.cacheManager = cacheManager; try { restServerConfigurationBuilder.host("localhost").port(0).maxContentLength(1_000_000) .staticResources(Paths.get(this.getClass().getResource("/static-test").toURI())); } catch (URISyntaxException ignored) { } } public static RestServerHelper defaultRestServer(String... cachesDefined) { return defaultRestServer(new ConfigurationBuilder(), cachesDefined); } public RestServerConfigurationBuilder serverConfigurationBuilder() { return restServerConfigurationBuilder; } public static RestServerHelper defaultRestServer(ConfigurationBuilder configuration, String... cachesDefined) { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().cacheManagerName("default"); EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(globalBuilder, configuration); cacheManager.getClassAllowList().addClasses(TestClass.class); for (String cacheConfiguration : cachesDefined) { cacheManager.defineConfiguration(cacheConfiguration, configuration.build()); } return new RestServerHelper(cacheManager); } public RestServerHelper withAuthenticator(RestAuthenticator authenticator) { restServerConfigurationBuilder.authentication().authenticator(authenticator); return this; } public RestServerHelper start(String name) { restServerConfigurationBuilder.name(name); Map<String, ProtocolServer> protocolServers = new HashMap<>(); restServer.setServerManagement(new DummyServerManagement(cacheManager, protocolServers), true); restServer.start(restServerConfigurationBuilder.build(), cacheManager); protocolServers.put("DummyProtocol", new MockProtocolServer("DummyProtocol", restServer.getTransport())); return this; } public void clear() { InternalCacheRegistry registry = cacheManager.getGlobalComponentRegistry() .getComponent(InternalCacheRegistry.class); cacheManager.getCacheNames().stream() .filter(cacheName -> !registry.isInternalCache(cacheName)) .filter(cacheManager::isRunning) .forEach(cacheName -> cacheManager.getCache(cacheName).getAdvancedCache().getDataContainer().clear()); } public void stop() { restServer.stop(); cacheManager.stop(); } public int getPort() { return restServer.getPort(); } public RestServerConfiguration getConfiguration() { return restServer.getConfiguration(); } public EmbeddedCacheManager getCacheManager() { return cacheManager; } public String getBasePath() { return String.format("/%s/v2/caches/%s", restServer.getConfiguration().contextPath(), cacheManager.getCacheManagerConfiguration().defaultCacheName().get()); } public RestServerHelper withKeyStore(String keyStorePath, char[] secret, String type) { restServerConfigurationBuilder.ssl().enable(); restServerConfigurationBuilder.ssl() .keyStoreFileName(keyStorePath) .keyStorePassword(secret) .keyStoreType(type); return this; } public RestServerHelper withTrustStore(String trustStorePath, char[] secret, String type) { restServerConfigurationBuilder.ssl().enable(); restServerConfigurationBuilder.ssl() .trustStoreFileName(trustStorePath) .trustStorePassword(secret) .trustStoreType(type); return this; } public RestServerHelper withClientAuth() { restServerConfigurationBuilder.ssl().enable(); restServerConfigurationBuilder.ssl().requireClientAuth(true); return this; } public String getHost() { return restServer.getHost(); } public void ignoreCache(String cacheName) { restServer.getServerStateManager().ignoreCache(cacheName).join(); } public void unignoreCache(String cacheName) { restServer.getServerStateManager().unignoreCache(cacheName).join(); } public RestClient createClient(boolean browser) { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.addServer().host(restServer.getHost()).port(restServer.getPort()); if (browser) { builder.header("User-Agent", "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/112.0"); } return RestClient.forConfiguration(builder.build()); } }
5,913
38.165563
162
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/helper/RestResponses.java
package org.infinispan.rest.helper; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.test.Exceptions; /** * A utility for managing {@link RestResponse}s in tests. * * @author Dan Berindei * @since 10.1 */ public class RestResponses { public static void assertSuccessful(CompletionStage<RestResponse> responseStage) { assertStatus(200, responseStage); } public static void assertNoContent(CompletionStage<RestResponse> responseStage) { assertStatus(204, responseStage); } public static void assertStatus(int expectedStatus, CompletionStage<RestResponse> responseStage) { int status = responseStatus(responseStage); assertEquals(expectedStatus, status); } public static int responseStatus(CompletionStage<RestResponse> responseStage) { try (RestResponse response = sync(responseStage)) { return response.getStatus(); } } public static String responseBody(CompletionStage<RestResponse> responseStage) { try (RestResponse response = sync(responseStage)) { assertEquals(200, response.getStatus()); return response.getBody(); } } public static Json jsonResponseBody(CompletionStage<RestResponse> responseCompletionStage) { return Exceptions.unchecked(() -> Json.read(responseBody(responseCompletionStage))); } private static <T> T sync(CompletionStage<T> stage) { return Exceptions.unchecked(() -> stage.toCompletableFuture().get(10, TimeUnit.SECONDS)); } private static void assertEquals(int expectedStatus, int status) { // Create the AssertionError manually so it works in both TestNG and JUnit if (status != expectedStatus) { throw new AssertionError("Expected: <" + expectedStatus + ">, but was: <" + status + ">"); } } }
1,972
31.883333
101
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/assertion/JsonAssertion.java
package org.infinispan.rest.assertion; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.commons.dataconversion.internal.Json; /** * Assertions on JSON contents. * * @author Dan Berindei * @since 12 */ public class JsonAssertion { String path; private Json node; public JsonAssertion(Json node) { this(node, ""); } public JsonAssertion(Json node, String path) { this.node = node; this.path = path; assertNotNull(path, node); } public JsonAssertion hasProperty(String propertyName) { return new JsonAssertion(node.at(propertyName), propertyPath(propertyName)); } public JsonAssertion hasNullProperty(String propertyName) { hasProperty(propertyName).isNull(); return this; } public JsonAssertion hasNoProperty(String propertyName) { assertFalse(propertyPath(propertyName), node.has(propertyName)); return this; } public void is(int value) { assertEquals(value, node.asInteger()); } public void is(String value) { assertEquals(value, node.asString()); } public void isNull() { assertTrue(path, node.isNull()); } private String propertyPath(String propertyName) { return this.path.isEmpty() ? propertyName : this.path + "." + propertyName; } }
1,469
23.5
82
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/assertion/ResponseAssertion.java
package org.infinispan.rest.assertion; import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static io.netty.handler.codec.http.HttpResponseStatus.CONFLICT; import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static io.netty.handler.codec.http.HttpResponseStatus.FOUND; import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import static io.netty.handler.codec.http.HttpResponseStatus.MOVED_PERMANENTLY; import static io.netty.handler.codec.http.HttpResponseStatus.NOT_ACCEPTABLE; import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; import static io.netty.handler.codec.http.HttpResponseStatus.NOT_MODIFIED; import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpResponseStatus.PERMANENT_REDIRECT; import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE; import static io.netty.handler.codec.http.HttpResponseStatus.SERVICE_UNAVAILABLE; import static io.netty.handler.codec.http.HttpResponseStatus.TEMPORARY_REDIRECT; import static io.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED; import static org.infinispan.rest.RequestHeader.CONTENT_ENCODING_HEADER; import static org.infinispan.rest.ResponseHeader.CACHE_CONTROL_HEADER; import static org.infinispan.rest.ResponseHeader.CONTENT_LENGTH_HEADER; import static org.infinispan.rest.ResponseHeader.CONTENT_TYPE_HEADER; import static org.infinispan.rest.ResponseHeader.DATE_HEADER; import static org.infinispan.rest.ResponseHeader.ETAG_HEADER; import static org.infinispan.rest.ResponseHeader.EXPIRES_HEADER; import static org.infinispan.rest.ResponseHeader.LAST_MODIFIED_HEADER; import static org.infinispan.rest.ResponseHeader.WWW_AUTHENTICATE_HEADER; import static org.testng.AssertJUnit.assertEquals; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.assertj.core.api.Assertions; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.rest.DateUtils; import org.infinispan.commons.util.concurrent.CompletableFutures; public class ResponseAssertion { private final RestResponse response; private ResponseAssertion(RestResponse response) { this.response = Objects.requireNonNull(response, "RestResponse cannot be null!"); } public static ResponseAssertion assertThat(CompletionStage<RestResponse> response) { CompletableFuture<RestResponse> future = response.toCompletableFuture(); boolean completed = CompletableFutures.uncheckedAwait(future, 30, TimeUnit.SECONDS); if (!completed) { Assertions.fail("Timeout obtaining responses"); } return assertThat(future.getNow(null)); } public static ResponseAssertion assertThat(RestResponse response) { return new ResponseAssertion(response); } public ResponseAssertion isOk() { if (response.getStatus() >= OK.code() && response.getStatus() <= NO_CONTENT.code()) { return this; } Assertions.fail("Unexpected error code " + response.getStatus() + ": " + response.getBody()); return this; } public ResponseAssertion isRedirect() { Assertions.assertThat(response.getStatus()).isIn(MOVED_PERMANENTLY.code(), FOUND.code(), TEMPORARY_REDIRECT.code(), PERMANENT_REDIRECT.code()); return this; } public ResponseAssertion doesntExist() { Assertions.assertThat(response.getStatus()).isEqualTo(NOT_FOUND.code()); return this; } public ResponseAssertion hasReturnedText(String text) { Assertions.assertThat(response.getBody()).isEqualTo(text); return this; } public ResponseAssertion hasReturnedText(String... textPossibilities) { String body = response.getBody(); Assertions.assertThat(body).matches(s -> { for (String possible : textPossibilities) { if (s != null && s.equals(possible)) { return true; } } return false; }, "Content: " + body + " doesn't match any of " + Arrays.toString(textPossibilities)); return this; } public ResponseAssertion containsReturnedText(String text) { Assertions.assertThat(response.getBody()).contains(text); return this; } public ResponseAssertion bodyNotEmpty() { Assertions.assertThat(response.getBody()).isNotEmpty(); return this; } public ResponseAssertion hasEtag() { Assertions.assertThat(response.headers().get(ETAG_HEADER.getValue())).isNotNull().isNotEmpty(); return this; } public ResponseAssertion hasNoContent() { Assertions.assertThat(response.getBody()).isEmpty(); return this; } public ResponseAssertion hasNoContentType() { Assertions.assertThat(response.headers().get(CONTENT_TYPE_HEADER.getValue())).isNull(); return this; } public ResponseAssertion hasNoContentEncoding() { Assertions.assertThat(response.headers().get(CONTENT_ENCODING_HEADER.getValue())).isNull(); return this; } public ResponseAssertion hasContentType(String contentType) { Assertions.assertThat(response.getHeader(CONTENT_TYPE_HEADER.getValue()).replace(" ", "")).contains(contentType.replace(" ", "")); return this; } public ResponseAssertion hasContentLength(Integer value) { Assertions.assertThat(response.getHeader(CONTENT_LENGTH_HEADER.getValue())).isEqualTo(value.toString()); return this; } public ResponseAssertion hasContentLength(Long value) { Assertions.assertThat(response.getHeader(CONTENT_LENGTH_HEADER.getValue())).isEqualTo(value.toString()); return this; } public ResponseAssertion hasGzipContentEncoding() { Assertions.assertThat(response.getHeader(CONTENT_ENCODING_HEADER.getValue())).isEqualTo("gzip"); return this; } public ResponseAssertion hasHeaderMatching(String header, String regexp) { Assertions.assertThat(response.getHeader(header)).matches(regexp); return this; } public ResponseAssertion hasHeaderWithValues(String header, String... headers) { List<String> expected = Arrays.stream(headers).map(String::toLowerCase).sorted().collect(Collectors.toList()); List<String> actual = response.headers().get(header).stream().flatMap(s -> Arrays.stream(s.split(","))) .map(String::toLowerCase).sorted().collect(Collectors.toList()); assertEquals(expected, actual); return this; } public ResponseAssertion containsAllHeaders(String... headers) { Assertions.assertThat(response.headers().keySet()).contains(headers); return this; } public ResponseAssertion hasCacheControlHeaders(String... directives) { List<String> valueList = response.headers().get(CACHE_CONTROL_HEADER.getValue()); Assertions.assertThat(valueList).isEqualTo(Arrays.asList(directives)); return this; } public ResponseAssertion hasExtendedHeaders() { Assertions.assertThat(response.headers().get("Cluster-Primary-Owner")).isNotNull().isNotEmpty(); Assertions.assertThat(response.headers().get("Cluster-Node-Name")).isNotNull().isNotEmpty(); Assertions.assertThat(response.headers().get("Cluster-Server-Address")).isNotNull().isNotEmpty(); return this; } public ResponseAssertion isConflicted() { Assertions.assertThat(response.getStatus()).isEqualTo(CONFLICT.code()); return this; } public ResponseAssertion isError() { Assertions.assertThat(response.getStatus()).isEqualTo(INTERNAL_SERVER_ERROR.code()); return this; } public ResponseAssertion isUnauthorized() { Assertions.assertThat(response.getStatus()).isEqualTo(UNAUTHORIZED.code()); Assertions.assertThat(response.headers().get(WWW_AUTHENTICATE_HEADER.getValue())).isNotNull().isNotEmpty(); return this; } public ResponseAssertion isForbidden() { Assertions.assertThat(response.getStatus()).isEqualTo(FORBIDDEN.code()); return this; } public ResponseAssertion isNotFound() { Assertions.assertThat(response.getStatus()).isEqualTo(NOT_FOUND.code()); return this; } public ResponseAssertion isPayloadTooLarge() { Assertions.assertThat(response.getStatus()).isEqualTo(REQUEST_ENTITY_TOO_LARGE.code()); return this; } public ResponseAssertion isNotModified() { Assertions.assertThat(response.getStatus()).isEqualTo(NOT_MODIFIED.code()); return this; } public ResponseAssertion hasContentEqualToFile(String fileName) { try { Path path = Paths.get(getClass().getClassLoader().getResource(fileName).toURI()); byte[] loadedFile = Files.readAllBytes(path); Assertions.assertThat(response.getBodyAsByteArray()).isEqualTo(loadedFile); } catch (Exception e) { throw new AssertionError(e); } return this; } public ResponseAssertion isNotAcceptable() { Assertions.assertThat(response.getStatus()).isEqualTo(NOT_ACCEPTABLE.code()); return this; } public ResponseAssertion isBadRequest() { Assertions.assertThat(response.getStatus()).isEqualTo(BAD_REQUEST.code()); return this; } public ResponseAssertion hasNoCharset() { Assertions.assertThat(response.headers().get(CONTENT_TYPE_HEADER.getValue())).doesNotContain("charset"); return this; } public ResponseAssertion hasReturnedBytes(byte[] bytes) { Assertions.assertThat(response.getBodyAsByteArray()).isEqualTo(bytes); return this; } public ResponseAssertion isServiceUnavailable() { Assertions.assertThat(response.getStatus()).isEqualTo(SERVICE_UNAVAILABLE.code()); return this; } public ResponseAssertion hasMediaType(MediaType[] mediaType) { String contentType = response.getHeader(CONTENT_TYPE_HEADER.getValue()); boolean hasMatches = Arrays.stream(mediaType).anyMatch(m -> MediaType.fromString(contentType).match(m)); Assertions.assertThat(hasMatches).isTrue(); return this; } public ResponseAssertion hasValidDate() { String dateHeader = response.getHeader(DATE_HEADER.getValue()); ZonedDateTime zonedDateTime = DateUtils.parseRFC1123(dateHeader); Assertions.assertThat(zonedDateTime).isNotNull(); return this; } public ResponseAssertion hasLastModified(long timestamp) { String dateHeader = response.getHeader(LAST_MODIFIED_HEADER.getValue()); Assertions.assertThat(dateHeader).isNotNull(); ZonedDateTime zonedDateTime = Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()); String value = DateTimeFormatter.RFC_1123_DATE_TIME.format(zonedDateTime); Assertions.assertThat(value).isEqualTo(dateHeader); return this; } public ResponseAssertion expiresAfter(int expireDuration) { String dateHeader = response.getHeader(DATE_HEADER.getValue()); String expiresHeader = response.getHeader(EXPIRES_HEADER.getValue()); ZonedDateTime date = DateUtils.parseRFC1123(dateHeader); ZonedDateTime expires = DateUtils.parseRFC1123(expiresHeader); ZonedDateTime diff = expires.minus(expireDuration, ChronoUnit.SECONDS); Assertions.assertThat(diff).isEqualTo(date); return this; } public ResponseAssertion hasNoErrors() { hasJson().hasProperty("error").isNull(); return this; } public JsonAssertion hasJson() { Json node = Json.read(response.getBody()); return new JsonAssertion(node); } }
12,128
38
149
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/SearchCountClusteredTest.java
package org.infinispan.rest.search; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.stream.LongStream; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests for the query "hit_count" for all types of query. * * @since 12.1 */ @Test(groups = "functional", testName = "rest.search.SearchCountClusteredTest") public class SearchCountClusteredTest extends MultiNodeRestTest { static final int INDEXED_ENTRIES = 300; private static final int NOT_INDEXED_ENTRIES = 200; static final String INDEXED_CACHE = "indexed"; static final String NOT_INDEXED_CACHE = "not-indexed"; public static final int DEFAULT_PAGE_SIZE = 10; @Override int getMembers() { return 3; } protected CacheMode getCacheMode() { return CacheMode.DIST_SYNC; } @Override protected Map<String, ConfigurationBuilder> getCacheConfigs() { Map<String, ConfigurationBuilder> caches = new HashMap<>(); final ConfigurationBuilder indexedCache = new ConfigurationBuilder(); final CacheMode cacheMode = getCacheMode(); if (cacheMode.isClustered()) { indexedCache.clustering().cacheMode(cacheMode); } indexedCache.statistics().enable().indexing().enable().addIndexedEntity("IndexedEntity").storage(IndexStorage.LOCAL_HEAP); indexedCache.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); caches.put(INDEXED_CACHE, indexedCache); final ConfigurationBuilder notIndexedCache = new ConfigurationBuilder(); if (cacheMode.isClustered()) { notIndexedCache.clustering().cacheMode(cacheMode); } notIndexedCache.encoding().mediaType(APPLICATION_PROTOSTREAM_TYPE); caches.put(NOT_INDEXED_CACHE, notIndexedCache); return caches; } @Override protected String getProtoFile() { return "count.proto"; } @BeforeClass public void setUp() { LongStream.range(0, INDEXED_ENTRIES).forEach(i -> { String str = "index " + i; String value = Json.object() .set("_type", "IndexedEntity") .set("indexedStoredField", str) .set("indexedNotStoredField", str) .set("sortableStoredField", i % 20) .set("sortableNotStoredField", "index_" + i % 20) .set("notIndexedField", str).toString(); RestResponse response = await(indexedCache().put(String.valueOf(i), RestEntity.create(APPLICATION_JSON, value))); assertEquals(204, response.getStatus()); assertTrue(response.getBody().isEmpty()); }); LongStream.range(0, NOT_INDEXED_ENTRIES).forEach(i -> { String value = "text " + i; Json json = Json.object().set("_type", "NotIndexedEntity").set("field1", value).set("field2", value); RestResponse response = await(nonIndexedCache().put(String.valueOf(i), RestEntity.create(APPLICATION_JSON, json.toString()))); assertEquals(204, response.getStatus()); assertTrue(response.getBody().isEmpty()); }); } /** * Pure indexed queries */ @Test public void testMatchAll() { CompletionStage<RestResponse> result = queryWithoutPagination(indexedCache(), "FROM IndexedEntity"); assertTotalAndPageSize(result, INDEXED_ENTRIES, INDEXED_ENTRIES); } @Test public void testMatchAllPagination() { CompletionStage<RestResponse> result = queryWithPagination(indexedCache(), "FROM IndexedEntity", 17, 0); assertTotalAndPageSize(result, INDEXED_ENTRIES, 17); } @Test public void testLimit() { CompletionStage<RestResponse> result = queryWithoutPagination(indexedCache(), "FROM IndexedEntity"); assertTotalAndPageSize(result, INDEXED_ENTRIES, INDEXED_ENTRIES); } @Test public void testLimitPagination() { CompletionStage<RestResponse> result = queryWithDefaultPagination(indexedCache(), "FROM IndexedEntity"); assertTotalAndPageSize(result, INDEXED_ENTRIES, DEFAULT_PAGE_SIZE); } @Test public void testSortedStored() { CompletionStage<RestResponse> result = queryWithoutPagination(indexedCache(), "FROM IndexedEntity ORDER BY sortableStoredField DESC"); assertTotalAndPageSize(result, INDEXED_ENTRIES, INDEXED_ENTRIES); } @Test public void testSortedStoredPagination() { CompletionStage<RestResponse> result = queryWithPagination(indexedCache(), "SELECT sortableStoredField FROM IndexedEntity ORDER BY sortableStoredField DESC", 35, 0); assertTotalAndPageSize(result, INDEXED_ENTRIES, 35); } @Test public void testSelectIndexed() { CompletionStage<RestResponse> result = queryWithoutPagination(indexedCache(), "SELECT indexedStoredField FROM IndexedEntity"); assertTotalAndPageSize(result, INDEXED_ENTRIES, INDEXED_ENTRIES); } @Test public void testSelectIndexedPagination() { CompletionStage<RestResponse> result = queryWithDefaultPagination(indexedCache(), "SELECT indexedStoredField FROM IndexedEntity"); assertTotalAndPageSize(result, INDEXED_ENTRIES, DEFAULT_PAGE_SIZE); } @Test public void testPagination() { CompletionStage<RestResponse> result = queryWithPagination(indexedCache(), "SELECT indexedStoredField FROM IndexedEntity", 8, 2); assertTotalAndPageSize(result, INDEXED_ENTRIES, 8); } @Test public void testAggregation() { CompletionStage<RestResponse> result = queryWithoutPagination(indexedCache(), "SELECT count(indexedStoredField) FROM IndexedEntity"); int indexedStoredField = getFieldAggregationValue(result, "indexedStoredField"); assertEquals(INDEXED_ENTRIES, indexedStoredField); } @Test public void testGrouping() { CompletionStage<RestResponse> result = queryWithoutPagination(indexedCache(), "SELECT count(sortableStoredField) FROM IndexedEntity GROUP BY sortableStoredField"); assertTotalAndPageSize(result, 20, 20); } @Test public void testGroupingPagination() { CompletionStage<RestResponse> result = queryWithDefaultPagination(indexedCache(), "SELECT count(sortableStoredField) FROM IndexedEntity GROUP BY sortableStoredField"); assertTotalAndPageSize(result, 20, 10); } @Test public void testCountOnly() { CompletionStage<RestResponse> result = queryWithPagination(indexedCache(), "FROM IndexedEntity", 0, 0); assertTotalAndPageSize(result, INDEXED_ENTRIES, 0); } /** * Hybrid queries */ @Test public void testSortedNotStored() { CompletionStage<RestResponse> result = queryWithoutPagination(indexedCache(), "FROM IndexedEntity ORDER BY sortableNotStoredField DESC"); assertTotalAndPageSize(result, INDEXED_ENTRIES, INDEXED_ENTRIES); } @Test public void testSortedNotStoredPagination() { CompletionStage<RestResponse> result = queryWithDefaultPagination(indexedCache(), "FROM IndexedEntity ORDER BY sortableNotStoredField DESC"); assertTotalAndPageSize(result, INDEXED_ENTRIES, DEFAULT_PAGE_SIZE); } @Test public void testSelectNonStoredField() { CompletionStage<RestResponse> result = queryWithoutPagination(indexedCache(), "SELECT indexedNotStoredField FROM IndexedEntity"); assertTotalAndPageSize(result, INDEXED_ENTRIES, INDEXED_ENTRIES); } @Test public void testSelectNonStoredFieldPagination() { CompletionStage<RestResponse> result = queryWithDefaultPagination(indexedCache(), "SELECT indexedNotStoredField FROM IndexedEntity"); assertTotalAndPageSize(result, INDEXED_ENTRIES, DEFAULT_PAGE_SIZE); } @Test public void testSelectNotIndexedField() { CompletionStage<RestResponse> result = queryWithoutPagination(indexedCache(), "SELECT notIndexedField FROM IndexedEntity"); assertTotalAndPageSize(result, INDEXED_ENTRIES, INDEXED_ENTRIES); } @Test public void testSelectNotIndexedFieldPagination() { CompletionStage<RestResponse> result = queryWithDefaultPagination(indexedCache(), "SELECT notIndexedField FROM IndexedEntity"); assertTotalAndPageSize(result, INDEXED_ENTRIES, DEFAULT_PAGE_SIZE); } @Test public void testHybridPaginated() { CompletionStage<RestResponse> result = queryWithDefaultPagination(indexedCache(), "SELECT notIndexedField FROM IndexedEntity WHERE indexedStoredField : 'index'"); assertTotalAndPageSize(result, INDEXED_ENTRIES, DEFAULT_PAGE_SIZE); } @Test public void testHybridNonPaginated() { CompletionStage<RestResponse> result = queryWithoutPagination(indexedCache(), "SELECT notIndexedField FROM IndexedEntity WHERE indexedStoredField : 'index'"); assertTotalAndPageSize(result, INDEXED_ENTRIES, INDEXED_ENTRIES); } @Test public void testAggregationHybrid() { CompletionStage<RestResponse> result = queryWithoutPagination(indexedCache(), "SELECT count(indexedStoredField), max(notIndexedField) FROM IndexedEntity"); int indexedStoredField = getFieldAggregationValue(result, "indexedStoredField"); assertEquals(INDEXED_ENTRIES, indexedStoredField); } @Test public void testAggregationHybridPagination() { CompletionStage<RestResponse> result = queryWithDefaultPagination(indexedCache(), "SELECT count(indexedStoredField), max(notIndexedField) FROM IndexedEntity"); int indexedStoredField = getFieldAggregationValue(result, "indexedStoredField"); assertEquals(INDEXED_ENTRIES, indexedStoredField); } @Test public void testCountOnlyHybrid() { CompletionStage<RestResponse> result = queryWithPagination(indexedCache(), "SELECT notIndexedField FROM IndexedEntity", 0, 0); assertTotalAndPageSize(result, INDEXED_ENTRIES, 0); } /** * Non-indexed queries */ @Test public void testMatchAllNotIndexed() { CompletionStage<RestResponse> result = queryWithoutPagination(nonIndexedCache(), "FROM NotIndexedEntity"); assertTotalAndPageSize(result, NOT_INDEXED_ENTRIES, NOT_INDEXED_ENTRIES); } public void testMatchAllNotIndexedPaginated() { CompletionStage<RestResponse> result = queryWithDefaultPagination(nonIndexedCache(), "FROM NotIndexedEntity"); assertTotalAndPageSize(result, NOT_INDEXED_ENTRIES, DEFAULT_PAGE_SIZE); } @Test public void testMaxResultsNotIndexedPaginated() { CompletionStage<RestResponse> result = queryWithPagination(nonIndexedCache(), "FROM NotIndexedEntity", 5, 1); assertTotalAndPageSize(result, NOT_INDEXED_ENTRIES, 5); } @Test public void testMaxResultsNotIndexed() { CompletionStage<RestResponse> result = queryWithoutPagination(nonIndexedCache(), "FROM NotIndexedEntity"); assertTotalAndPageSize(result, NOT_INDEXED_ENTRIES, NOT_INDEXED_ENTRIES); } @Test public void testSortedNotIndexed() { CompletionStage<RestResponse> result = queryWithoutPagination(nonIndexedCache(), "FROM NotIndexedEntity ORDER BY field2"); assertTotalAndPageSize(result, NOT_INDEXED_ENTRIES, NOT_INDEXED_ENTRIES); } @Test public void testSortedNotIndexedPaginated() { CompletionStage<RestResponse> result = queryWithDefaultPagination(nonIndexedCache(), "FROM NotIndexedEntity ORDER BY field2"); assertTotalAndPageSize(result, NOT_INDEXED_ENTRIES, DEFAULT_PAGE_SIZE); } @Test public void testPaginatedNotIndexed() { CompletionStage<RestResponse> result = queryWithPagination(nonIndexedCache(), "SELECT field1 FROM NotIndexedEntity", 5, 2); assertTotalAndPageSize(result, NOT_INDEXED_ENTRIES, 5); } @Test public void testSelectNotIndexed() { CompletionStage<RestResponse> result = queryWithDefaultPagination(nonIndexedCache(), "SELECT field1 FROM NotIndexedEntity"); assertTotalAndPageSize(result, NOT_INDEXED_ENTRIES, DEFAULT_PAGE_SIZE); } @Test public void testSelectNotIndexedPaginated() { CompletionStage<RestResponse> result = queryWithDefaultPagination(nonIndexedCache(), "SELECT field1 FROM NotIndexedEntity"); assertTotalAndPageSize(result, NOT_INDEXED_ENTRIES, DEFAULT_PAGE_SIZE); } @Test public void testAggregationNotIndexed() { CompletionStage<RestResponse> result = queryWithoutPagination(nonIndexedCache(), "SELECT count(field1), max(field2) FROM NotIndexedEntity"); int field1Count = getFieldAggregationValue(result, "field1"); assertEquals(NOT_INDEXED_ENTRIES, field1Count); } @Test public void testAggregationNotIndexedPagination() { CompletionStage<RestResponse> result = queryWithDefaultPagination(nonIndexedCache(), "SELECT count(field1), max(field2) FROM NotIndexedEntity"); int field1Count = getFieldAggregationValue(result, "field1"); assertEquals(NOT_INDEXED_ENTRIES, field1Count); } @Test public void testCountOnlyNotIndexed() { CompletionStage<RestResponse> result = queryWithPagination(nonIndexedCache(), "SELECT field1 FROM NotIndexedEntity", 0, 0); assertTotalAndPageSize(result, NOT_INDEXED_ENTRIES, 0); } private void assertTotalAndPageSize(CompletionStage<RestResponse> response, int expectedHitCount, int pageSize) { RestResponse restResponse = await(response); String body = restResponse.getBody(); Json responseDoc = Json.read(body); Json hitCount = responseDoc.at("hit_count"); assertEquals(expectedHitCount, hitCount.asInteger()); Json hitCountExact = responseDoc.at("hit_count_exact"); assertEquals(true, hitCountExact.getValue()); long hitsSize = responseDoc.at("hits").asJsonList().size(); assertEquals(pageSize, hitsSize); } private CompletionStage<RestResponse> queryWithoutPagination(RestCacheClient client, String query) { // don't do that is very inefficient (see ISPN-14194) return client.query(query, Integer.MAX_VALUE, 0); } private CompletionStage<RestResponse> queryWithDefaultPagination(RestCacheClient client, String query) { return client.query(query); } private CompletionStage<RestResponse> queryWithPagination(RestCacheClient client, String query, int maxResults, int offset) { return client.query(query, maxResults, offset); } private int getFieldAggregationValue(CompletionStage<RestResponse> response, String field) { RestResponse restResponse = await(response); String body = restResponse.getBody(); return Json.read(body).at("hits").asJsonList().get(0).at("hit").at(field).asInteger(); } private RestCacheClient indexedCache() { return cacheClients.get(INDEXED_CACHE); } private RestCacheClient nonIndexedCache() { return cacheClients.get(NOT_INDEXED_CACHE); } }
15,468
40.808108
173
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/NonIndexedRestSearchTest.java
package org.infinispan.rest.search; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @since 9.2 */ @Test(groups = "functional", testName = "rest.search.NonIndexedRestSearchTest") public class NonIndexedRestSearchTest extends BaseRestSearchTest { @Override protected ConfigurationBuilder getConfigBuilder() { ConfigurationBuilder configurationBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); configurationBuilder.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM); return configurationBuilder; } }
714
33.047619
102
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/BaseRestSearchTest.java
package org.infinispan.rest.search; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON_TYPE; import static org.infinispan.query.remote.json.JSONConstants.HIT; import static org.infinispan.query.remote.json.JSONConstants.HIT_COUNT; import static org.infinispan.rest.JSONConstants.TYPE; import static org.infinispan.rest.framework.Method.GET; import static org.infinispan.rest.framework.Method.POST; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletionStage; import java.util.function.BiConsumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.infinispan.Cache; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.client.rest.impl.okhttp.StringRestEntityOkHttp; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ClusteringConfiguration; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.query.Search; import org.infinispan.query.core.stats.IndexInfo; import org.infinispan.query.core.stats.SearchStatistics; import org.infinispan.rest.RequestHeader; import org.infinispan.rest.RestTestSCI; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.rest.framework.Method; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.rest.search.entity.Person; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Base class for query over Rest tests. * * @since 9.2 */ @Test(groups = "functional") public abstract class BaseRestSearchTest extends MultipleCacheManagersTest { private static final int ENTRIES = 50; private static final String CACHE_NAME = "search-rest"; private static final String PROTO_FILE_NAME = "person.proto"; protected RestClient client; protected RestCacheClient cacheClient; private final List<RestServerHelper> restServers = new ArrayList<>(); private final List<RestClient> clients = new ArrayList<>(); protected int getNumNodes() { return 3; } @Override protected void createCacheManagers() throws Exception { // global config GlobalConfigurationBuilder globalCfg = GlobalConfigurationBuilder.defaultClusteredBuilder(); globalCfg.serialization().addContextInitializer(RestTestSCI.INSTANCE); // test cache config ConfigurationBuilder builder = getConfigBuilder(); builder.statistics().enabled(true); // create a 'default' config which is not indexed ConfigurationBuilder defaultBuilder = new ConfigurationBuilder(); // start cache managers + default cache createClusteredCaches(getNumNodes(), globalCfg, defaultBuilder, isServerMode(), "default"); // start rest sever for each cache manager cacheManagers.forEach(cm -> { RestServerHelper restServer = new RestServerHelper(cm); restServer.start(TestResourceTracker.getCurrentTestShortName()); restServers.add(restServer); RestClientConfigurationBuilder clientConfigurationBuilder = new RestClientConfigurationBuilder(); clientConfigurationBuilder.addServer().host(restServer.getHost()).port(restServer.getPort()); clients.add(RestClient.forConfiguration(clientConfigurationBuilder.build())); }); client = clients.get(0); cacheClient = client.cache(CACHE_NAME); // register protobuf schema String protoFileContents = Util.getResourceAsString(PROTO_FILE_NAME, getClass().getClassLoader()); registerProtobuf(protoFileContents); // start indexed test cache that depends on the protobuf schema cacheManagers.forEach(cm -> { cm.defineConfiguration(CACHE_NAME, builder.build()); cm.getCache(CACHE_NAME); }); } protected boolean isServerMode() { return true; } @DataProvider(name = "HttpMethodProvider") protected static Object[][] provideCacheMode() { return new Object[][]{{GET}, {POST}}; } protected RestServerHelper pickServer() { return restServers.get(0); } protected String getPath(String cacheName) { return String.format("/rest/v2/caches/%s?action=search", cacheName); } protected String getPath() { return String.format("/rest/v2/caches/%s?action=search", CACHE_NAME); } @BeforeClass public void setUp() { populateData(); } @AfterMethod @Override protected void clearContent() { } @Test(dataProvider = "HttpMethodProvider") public void shouldReportInvalidQueries(Method method) throws Exception { CompletionStage<RestResponse> response; String wrongQuery = "from Whatever"; String path = getPath(); if (method == POST) { response = client.raw().post(path, "{ \"query\": \"" + wrongQuery + "\"}", APPLICATION_JSON_TYPE); } else { String getURL = path.concat("&query=").concat(URLEncoder.encode(wrongQuery, "UTF-8")); response = client.raw().get(getURL); } ResponseAssertion.assertThat(response).isBadRequest(); String contentAsString = join(response).getBody(); assertTrue(contentAsString.contains("Unknown entity name") || contentAsString.contains("Unknown type name"), contentAsString); } @Test(dataProvider = "HttpMethodProvider") public void shouldReturnEmptyResults(Method method) throws Exception { Json query = query("from org.infinispan.rest.search.entity.Person p where p.name = 'nobody'", method); assertZeroHits(query); } @Test(dataProvider = "HttpMethodProvider") public void testSimpleQuery(Method method) throws Exception { Json queryResult = query("from org.infinispan.rest.search.entity.Person p where p.surname = 'Cage'", method); assertEquals(queryResult.at("hit_count").asInteger(), 1); Json hits = queryResult.at("hits"); List<Json> jsonHits = hits.asJsonList(); assertEquals(jsonHits.size(), 1); Json result = jsonHits.iterator().next(); Json firstHit = result.at(HIT); assertEquals(firstHit.at("id").asInteger(), 2); assertEquals(firstHit.at("name").asString(), "Luke"); assertEquals(firstHit.at("surname").asString(), "Cage"); } @Test(dataProvider = "HttpMethodProvider") public void testMultiResultQuery(Method method) throws Exception { Json results = query("from org.infinispan.rest.search.entity.Person p where p.id < 5 and p.gender = 'MALE'", method); assertEquals(results.at(HIT_COUNT).asInteger(), 3); Json hits = results.at("hits"); assertEquals(hits.asList().size(), 3); } @Test(dataProvider = "HttpMethodProvider") public void testProjections(Method method) throws Exception { Json results = query("Select name, surname from org.infinispan.rest.search.entity.Person", method); assertEquals(results.at(HIT_COUNT).asInteger(), ENTRIES); Json hits = results.at("hits"); List<?> names = findValues(hits, "name"); List<?> surnames = findValues(hits, "surname"); List<?> streets = findValues(hits, "street"); List<?> gender = findValues(hits, "gender"); assertEquals(10, names.size()); assertEquals(10, surnames.size()); assertEquals(0, streets.size()); assertEquals(0, gender.size()); } private List<?> findValues(Json hits, String fieldName) { return hits.asJsonList().stream() .map(j -> j.at("hit")) .map(h -> h.asMap().get(fieldName)) .filter(Objects::nonNull) .collect(Collectors.toList()); } @Test(dataProvider = "HttpMethodProvider") public void testGrouping(Method method) throws Exception { Json results = query("select p.gender, count(p.name) from org.infinispan.rest.search.entity.Person p where p.id < 5 group by p.gender order by p.gender", method); assertEquals(results.at(HIT_COUNT).asInteger(), 2); Json hits = results.at("hits"); Json males = hits.at(0); assertEquals(males.at(HIT).at("name").asInteger(), 3); Json females = hits.at(1); assertEquals(females.at(HIT).at("name").asInteger(), 1); } @Test(dataProvider = "HttpMethodProvider") public void testOffset(Method method) throws Exception { String q = "select p.name from org.infinispan.rest.search.entity.Person p where p.id < 5 order by p.name desc"; Json results = query(q, method, 2, 2); assertEquals(results.at("hit_count").asInteger(), 4); assertEquals(results.at("hit_count_exact").asBoolean(), true); Json hits = results.at("hits"); assertEquals(hits.asList().size(), 2); assertEquals(hits.at(0).at(HIT).at("name").asString(), "Jessica"); assertEquals(hits.at(1).at(HIT).at("name").asString(), "Danny"); } @Test(dataProvider = "HttpMethodProvider") public void testIncompleteSearch(Method method) { String searchUrl = getPath(); CompletionStage<RestResponse> response; if (method.equals(POST)) { response = client.raw().post(searchUrl); } else { response = client.raw().get(searchUrl); } ResponseAssertion.assertThat(response).isBadRequest(); String contentAsString = join(response).getBody(); Json jsonNode = Json.read(contentAsString); assertTrue(jsonNode.at("error").at("message").asString().contains("Invalid search request")); } @Test public void testReadDocument() { CompletionStage<RestResponse> response = get("1", "*/*"); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).bodyNotEmpty(); } @Test public void testReadDocumentFromBrowser() throws Exception { String mediaType = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; RestResponse fromBrowser = join(cacheClient.get("2", mediaType)); ResponseAssertion.assertThat(fromBrowser).isOk(); ResponseAssertion.assertThat(fromBrowser).hasContentType(APPLICATION_JSON_TYPE); Json person = Json.read(fromBrowser.getBody()); assertEquals(person.at("id").asInteger(), 2); } @Test public void testErrorPropagation() throws Exception { CompletionStage<RestResponse> response = executeQueryRequest(GET, "from org.infinispan.rest.search.entity.Person where id:1", 0, 10); ResponseAssertion.assertThat(response).isBadRequest(); } private int getCount() throws Exception { Json results = query("from org.infinispan.rest.search.entity.Person", GET); return results.at("hit_count").asInteger(); } @Test public void testMassIndexing() { boolean indexEnabled = getConfigBuilder().indexing().enabled(); CompletionStage<RestResponse> clearResponse = client.cache(CACHE_NAME).clearIndex(); if (indexEnabled) { ResponseAssertion.assertThat(clearResponse).isOk(); } else { ResponseAssertion.assertThat(clearResponse).isBadRequest(); } if (indexEnabled) eventually(() -> getCount() == 0); CompletionStage<RestResponse> massIndexResponse = client.cache(CACHE_NAME).reindex(); if (indexEnabled) { ResponseAssertion.assertThat(massIndexResponse).isOk(); } else { ResponseAssertion.assertThat(massIndexResponse).isBadRequest(); } eventually(() -> getCount() == ENTRIES); } @Test public void testReindexAfterSchemaChanges() throws Exception { if (!getConfigBuilder().indexing().enabled()) return; // Update the schema adding an extra field String changedSchema = Util.getResourceAsString("person-changed.proto", getClass().getClassLoader()); registerProtobuf(changedSchema); // reindex join(client.cache(CACHE_NAME).reindex()); // Query on the new field Json result = query("FROM org.infinispan.rest.search.entity.Person where newField = 'value'", GET); assertZeroHits(result); } @Test public void testQueryStats() throws Exception { RestResponse response = join(cacheClient.queryStats()); if (!getConfigBuilder().indexing().enabled()) { ResponseAssertion.assertThat(response).isBadRequest(); } else { ResponseAssertion.assertThat(response).isOk(); Json stats = Json.read(response.getBody()); assertTrue(stats.at("search_query_execution_count").asLong() >= 0); assertTrue(stats.at("search_query_total_time").asLong() >= 0); assertTrue(stats.at("search_query_execution_max_time").asLong() >= 0); assertTrue(stats.at("search_query_execution_avg_time").asLong() >= 0); assertTrue(stats.at("object_loading_total_time").asLong() >= 0); assertTrue(stats.at("object_loading_execution_max_time").asLong() >= 0); assertTrue(stats.at("object_loading_execution_avg_time").asLong() >= 0); assertTrue(stats.at("objects_loaded_count").asLong() >= 0); assertNotNull(stats.at("search_query_execution_max_time_query_string").asString()); RestResponse clearResponse = join(cacheClient.clearQueryStats()); response = join(cacheClient.queryStats()); stats = Json.read(response.getBody()); ResponseAssertion.assertThat(clearResponse).isOk(); assertEquals(stats.at("search_query_execution_count").asLong(), 0); assertEquals(stats.at("search_query_execution_max_time").asLong(), 0); } } @Test public void testIndexStats() { RestResponse response = join(cacheClient.indexStats()); if (!getConfigBuilder().indexing().enabled()) { ResponseAssertion.assertThat(response).isBadRequest(); } else { ResponseAssertion.assertThat(response).isOk(); Json stats = Json.read(response.getBody()); Json indexClassNames = stats.at("indexed_class_names"); String indexName = "org.infinispan.rest.search.entity.Person"; assertEquals(indexClassNames.at(0).asString(), indexName); assertNotNull(stats.at("indexed_entities_count")); //TODO: Index sizes are not currently exposed (HSEARCH-4056) assertTrue(stats.at("index_sizes").at(indexName).asInteger() >= 0); } } @Test public void testLocalQuery() { Configuration configuration = getConfigBuilder().build(); ClusteringConfiguration clustering = configuration.clustering(); int sum = clients.stream().map(cli -> { RestResponse queryResponse = join(cli.cache(CACHE_NAME).query("FROM org.infinispan.rest.search.entity.Person", true)); return Json.read(queryResponse.getBody()).at(HIT_COUNT).asInteger(); }).mapToInt(value -> value).sum(); int expected = ENTRIES; if (clustering.cacheMode().isClustered()) { expected = ENTRIES * clustering.hash().numOwners(); } assertEquals(expected, sum); } @Test public void testLocalReindexing() { boolean indexEnabled = getConfigBuilder().indexing().enabled(); if (!indexEnabled || getNumNodes() < 2) return; // reindex() reindex the whole cluster join(clients.get(0).cache(CACHE_NAME).reindex()); assertAllIndexed(); clearIndexes(); // Local indexing should not touch the indexes of other caches join(clients.get(0).cache(CACHE_NAME).reindexLocal()); assertOnlyIndexed(0); clearIndexes(); join(clients.get(1).cache(CACHE_NAME).reindexLocal()); assertOnlyIndexed(1); clearIndexes(); join(clients.get(2).cache(CACHE_NAME).reindexLocal()); assertOnlyIndexed(2); } void clearIndexes() { join(clients.get(0).cache(CACHE_NAME).clearIndex()); } private void assertIndexState(BiConsumer<IndexInfo, Integer> cacheIndexInfo) { IntStream.range(0, getNumNodes()).forEach(i -> { Cache<?, ?> cache = cache(i, CACHE_NAME); SearchStatistics searchStatistics = Search.getSearchStatistics(cache); Map<String, IndexInfo> indexInfo = join(searchStatistics.getIndexStatistics().computeIndexInfos()); cacheIndexInfo.accept(indexInfo.get(Person.class.getName()), i); }); } private void assertAllIndexed() { assertIndexState((indexInfo, i) -> assertTrue(indexInfo.count() > 0)); } private void assertOnlyIndexed(int id) { assertIndexState((indexInfo, i) -> { long count = indexInfo.count(); if (i == id) { assertTrue(count > 0); } else { assertEquals(count, 0); } }); } @AfterClass(alwaysRun = true) public void tearDown() throws Exception { for (RestClient client : clients) { client.close(); } restServers.forEach(RestServerHelper::stop); } protected void populateData() { Json person1 = createPerson(1, "Jessica", "Jones", "46th St", "NY 10036", "FEMALE", 1111, 2222, 3333); Json person2 = createPerson(2, "Luke", "Cage", "Malcolm X Boulevard", "NY 11221", "MALE", 4444, 5555); Json person3 = createPerson(3, "Matthew", "Murdock", "57th St", "NY 10019", "MALE"); Json person4 = createPerson(4, "Danny", "Randy", "Vanderbilt Av.", "NY 10017", "MALE", 2122561084); index(1, person1.toString()); index(2, person2.toString()); index(3, person3.toString()); index(4, person4.toString()); for (int i = 5; i <= ENTRIES; i++) { String text = "Generic" + i; Json generic = createPerson(i, text, text, text, text, "MALE", 2122561084); index(i, generic.toString()); } eventually(() -> getCount() == ENTRIES); } private void index(int id, String person) { write(id, person, Method.POST, MediaType.APPLICATION_JSON); } protected void put(int id, String contents) { write(id, contents, Method.PUT, MediaType.APPLICATION_JSON); } protected void write(int id, String contents, Method method, MediaType contentType) { RestEntity entity = new StringRestEntityOkHttp(contentType, contents); CompletionStage<RestResponse> response; if (method.equals(POST)) { response = client.cache(CACHE_NAME).post(String.valueOf(id), entity); } else { response = client.cache(CACHE_NAME).put(String.valueOf(id), entity); } ResponseAssertion.assertThat(response).isOk(); } protected CompletionStage<RestResponse> get(String id, String accept) { String path = String.format("/rest/v2/caches/%s/%s", CACHE_NAME, id); return client.raw().get(path, Collections.singletonMap(RequestHeader.ACCEPT_HEADER.getValue(), accept)); } protected Json createPerson(int id, String name, String surname, String street, String postCode, String gender, int... phoneNumbers) { Json person = Json.object(); person.set(TYPE, "org.infinispan.rest.search.entity.Person"); person.set("id", id); person.set("name", name); person.set("surname", surname); person.set("gender", gender); Json address = Json.object(); if (needType()) address.set(TYPE, "org.infinispan.rest.search.entity.Address"); address.set("street", street); address.set("postCode", postCode); person.set("address", address); Json numbers = Json.array(); for (int phone : phoneNumbers) { Json number = Json.object(); if (needType()) number.set(TYPE, "org.infinispan.rest.search.entity.PhoneNumber"); number.set("number", phone); } person.set("phoneNumbers", numbers); return person; } protected void registerProtobuf(String protoFileContents) { CompletionStage<RestResponse> response = client.schemas().put(PROTO_FILE_NAME, protoFileContents); ResponseAssertion.assertThat(response).hasNoErrors(); } private void assertZeroHits(Json queryResponse) { Json hits = queryResponse.at("hits"); assertEquals(hits.asList().size(), 0); } private Json query(String q, Method method) throws Exception { return query(q, method, 0, 10); } private CompletionStage<RestResponse> executeQueryRequest(Method method, String q, int offset, int maxResults) throws Exception { String path = getPath(); if (method == POST) { Json queryReq = Json.object(); queryReq.set("query", q); queryReq.set("offset", offset); queryReq.set("max_results", maxResults); return client.raw().post(path, queryReq.toString(), APPLICATION_JSON_TYPE); } String queryReq = path + "&query=" + URLEncoder.encode(q, "UTF-8") + "&offset=" + offset + "&max_results=" + maxResults; return client.raw().get(queryReq); } private Json query(String q, Method method, int offset, int maxResults) throws Exception { CompletionStage<RestResponse> response = executeQueryRequest(method, q, offset, maxResults); ResponseAssertion.assertThat(response).isOk(); String contentAsString = join(response).getBody(); return Json.read(contentAsString); } protected boolean needType() { return false; } protected abstract ConfigurationBuilder getConfigBuilder(); }
22,162
37.015437
168
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/SingleNodeLocalIndexTest.java
package org.infinispan.rest.search; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @since 9.2 */ @Test(groups = "functional", testName = "rest.search.SingleNodeLocalIndexTest") public class SingleNodeLocalIndexTest extends BaseRestSearchTest { @Override protected ConfigurationBuilder getConfigBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.clustering().cacheMode(CacheMode.LOCAL); configurationBuilder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("org.infinispan.rest.search.entity.Person") .encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM); return configurationBuilder; } @Override protected int getNumNodes() { return 1; } }
1,040
31.53125
79
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/IndexedRestOffHeapSearchTest.java
package org.infinispan.rest.search; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.testng.annotations.Test; /** * Test for indexed search over Rest when using OFF_HEAP. * * @since 9.2 */ @Test(groups = "functional", testName = "rest.search.IndexedRestOffHeapSearchTest") public class IndexedRestOffHeapSearchTest extends BaseRestSearchTest { @Override protected ConfigurationBuilder getConfigBuilder() { ConfigurationBuilder configurationBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); configurationBuilder.indexing().enable().storage(LOCAL_HEAP) .addIndexedEntity("org.infinispan.rest.search.entity.Person"); configurationBuilder.memory().storage(StorageType.OFF_HEAP); return configurationBuilder; } }
982
35.407407
102
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/RestHitCountAccuracyTest.java
package org.infinispan.rest.search; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletionStage; import org.infinispan.Cache; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.model.Game; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.search.RestHitCountAccuracyTest") @TestForIssue(jiraKey = "ISPN-14195") public class RestHitCountAccuracyTest extends SingleCacheManagerTest { private static final String CACHE_NAME = "games"; private static final int ENTRIES = 5_000; private RestServerHelper restServer; private RestClient restClient; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(); // Register proto schema Cache<String, String> metadataCache = cacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.putIfAbsent(Game.GameSchema.INSTANCE.getProtoFileName(), Game.GameSchema.INSTANCE.getProtoFile()); assertFalse(metadataCache.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX)); ConfigurationBuilder config = new ConfigurationBuilder(); config .encoding() .mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE) .indexing() .enable() .storage(IndexStorage.LOCAL_HEAP) .addIndexedEntity("Game") .query() .hitCountAccuracy(10); // lower the default accuracy cacheManager.createCache(CACHE_NAME, config.build()); restServer = new RestServerHelper(cacheManager); restServer.start(TestResourceTracker.getCurrentTestShortName()); restClient = RestClient.forConfiguration(new RestClientConfigurationBuilder().addServer() .host(restServer.getHost()).port(restServer.getPort()) .build()); return cacheManager; } @Override protected void teardown() { try { restClient.close(); } catch (IOException ex) { // ignore it } finally { try { restServer.stop(); } finally { super.teardown(); } } } @Test @TestForIssue(jiraKey = "ISPN-14189") public void test() throws Exception { RestCacheClient cacheClient = restClient.cache(CACHE_NAME); writeEntries(ENTRIES, cacheClient); assertEquals(ENTRIES, count(cacheClient)); CompletionStage<RestResponse> response = cacheClient.query("from Game where description : 'game'", 10, 0); assertThat(response).isOk(); Json body = Json.read(response.toCompletableFuture().get().getBody()); Object hitCountExact = body.at("hit_count_exact").getValue(); assertEquals(hitCountExact, false); // raise the default accuracy response = cacheClient.query("from Game where description : 'game'", 10, 0, ENTRIES); assertThat(response).isOk(); body = Json.read(response.toCompletableFuture().get().getBody()); hitCountExact = body.at("hit_count_exact").getValue(); assertEquals(hitCountExact, true); assertEquals(body.at("hit_count").asInteger(), ENTRIES); } private static void writeEntries(int entries, RestCacheClient cacheClient) { List<CompletionStage<RestResponse>> responses = new ArrayList<>(entries); for (int i = 0; i < entries; i++) { Json game = Json.object() .set("_type", "Game") .set("name", "Game n." + i) .set("description", "This is the game #" + i); responses.add(cacheClient.put("game-" + i, RestEntity.create(MediaType.APPLICATION_JSON, game.toString()))); } for (CompletionStage<RestResponse> response : responses) { assertThat(response).isOk(); } } private int count(RestCacheClient cacheClient) { RestResponse response = join(cacheClient.searchStats()); Json stat = Json.read(response.getBody()); Json indexGame = stat.at("index").at("types").at("Game"); return indexGame.at("count").asInteger(); } }
5,290
37.904412
129
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/EmbeddedRestSearchTest.java
package org.infinispan.rest.search; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Test for querying embedded cache managers and embedded REST servers, storing * protobuf and JSON on the API side. */ @Test(groups = "functional", testName = "rest.search.EmbeddedRestSearchTest") public class EmbeddedRestSearchTest extends SingleNodeLocalIndexTest { @Override protected ConfigurationBuilder getConfigBuilder() { ConfigurationBuilder config = super.getConfigBuilder(); config.encoding().key().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); config.encoding().value().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); return config; } @Override protected boolean isServerMode() { return false; } }
869
31.222222
82
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/MultiNodeRestTest.java
package org.infinispan.rest.search; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.function.Function; import java.util.stream.Collectors; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; /** * @since 12.1 */ public abstract class MultiNodeRestTest extends MultipleCacheManagersTest { private RestClient client; protected Map<String, RestCacheClient> cacheClients; private final List<RestServerHelper> restServers = new ArrayList<>(); abstract int getMembers(); @Override protected void createCacheManagers() throws Throwable { createClusteredCaches(getMembers(), GlobalConfigurationBuilder.defaultClusteredBuilder(), new ConfigurationBuilder(), true); cacheManagers.forEach(cm -> { RestServerHelper restServer = new RestServerHelper(cm); restServer.start(TestResourceTracker.getCurrentTestShortName()); restServers.add(restServer); }); RestClientConfigurationBuilder clientConfigurationBuilder = new RestClientConfigurationBuilder(); restServers.forEach(s -> clientConfigurationBuilder.addServer().host(s.getHost()).port(s.getPort())); this.client = RestClient.forConfiguration(clientConfigurationBuilder.build()); // Register the proto schema before starting the caches String protoFileContents = Util.getResourceAsString(getProtoFile(), getClass().getClassLoader()); registerProtobuf(protoFileContents); cacheManagers.forEach(cm -> { getCacheConfigs().forEach((name, configBuilder) -> cm.createCache(name, configBuilder.build())); }); cacheClients = getCacheConfigs().keySet().stream().collect(Collectors.toMap(Function.identity(), client::cache)); } @AfterClass(alwaysRun = true) public void tearDown() throws Exception { client.close(); restServers.forEach(RestServerHelper::stop); } @AfterMethod @Override protected void clearContent() { } protected void registerProtobuf(String protoFileContents) { CompletionStage<RestResponse> response = client.schemas().post("file.proto", protoFileContents); ResponseAssertion.assertThat(response).hasNoErrors(); } protected abstract Map<String, ConfigurationBuilder> getCacheConfigs(); protected abstract String getProtoFile(); }
3,020
37.240506
130
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/NonIndexedRestOffHeapSearch.java
package org.infinispan.rest.search; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.testng.annotations.Test; /** * @since 9.2 */ @Test(groups = "functional", testName = "rest.search.NonIndexedRestOffHeapSearch") public class NonIndexedRestOffHeapSearch extends BaseRestSearchTest { @Override protected ConfigurationBuilder getConfigBuilder() { ConfigurationBuilder configurationBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); configurationBuilder.encoding().key().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); configurationBuilder.encoding().value().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); configurationBuilder.memory().storageType(StorageType.OFF_HEAP); return configurationBuilder; } }
954
38.791667
102
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/SearchCountLocalTest.java
package org.infinispan.rest.search; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; /** * @since 12.1 */ @Test(groups = "functional", testName = "rest.search.SearchCountLocalTest") public class SearchCountLocalTest extends SearchCountClusteredTest { @Override int getMembers() { return 1; } @Override protected CacheMode getCacheMode() { return CacheMode.LOCAL; } }
443
19.181818
75
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/NonIndexedPojoQueryTest.java
package org.infinispan.rest.search; import java.util.concurrent.CompletionStage; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.rest.assertion.ResponseAssertion; import org.testng.annotations.Test; /** * Test for search via rest when storing java objects in the cache. * * @since 9.2 */ @Test(groups = "functional", testName = "rest.search.NonIndexedPojoQueryTest") public class NonIndexedPojoQueryTest extends BaseRestSearchTest { @Override protected ConfigurationBuilder getConfigBuilder() { ConfigurationBuilder configurationBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); configurationBuilder.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE); configurationBuilder.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE); return configurationBuilder; } @Override protected void createCacheManagers() throws Exception { super.createCacheManagers(); cacheManagers.forEach(cm -> cm.getClassAllowList().addRegexps("org.infinispan.rest.search.entity.*")); } @Override protected void registerProtobuf(String protoFileContents) { // Not needed } @Override protected boolean needType() { return true; } @Override public void testReadDocumentFromBrowser() { CompletionStage<RestResponse> fromBrowser = get("2", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); ResponseAssertion.assertThat(fromBrowser).isOk(); ResponseAssertion.assertThat(fromBrowser).bodyNotEmpty(); } }
1,741
32.5
126
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/IndexedCacheNonIndexedEntityTest.java
package org.infinispan.rest.search; import static org.infinispan.commons.api.CacheContainerAdmin.AdminFlag.VOLATILE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.rest.resources.AbstractRestResourceTest.cacheConfigToJson; import static org.testng.AssertJUnit.assertFalse; import java.util.concurrent.CompletionStage; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Indexer; import org.infinispan.query.Search; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * @since 12.0 */ @Test(groups = "functional", testName = "rest.search.IndexedCacheNonIndexedEntityTest") public class IndexedCacheNonIndexedEntityTest extends SingleCacheManagerTest { private static final String CACHE_NAME = "IndexedCacheNonIndexedEntitiesTest"; private static final String SCHEMA = "message NonIndexed { optional string name = 1; }"; protected RestClient client; private RestServerHelper restServer; @Override protected EmbeddedCacheManager createCacheManager() { GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder().nonClusteredDefault(); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(gcb, getDefaultStandaloneCacheConfig(false)); restServer = new RestServerHelper(cm); restServer.start(TestResourceTracker.getCurrentTestShortName() + "-" + cm.getAddress()); RestClientConfigurationBuilder clientConfigurationBuilder = new RestClientConfigurationBuilder(); clientConfigurationBuilder.addServer().host(restServer.getHost()).port(restServer.getPort()); client = RestClient.forConfiguration(clientConfigurationBuilder.build()); return cm; } @AfterClass public void tearDown() throws Exception { client.close(); restServer.stop(); } @Test public void shouldPreventNonIndexedEntities() { CompletionStage<RestResponse> response = client.schemas().post("customer", SCHEMA); ResponseAssertion.assertThat(response).isOk(); ConfigurationBuilder configurationBuilder = getDefaultStandaloneCacheConfig(false); configurationBuilder.statistics().enable(); configurationBuilder.encoding().mediaType(APPLICATION_PROTOSTREAM_TYPE).indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("NonIndexed"); String config = cacheConfigToJson(CACHE_NAME, configurationBuilder.build()); RestEntity configEntity = RestEntity.create(MediaType.APPLICATION_JSON, config); RestCacheClient cacheClient = client.cache(CACHE_NAME); response = cacheClient.createWithConfiguration(configEntity, VOLATILE); // The SearchMapping is started lazily, creating and starting the cache will not throw errors ResponseAssertion.assertThat(response).isOk(); // Force initialization of the SearchMapping response = cacheClient.query("FROM NonIndexed"); ResponseAssertion.assertThat(response).isBadRequest(); String errorText = "The configured indexed-entity type 'NonIndexed' must be indexed. Please annotate it with @Indexed"; ResponseAssertion.assertThat(response).containsReturnedText(errorText); // Call Indexer operations response = cacheClient.clearIndex(); ResponseAssertion.assertThat(response).containsReturnedText(errorText); // The Indexer should not have "running" status Indexer indexer = Search.getIndexer(cacheManager.getCache(CACHE_NAME)); assertFalse(indexer.isRunning()); } }
4,384
45.157895
125
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/NonSharedIndexSearchTest.java
package org.infinispan.rest.search; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Test for indexed search over Rest when using a non-shared index. * * @since 9.2 */ @Test(groups = "functional", testName = "rest.search.NonSharedIndexSearchTest") public class NonSharedIndexSearchTest extends BaseRestSearchTest { @Override protected ConfigurationBuilder getConfigBuilder() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("org.infinispan.rest.search.entity.Person") .encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM); return builder; } }
962
32.206897
89
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/IndexedRestSearchTest.java
package org.infinispan.rest.search; import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD; import static io.netty.handler.codec.http.HttpHeaderNames.HOST; import static io.netty.handler.codec.http.HttpHeaderNames.ORIGIN; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import java.util.HashMap; import java.util.Map; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.rest.assertion.ResponseAssertion; import org.testng.annotations.Test; /** * Tests for search over rest for indexed caches. * * @since 9.2 */ @Test(groups = "functional", testName = "rest.search.IndexedRestSearchTest") public class IndexedRestSearchTest extends BaseRestSearchTest { @Override protected ConfigurationBuilder getConfigBuilder() { ConfigurationBuilder configurationBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); configurationBuilder.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity("org.infinispan.rest.search.entity.Person"); return configurationBuilder; } @Test public void testReplaceIndexedDocument() throws Exception { put(10, createPerson(0, "P", "", "?", "?", "MALE").toString()); put(10, createPerson(0, "P", "Surname", "?", "?", "MALE").toString()); RestResponse response = join(get("10", "application/json")); Json person = Json.read(response.getBody()); assertEquals("Surname", person.at("surname").asString()); } @Test public void testCORS() { String searchUrl = getPath(); Map<String, String> headers = new HashMap<>(); headers.put(HOST.toString(), "localhost"); headers.put(ORIGIN.toString(), "http://localhost:" + pickServer().getPort()); headers.put(ACCESS_CONTROL_REQUEST_METHOD.toString(), "GET"); RestResponse preFlight = join(client.raw().options(searchUrl, headers)); ResponseAssertion.assertThat(preFlight).isOk(); ResponseAssertion.assertThat(preFlight).hasNoContent(); ResponseAssertion.assertThat(preFlight).containsAllHeaders("access-control-allow-origin", "access-control-allow-methods"); } }
2,483
37.8125
128
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/entity/Gender.java
package org.infinispan.rest.search.entity; import org.infinispan.protostream.annotations.ProtoEnumValue; /** * @since 9.2 */ public enum Gender { @ProtoEnumValue(number = 1) MALE, @ProtoEnumValue(number = 2) FEMALE }
233
15.714286
61
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/entity/Person.java
package org.infinispan.rest.search.entity; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.descriptors.Type; /** * @since 9.2 */ @ProtoDoc("@Indexed") public class Person implements Serializable { private Integer id; private String name; private String surname; @ProtoDoc("@Field") private Integer age; private Address address; private Gender gender; private Set<PhoneNumber> phoneNumbers; public Person() { } public Person(Integer id, String name, String surname, Integer age, Address address, Gender gender, Set<PhoneNumber> phoneNumbers) { this.id = id; this.name = name; this.surname = surname; this.age = age; this.address = address; this.gender = gender; this.phoneNumbers = phoneNumbers; } @ProtoField(number = 1) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @ProtoField(number = 2) public String getName() { return name; } public void setName(String name) { this.name = name; } @ProtoField(number = 3) public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } @ProtoField(number = 4) public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } @ProtoField(number = 5) public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @ProtoField(number = 6, collectionImplementation = HashSet.class) public Set<PhoneNumber> getPhoneNumbers() { return phoneNumbers; } public void setPhoneNumbers(Set<PhoneNumber> phoneNumbers) { this.phoneNumbers = phoneNumbers; } @ProtoField(number = 7, type = Type.UINT32) public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
2,177
19.166667
135
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/entity/PhoneNumber.java
package org.infinispan.rest.search.entity; import org.infinispan.protostream.annotations.ProtoField; /** * @since 9.2 */ public class PhoneNumber { private String number; @ProtoField(1) public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } }
333
14.904762
57
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/entity/Address.java
package org.infinispan.rest.search.entity; import java.io.Serializable; import org.infinispan.protostream.annotations.ProtoField; /** * @since 9.2 */ public class Address implements Serializable { private String street; private String postCode; @ProtoField(number = 1) public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } @ProtoField(number = 2) public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } }
593
17
57
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/search/reindex/RestReindexRemoveAndStatisticsTest.java
package org.infinispan.rest.search.reindex; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.infinispan.Cache; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.configuration.cache.IndexingMode; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.model.Game; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "unit", testName = "rest.search.reindex.RestReindexRemoveAndStatisticsTest") public class RestReindexRemoveAndStatisticsTest extends SingleCacheManagerTest { private static final String CACHE_NAME = "types"; private static final int ENTRIES = 5_000; private static final int FEW_ENTRIES = 5; private RestServerHelper restServer; private RestClient restClient; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(); // Register proto schema Cache<String, String> metadataCache = cacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.putIfAbsent(Game.GameSchema.INSTANCE.getProtoFileName(), Game.GameSchema.INSTANCE.getProtoFile()); assertFalse(metadataCache.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX)); ConfigurationBuilder config = new ConfigurationBuilder(); config .encoding() .mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE) .indexing() .enable() .indexingMode(IndexingMode.MANUAL) .storage(IndexStorage.LOCAL_HEAP) .addIndexedEntity("Game"); cacheManager.createCache(CACHE_NAME, config.build()); restServer = new RestServerHelper(cacheManager); restServer.start(TestResourceTracker.getCurrentTestShortName()); restClient = RestClient.forConfiguration(new RestClientConfigurationBuilder().addServer() .host(restServer.getHost()).port(restServer.getPort()) .build()); return cacheManager; } @Test @TestForIssue(jiraKey = "ISPN-14189") public void reindexRemoveAndGetStatistics() { RestCacheClient cacheClient = restClient.cache(CACHE_NAME); assertThat(cacheClient.clearIndex()).isOk(); assertEquals(0, count(cacheClient)); writeEntries(ENTRIES, cacheClient); assertEquals(0, count(cacheClient)); assertThat(cacheClient.reindex()).isOk(); assertEquals(ENTRIES, count(cacheClient)); assertThat(cacheClient.clearIndex()).isOk(); assertEquals(0, count(cacheClient)); } @Test public void reindexAsFirstOperation() { // Test mass indexing as first operation, // executed when the LazySearchMapping#searchMappingRef is not available. // See LazySearchMapping#allIndexedEntityJavaClasses. RestCacheClient cacheClient = restClient.cache(CACHE_NAME); assertThat(cacheClient.reindex()).isOk(); } @Test @TestForIssue(jiraKey = "ISPN-14901") public void reindexAndConcurrentlyGetStatistics() throws Exception { RestCacheClient cacheClient = restClient.cache(CACHE_NAME); assertThat(cacheClient.clearIndex()).isOk(); assertEquals(0, count(cacheClient)); writeEntries(FEW_ENTRIES, cacheClient); assertEquals(0, count(cacheClient)); // Do some tries to reproduce the proper interleaving for (int i=0; i<3; i++) { CompletableFuture<RestResponse> reindexOperation = cacheClient.reindex().toCompletableFuture(); while (!reindexOperation.isDone()) { CompletionStage<RestResponse> searchStatsRequest = cacheClient.searchStats(); assertThat(searchStatsRequest).isOk(); } assertThat(reindexOperation).isOk(); } } @Override protected void teardown() { try { restClient.close(); } catch (IOException ex) { // ignore it } finally { try { restServer.stop(); } finally { super.teardown(); } } } private static void writeEntries(int entries, RestCacheClient cacheClient) { List<CompletionStage<RestResponse>> responses = new ArrayList<>(entries); for (int i = 0; i < entries; i++) { Json game = Json.object() .set("_type", "Game") .set("name", "Game n." + i) .set("description", "This is the game #" + i); responses.add(cacheClient.put("game-" + i, RestEntity.create(MediaType.APPLICATION_JSON, game.toString()))); } for (CompletionStage<RestResponse> response : responses) { assertThat(response).isOk(); } } private int count(RestCacheClient cacheClient) { RestResponse response = join(cacheClient.searchStats()); Json stat = Json.read(response.getBody()); Json indexGame = stat.at("index").at("types").at("Game"); return indexGame.at("count").asInteger(); } }
6,151
37.21118
129
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/tracing/OpenTelemetryClient.java
package org.infinispan.rest.tracing; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.StatusCode; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import io.opentelemetry.context.Scope; import io.opentelemetry.context.propagation.ContextPropagators; import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; import io.opentelemetry.sdk.trace.SpanProcessor; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; import io.opentelemetry.sdk.trace.export.SpanExporter; public class OpenTelemetryClient { private final SdkTracerProvider tracerProvider; private final OpenTelemetry openTelemetry; private final Tracer tracer; public OpenTelemetryClient(SpanExporter spanExporter) { // we usually use a batch processor, // but this is a test SpanProcessor spanProcessor = SimpleSpanProcessor.create(spanExporter); SdkTracerProviderBuilder builder = SdkTracerProvider.builder() .addSpanProcessor(spanProcessor); tracerProvider = builder.build(); openTelemetry = OpenTelemetrySdk.builder() .setTracerProvider(tracerProvider) .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance())) .buildAndRegisterGlobal(); tracer = openTelemetry.getTracer("org.infinispan.hotrod.client.test", "1.0.0"); } public void shutdown() { tracerProvider.shutdown(); GlobalOpenTelemetry.resetForTest(); } public OpenTelemetry openTelemetry() { return openTelemetry; } @SuppressWarnings("unused") public void withinClientSideSpan(String spanName, Runnable operations) { Span span = tracer.spanBuilder(spanName).setSpanKind(SpanKind.CLIENT).startSpan(); // put the span into the current Context try (Scope scope = span.makeCurrent()) { operations.run(); } catch (Throwable throwable) { span.setStatus(StatusCode.ERROR, "Something bad happened!"); span.recordException(throwable); throw throwable; } finally { span.end(); // Cannot set a span after this call } } }
2,426
36.921875
95
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/tracing/TracingPropagationTest.java
package org.infinispan.rest.tracing; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import org.assertj.core.api.Assertions; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.server.core.telemetry.TelemetryService; import org.infinispan.server.core.telemetry.impl.OpenTelemetryService; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; import io.opentelemetry.sdk.trace.data.SpanData; @Test(groups = "functional", testName = "rest.tracing.TracingPropagationTest") public class TracingPropagationTest extends SingleCacheManagerTest { private static final String CACHE_NAME = "tracing"; private final InMemorySpanExporter inMemorySpanExporter = InMemorySpanExporter.create(); // Configure OpenTelemetry SDK for tests private final OpenTelemetryClient oTelConfig = new OpenTelemetryClient(inMemorySpanExporter); private RestServerHelper restServer; private RestClient restClient; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(); cacheManager.createCache(CACHE_NAME, getDefaultClusteredCacheConfig(CacheMode.LOCAL).build()); GlobalComponentRegistry globalComponentRegistry = cacheManager.getGlobalComponentRegistry(); globalComponentRegistry.registerComponent(new OpenTelemetryService(oTelConfig.openTelemetry()), TelemetryService.class); restServer = new RestServerHelper(cacheManager); restServer.start(TestResourceTracker.getCurrentTestShortName()); restClient = RestClient.forConfiguration(new RestClientConfigurationBuilder().addServer() .host(restServer.getHost()).port(restServer.getPort()) .build()); return cacheManager; } @Test public void smokeTest() { RestCacheClient client = restClient.cache(CACHE_NAME); oTelConfig.withinClientSideSpan("user-client-side-span", () -> { // verify that the client thread contains the span context Map<String, String> contextMap = getContextMap(); Assertions.assertThat(contextMap).isNotEmpty(); CompletionStage<RestResponse> resp1 = client.put("aaa", MediaType.TEXT_PLAIN.toString(), RestEntity.create(MediaType.TEXT_PLAIN, "bbb"), contextMap); CompletionStage<RestResponse> resp2 = client.put("bbb", MediaType.TEXT_PLAIN.toString(), RestEntity.create(MediaType.TEXT_PLAIN, "ccc"), contextMap); assertThat(resp1).isOk(); assertThat(resp2).isOk(); }); // Verify that the client span (user-client-side-span) and the two PUT server spans are exported correctly. // We're going now to correlate the client span with the server spans! List<SpanData> spans = inMemorySpanExporter.getFinishedSpanItems(); Assertions.assertThat(spans).hasSize(3); String traceId = null; Set spanIds = new HashSet(); Map<String, Integer> parentSpanIds = new HashMap<>(); String parentSpan = null; for (SpanData span : spans) { if (traceId == null) { traceId = span.getTraceId(); } else { // check that the spans have all the same trace id Assertions.assertThat(span.getTraceId()).isEqualTo(traceId); } spanIds.add(span.getSpanId()); parentSpanIds.compute(span.getParentSpanId(), (key, value) -> (value == null) ? 1 : value + 1); Integer times = parentSpanIds.get(span.getParentSpanId()); if (times == 2) { parentSpan = span.getParentSpanId(); } } // we have 3 different spans: Assertions.assertThat(spanIds).hasSize(3); // two of which have the same parent span Assertions.assertThat(parentSpanIds).hasSize(2); // that is the other span Assertions.assertThat(spanIds).contains(parentSpan); } @Override protected void teardown() { try { oTelConfig.shutdown(); restClient.close(); } catch (IOException ex) { // ignore it } finally { try { restServer.stop(); } finally { super.teardown(); } } } public static Map<String, String> getContextMap() { HashMap<String, String> result = new HashMap<>(); // Inject the request with the *current* Context, which contains our current Span. W3CTraceContextPropagator.getInstance().inject(Context.current(), result, (carrier, key, value) -> carrier.put(key, value)); return result; } }
5,626
38.076389
126
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/framework/RestDispatcherTest.java
package org.infinispan.rest.framework; import static java.util.concurrent.CompletableFuture.completedFuture; import static org.infinispan.rest.framework.Method.GET; import static org.infinispan.rest.framework.Method.HEAD; import static org.infinispan.rest.framework.Method.POST; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicInteger; import javax.security.auth.Subject; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.rest.framework.impl.Invocations; import org.infinispan.rest.framework.impl.ResourceManagerImpl; import org.infinispan.rest.framework.impl.RestDispatcherImpl; import org.infinispan.rest.framework.impl.SimpleRequest; import org.infinispan.rest.framework.impl.SimpleRestResponse; import org.infinispan.security.AuditContext; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.CustomAuditLoggerTest; import org.infinispan.security.impl.Authorizer; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.test.TestingUtil; import org.testng.Assert; import org.testng.annotations.Test; /** * @since 10.0 */ @Test(groups = "unit", testName = "rest.framework.RestDispatcherTest") public class RestDispatcherTest { @Test public void testDispatch() { ResourceManagerImpl manager = new ResourceManagerImpl(); manager.registerResource("/", new RootResource()); manager.registerResource("ctx", new CounterResource()); manager.registerResource("ctx", new MemoryResource()); manager.registerResource("ctx", new EchoResource()); manager.registerResource("ctx", new FileResource()); GlobalConfiguration globalConfiguration = new GlobalConfigurationBuilder().build(); RestDispatcherImpl restDispatcher = new RestDispatcherImpl(manager, new Authorizer(globalConfiguration.security(), AuditContext.SERVER, "test", null)); RestRequest restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/").build(); CompletionStage<RestResponse> response = restDispatcher.dispatch(restRequest); assertEquals("Hello World!", join(response).getEntity().toString()); restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/image.gif").build(); response = restDispatcher.dispatch(restRequest); assertEquals("Hello World!", join(response).getEntity().toString()); restRequest = new SimpleRequest.Builder().setMethod(POST).setPath("//ctx/counters/counter1").build(); response = restDispatcher.dispatch(restRequest); assertEquals(200, join(response).getStatus()); restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/counters/counter1?action=increment").build(); response = restDispatcher.dispatch(restRequest); assertEquals(200, join(response).getStatus()); restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/counters//counter1").build(); response = restDispatcher.dispatch(restRequest); assertEquals("counter1->1", join(response).getEntity().toString()); restRequest = new SimpleRequest.Builder().setMethod(POST).setPath("/ctx/jvm").build(); assertNoResource(restDispatcher, restRequest); restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/jvm/memory").build(); response = restDispatcher.dispatch(restRequest); assertTrue(Long.parseLong(join(response).getEntity().toString()) > 0); restRequest = new SimpleRequest.Builder().setMethod(HEAD).setPath("/ctx/jvm/memory").build(); response = restDispatcher.dispatch(restRequest); assertTrue(Long.parseLong(join(response).getEntity().toString()) > 0); restRequest = new SimpleRequest.Builder().setMethod(HEAD).setPath("/ctx/v2/java-memory").build(); response = restDispatcher.dispatch(restRequest); assertTrue(Long.parseLong(join(response).getEntity().toString()) > 0); restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/context/var1/var2").build(); response = restDispatcher.dispatch(restRequest); assertEquals("var1,var2", join(response).getEntity().toString()); restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/context/var1/var2/var3?action=triple").build(); response = restDispatcher.dispatch(restRequest); assertEquals("triple(var1,var2,var3)", join(response).getEntity().toString()); restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/context/var1/var2/var3?action=invalid").build(); assertNoResource(restDispatcher, restRequest); restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/web/").build(); response = restDispatcher.dispatch(restRequest); assertEquals("/ctx/web/index.html", join(response).getEntity().toString()); restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/web/file.txt").build(); response = restDispatcher.dispatch(restRequest); assertEquals("/ctx/web/file.txt", join(response).getEntity().toString()); restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/web/dir/file.txt").build(); response = restDispatcher.dispatch(restRequest); assertEquals("/ctx/web/dir/file.txt", join(response).getEntity().toString()); restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/web/dir1/dir2/file.txt").build(); response = restDispatcher.dispatch(restRequest); assertEquals("/ctx/web/dir1/dir2/file.txt", join(response).getEntity().toString()); // Create a resource named "{c}" restRequest = new SimpleRequest.Builder().setMethod(POST).setPath("/ctx/counters/{c}").build(); response = restDispatcher.dispatch(restRequest); assertEquals(200, join(response).getStatus()); // Read a resource named "{c}" restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/counters/{c}").build(); response = restDispatcher.dispatch(restRequest); assertEquals("{c}->0", join(response).getEntity().toString()); } @Test public void testDispatchWithAuthz() { final Subject ADMIN = TestingUtil.makeSubject("admin"); final Subject LIFECYCLE = TestingUtil.makeSubject("lifecycle"); ResourceManagerImpl manager = new ResourceManagerImpl(); manager.registerResource("ctx", new SecureResource()); CustomAuditLoggerTest.TestAuditLogger auditLogger = new CustomAuditLoggerTest.TestAuditLogger(); GlobalConfiguration globalConfiguration = new GlobalConfigurationBuilder().security().authorization().enable().groupOnlyMapping(false) .auditLogger(auditLogger).principalRoleMapper(new IdentityRoleMapper()).build(); RestDispatcherImpl restDispatcher = new RestDispatcherImpl(manager, new Authorizer(globalConfiguration.security(), AuditContext.SERVER, "test", null)); // Anonymous RestRequest restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/secure").build(); CompletionStage<RestResponse> response = restDispatcher.dispatch(restRequest); Exceptions.expectCompletionException(SecurityException.class, response); assertEquals("Permission to ADMIN is DENY for user null", auditLogger.getLastRecord()); // Wrong user restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/secure").setSubject(LIFECYCLE).build(); response = restDispatcher.dispatch(restRequest); Exceptions.expectCompletionException(SecurityException.class, response); assertEquals("Permission to ADMIN is DENY for user Subject:\n\tPrincipal: TestPrincipal [name=lifecycle]\n", auditLogger.getLastRecord()); // Correct user restRequest = new SimpleRequest.Builder().setMethod(GET).setPath("/ctx/secure").setSubject(ADMIN).build(); response = restDispatcher.dispatch(restRequest); assertEquals("Subject:\n\tPrincipal: TestPrincipal [name=admin]\n", join(response).getEntity().toString()); assertEquals("Permission to ADMIN is ALLOW for user Subject:\n\tPrincipal: TestPrincipal [name=admin]\n", auditLogger.getLastRecord()); } private void assertNoResource(RestDispatcher dispatcher, RestRequest restRequest) { try { CompletionStage<RestResponse> response = dispatcher.dispatch(restRequest); if (join(response) != null) Assert.fail(); } catch (Exception ignored) { } } static class EchoResource implements ResourceHandler { @Override public Invocations getInvocations() { return new Invocations.Builder() .invocation().name("doubleVars").method(GET).path("/context/{variable1}/{variable2}").handleWith(this::doubleVars) .invocation().name("tripleVars").method(GET).path("/context/{variable1}/{variable2}/{variable3}").withAction("triple").handleWith(this::tripleVarWithAction) .create(); } private CompletionStage<RestResponse> tripleVarWithAction(RestRequest restRequest) { SimpleRestResponse.Builder responseBuilder = new SimpleRestResponse.Builder(); String variable1 = restRequest.variables().get("variable1"); String variable2 = restRequest.variables().get("variable2"); String variable3 = restRequest.variables().get("variable3"); String action = restRequest.getAction(); return completedFuture(responseBuilder.entity(action + "(" + variable1 + "," + variable2 + "," + variable3 + ")").build()); } private CompletionStage<RestResponse> doubleVars(RestRequest restRequest) { SimpleRestResponse.Builder responseBuilder = new SimpleRestResponse.Builder(); String variable1 = restRequest.variables().get("variable1"); String variable2 = restRequest.variables().get("variable2"); return completedFuture(responseBuilder.entity(variable1 + "," + variable2).build()); } } static class CounterResource implements ResourceHandler { private final Map<String, AtomicInteger> counters = new HashMap<>(); @Override public Invocations getInvocations() { return new Invocations.Builder() .invocation().name("allCounters").method(GET).path("/counters").handleWith(this::listAllCounters) .invocation().name("addCounter").method(POST).path("/counters/{name}").handleWith(this::addCounter) .invocation().name("getCounter").method(GET).path("/counters/{name}").handleWith(this::getCounter) .invocation().name("incrementCounter").method(GET).path("/counters/{name}").withAction("increment").handleWith(this::incrementCounter) .create(); } private CompletionStage<RestResponse> listAllCounters(RestRequest request) { SimpleRestResponse.Builder responseBuilder = new SimpleRestResponse.Builder(); StringBuilder sb = new StringBuilder(); counters.forEach((key, value) -> sb.append(key).append("->").append(value.get())); return completedFuture(responseBuilder.status(200).entity(sb.toString()).build()); } private CompletionStage<RestResponse> addCounter(RestRequest request) { SimpleRestResponse.Builder responseBuilder = new SimpleRestResponse.Builder(); String newCounterName = request.variables().get("name"); if (newCounterName == null) { return completedFuture(responseBuilder.status(503).build()); } counters.put(newCounterName, new AtomicInteger()); return completedFuture(responseBuilder.status(200).build()); } private CompletionStage<RestResponse> getCounter(RestRequest restRequest) { SimpleRestResponse.Builder responseBuilder = new SimpleRestResponse.Builder(); String name = restRequest.variables().get("name"); AtomicInteger atomicInteger = counters.get(name); if (atomicInteger == null) return completedFuture(responseBuilder.status(404).build()); return completedFuture(responseBuilder.status(200).entity(name + "->" + atomicInteger.get()).build()); } private CompletionStage<RestResponse> incrementCounter(RestRequest request) { SimpleRestResponse.Builder responseBuilder = new SimpleRestResponse.Builder(); String name = request.variables().get("name"); if (name == null) return completedFuture(responseBuilder.status(404).build()); counters.get(name).incrementAndGet(); return completedFuture(responseBuilder.status(200).build()); } } static class MemoryResource implements ResourceHandler { @Override public Invocations getInvocations() { return new Invocations.Builder() .invocation().methods(GET, HEAD).path("/jvm/memory").path("/v2/java-memory").handleWith(this::showMemory) .create(); } private CompletionStage<RestResponse> showMemory(RestRequest request) { return completedFuture(new SimpleRestResponse.Builder().entity(String.valueOf(Runtime.getRuntime().freeMemory())).build()); } } static class RootResource implements ResourceHandler { @Override public Invocations getInvocations() { return new Invocations.Builder() .invocation().method(GET).path("/").path("/image.gif").handleWith(this::serveStaticResource) .create(); } private CompletionStage<RestResponse> serveStaticResource(RestRequest restRequest) { return completedFuture(new SimpleRestResponse.Builder().entity("Hello World!").build()); } } static class FileResource implements ResourceHandler { @Override public Invocations getInvocations() { return new Invocations.Builder() .invocation().method(GET).path("/web").path("/web/*").handleWith(this::handleGet) .create(); } private CompletionStage<RestResponse> handleGet(RestRequest restRequest) { String path = restRequest.path(); if (path.endsWith("web/")) { path = path.concat("index.html"); } return completedFuture(new SimpleRestResponse.Builder().entity(path).build()); } } static class SecureResource implements ResourceHandler { @Override public Invocations getInvocations() { return new Invocations.Builder() .invocation().method(GET).path("/secure").permission(AuthorizationPermission.ADMIN).auditContext(AuditContext.SERVER).handleWith(this::handleGet) .create(); } private CompletionStage<RestResponse> handleGet(RestRequest restRequest) { return completedFuture(new SimpleRestResponse.Builder().entity(restRequest.getSubject().toString()).build()); } } }
15,154
48.688525
171
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/framework/impl/SimpleRequest.java
package org.infinispan.rest.framework.impl; import java.net.InetSocketAddress; import java.util.EnumSet; import java.util.List; import java.util.Map; import javax.security.auth.Subject; import org.infinispan.commons.api.CacheContainerAdmin.AdminFlag; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.context.Flag; import org.infinispan.rest.framework.ContentSource; import org.infinispan.rest.framework.Method; import org.infinispan.rest.framework.RestRequest; import io.netty.handler.codec.http.QueryStringDecoder; /** * @since 10.0 */ public class SimpleRequest implements RestRequest { private final Method method; private final String path; private Map<String, String> headers; private final ContentSource contents; private Map<String, String> variables; private String action; private Subject subject; private SimpleRequest(Method method, String path, Map<String, String> headers, ContentSource contents, Subject subject) { QueryStringDecoder queryStringDecoder = new QueryStringDecoder(path); Map<String, List<String>> parameters = queryStringDecoder.parameters(); this.path = queryStringDecoder.path(); this.headers = headers; List<String> action = parameters.get("action"); if (action != null) { this.action = action.iterator().next(); } this.method = method; this.contents = contents; this.subject = subject; } @Override public Method method() { return method; } @Override public String path() { return path; } @Override public String uri() { return null; } @Override public String header(String name) { return null; } @Override public List<String> headers(String name) { return null; } @Override public Iterable<String> headersKeys() { return null; } @Override public InetSocketAddress getRemoteAddress() { return null; } @Override public ContentSource contents() { return contents; } @Override public Map<String, List<String>> parameters() { return null; } @Override public String getParameter(String name) { return null; } @Override public Map<String, String> variables() { return variables; } @Override public String getAction() { return action; } @Override public MediaType contentType() { return MediaType.MATCH_ALL; } @Override public MediaType keyContentType() { return MediaType.MATCH_ALL; } @Override public String getAcceptHeader() { return null; } @Override public String getAuthorizationHeader() { return null; } @Override public String getCacheControlHeader() { return null; } @Override public String getContentTypeHeader() { return null; } @Override public String getEtagIfMatchHeader() { return null; } @Override public String getIfModifiedSinceHeader() { return null; } @Override public String getEtagIfNoneMatchHeader() { return null; } @Override public String getIfUnmodifiedSinceHeader() { return null; } @Override public Long getMaxIdleTimeSecondsHeader() { return null; } @Override public Long getTimeToLiveSecondsHeader() { return null; } @Override public EnumSet<AdminFlag> getAdminFlags() { return null; } @Override public Flag[] getFlags() { return new Flag[0]; } @Override public Long getCreatedHeader() { return null; } @Override public Long getLastUsedHeader() { return null; } @Override public Subject getSubject() { return subject; } @Override public void setSubject(Subject subject) { this.subject = subject; } @Override public void setVariables(Map<String, String> variables) { this.variables = variables; } @Override public void setAction(String action) { this.action = action; } public static class Builder implements RestRequestBuilder<Builder> { private Method method; private String path; private Map<String, String> headers; private ContentSource contents; private Subject subject; public Builder setMethod(Method method) { this.method = method; return this; } public Builder setPath(String path) { this.path = path; return this; } public Builder setHeaders(Map<String, String> headers) { this.headers = headers; return this; } public Builder setContents(ContentSource contents) { this.contents = contents; return this; } public Builder setSubject(Subject subject) { this.subject = subject; return this; } public SimpleRequest build() { return new SimpleRequest(method, path, headers, contents, subject); } } }
5,019
19.658436
124
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/framework/impl/PathInterpreterTest.java
package org.infinispan.rest.framework.impl; import static org.infinispan.rest.framework.impl.PathInterpreter.resolveVariables; import static org.testng.Assert.assertEquals; import java.util.Map; import org.testng.annotations.Test; @Test(groups = "unit", testName = "rest.framework.PathInterpreterTest") public class PathInterpreterTest { @Test public void testSingleVariable() { Map<String, String> res = resolveVariables("{id}", "5435"); assertEquals(1, res.size()); assertEquals(res.get("id"), "5435"); } @Test public void testSingleVariable2() { Map<String, String> res = resolveVariables("{variable_name}", "a"); assertEquals(1, res.size()); assertEquals(res.get("variable_name"), "a"); } @Test public void testDualVariables() { Map<String, String> res = resolveVariables("{cachemanager}-{cache}", "default-mycache"); assertEquals(2, res.size()); assertEquals(res.get("cachemanager"), "default"); assertEquals(res.get("cache"), "mycache"); } @Test public void testDualVariables2() { Map<String, String> res = resolveVariables("{cachemanager}{cache}", "defaultmycache"); assertEquals(0, res.size()); } @Test public void testDualVariables3() { Map<String, String> res = resolveVariables("{a}:{b}", "value1:value2"); assertEquals(2, res.size()); assertEquals(res.get("a"), "value1"); assertEquals(res.get("b"), "value2"); } @Test public void testPrefixSufix() { Map<String, String> res = resolveVariables("prefix_{variable1}_{variable2}_suffix", "prefix_value1_value2_suffix"); assertEquals(2, res.size()); assertEquals(res.get("variable1"), "value1"); assertEquals(res.get("variable2"), "value2"); } @Test public void testSingleVariableWithPrefix() { Map<String, String> res = resolveVariables("counter-{id}", "counter-2345"); assertEquals(1, res.size()); assertEquals(res.get("id"), "2345"); } @Test public void testNull() { Map<String, String> res1 = resolveVariables(null, "whatever"); Map<String, String> res2 = resolveVariables("{hello}", null); assertEquals(0, res1.size()); assertEquals(0, res2.size()); } @Test public void testNonConformantPath() { Map<String, String> res = resolveVariables("{cachemanager}-{cache}", "default"); assertEquals(0, res.size()); } @Test public void testMalformedExpression() { Map<String, String> res = resolveVariables("{counter {id}}", "whatever"); assertEquals(0, res.size()); } @Test public void testMalformedExpression2() { Map<String, String> res = resolveVariables("{counter }id}-", "whatever"); assertEquals(0, res.size()); } }
2,798
26.99
121
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/framework/impl/ResourceManagerImplTest.java
package org.infinispan.rest.framework.impl; import static org.infinispan.rest.framework.LookupResult.Status.FOUND; import static org.infinispan.rest.framework.LookupResult.Status.INVALID_ACTION; import static org.infinispan.rest.framework.LookupResult.Status.INVALID_METHOD; import static org.infinispan.rest.framework.LookupResult.Status.NOT_FOUND; import static org.infinispan.rest.framework.Method.DELETE; import static org.infinispan.rest.framework.Method.GET; import static org.infinispan.rest.framework.Method.HEAD; import static org.infinispan.rest.framework.Method.POST; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.util.Arrays; import org.infinispan.rest.framework.LookupResult; import org.infinispan.rest.framework.Method; import org.infinispan.rest.framework.RegistrationException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "unit", testName = "rest.framework.ResourceManagerImplTest") public class ResourceManagerImplTest { private ResourceManagerImpl resourceManager; @BeforeMethod public void setUp() { resourceManager = new ResourceManagerImpl(); } @Test(expectedExceptions = RegistrationException.class, expectedExceptionsMessageRegExp = "ISPN.*Cannot register invocation 'HandlerB'.*") public void testShouldPreventOverlappingVariablePaths() { registerHandler("/", "HandlerA", "/{pathA}"); registerHandler("/", "HandlerB", "/{pathB}"); } @Test(expectedExceptions = RegistrationException.class, expectedExceptionsMessageRegExp = "ISPN.*/path/\\{b\\}.*conflicts with.*/path/a.*") public void testPreventAmbiguousPaths() { registerHandler("/", "handler1", "/path/a"); registerHandler("/", "handler2", "/path/{b}"); } @Test(expectedExceptions = RegistrationException.class, expectedExceptionsMessageRegExp = "ISPN.*/path/\\{b\\}.*conflicts with.*/path/\\{a\\}.*") public void testPreventVariableNameConflict() { registerHandler("/", "handler1", "/path/{a}/"); registerHandler("/", "handler1", "/path/{b}/sub-path"); } public void testAllowRegistrationForDifferentMethods() { registerHandler("/", "HandlerA", GET, "/root/a/{pathA}"); registerHandler("/", "HandlerB", POST, "/root/a/{pathA}"); } public void testLookupRepeatedPaths() { registerHandler("/", "Handler", GET, "/root/path/path"); assertNotNull(resourceManager.lookupResource(GET, "/root/path/path")); } @Test public void testLookupHandler() { registerHandler("root", "CompaniesHandler", "/companies", "/companies/{company}", "/companies/{company}/{id}"); registerHandler("root", "StocksHandler", "/stocks/{stock}", "/stocks/{stock}/{currency}"); registerHandler("root", "DirectorsHandler", "/directors", "/directors/director", "/directors/director/{personId}"); registerHandler("root", "InfoHandler", "/info", "/info/jvm", "/info/jvm/{format}", "/info/{format}/{encoding}"); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/root/dummy").getStatus()); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/fake/").getStatus()); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/").getStatus()); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/root/stocks").getStatus()); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/root/stocks/2/USD/1").getStatus()); assertInvocation(resourceManager.lookupResource(GET, "/root/stocks/2"), "StocksHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/stocks/2/USD"), "StocksHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/directors"), "DirectorsHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/directors/director"), "DirectorsHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/directors/director/John"), "DirectorsHandler"); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/root/directors/1345").getStatus()); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/root/directors/director/Tim/123").getStatus()); assertInvocation(resourceManager.lookupResource(GET, "/root/companies"), "CompaniesHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/info"), "InfoHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/info/jvm"), "InfoHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/info/jvm/json"), "InfoHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/info/json/zip"), "InfoHandler"); } @Test public void testLookupStatuses() { registerHandler("ctx", "handler1", "/items/{item}"); registerHandlerWithAction("ctx", new Method[]{GET}, "handler2", "clear", "/items/{item}/{sub}"); LookupResult lookupResult = resourceManager.lookupResource(GET, "/invalid"); assertEquals(NOT_FOUND, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(GET, "/ctx/items/1"); assertEquals(FOUND, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(DELETE, "/ctx/items/1"); assertEquals(INVALID_METHOD, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(GET, "/ctx/items/1/1", "clear"); assertEquals(FOUND, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(GET, "/ctx/items/1/1"); assertEquals(INVALID_ACTION, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(GET, "/ctx/items/1/1", "invalid"); assertEquals(INVALID_ACTION, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(GET, "/ctx/items/1", "invalid"); assertEquals(INVALID_ACTION, lookupResult.getStatus()); } private void assertInvocation(LookupResult result, String name) { assertEquals(name, result.getInvocation().getName()); } private void registerHandler(String ctx, String handlerName, Method method, String... paths) { resourceManager.registerResource(ctx, () -> { Invocations.Builder builder = new Invocations.Builder(); Arrays.stream(paths).forEach(p -> builder.invocation().method(method).path(p).name(handlerName).handleWith(restRequest -> null)); return builder.create(); }); } private void registerHandlerWithAction(String ctx, Method[] methods, String handlerName, String action, String... paths) { resourceManager.registerResource(ctx, () -> { Invocations.Builder builder = new Invocations.Builder(); Arrays.stream(paths).forEach(p -> { InvocationImpl.Builder invocation = builder.invocation(); invocation.methods(methods).path(p).name(handlerName).handleWith(restRequest -> null); if (action != null) invocation.withAction(action); }); return builder.create(); }); } private void registerHandler(String ctx, String handlerName, String... paths) { registerHandlerWithAction(ctx, new Method[]{GET, HEAD, POST}, handlerName, null, paths); } }
7,241
48.944828
148
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/ClusterResourceTest.java
package org.infinispan.rest.resources; import static org.infinispan.client.rest.configuration.Protocol.HTTP_11; import static org.infinispan.client.rest.configuration.Protocol.HTTP_20; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.List; import java.util.concurrent.CompletionStage; import java.util.regex.Pattern; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.internal.Json; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.ClusterResourceTest") public class ClusterResourceTest extends AbstractRestResourceTest { @Override public Object[] factory() { return new Object[] { new ClusterResourceTest().withSecurity(false).protocol(HTTP_11).ssl(false).browser(false), new ClusterResourceTest().withSecurity(false).protocol(HTTP_11).ssl(false).browser(true), new ClusterResourceTest().withSecurity(true).protocol(HTTP_20).ssl(false).browser(false), new ClusterResourceTest().withSecurity(true).protocol(HTTP_20).ssl(false).browser(true), new ClusterResourceTest().withSecurity(true).protocol(HTTP_11).ssl(true).browser(false), new ClusterResourceTest().withSecurity(true).protocol(HTTP_11).ssl(true).browser(true), new ClusterResourceTest().withSecurity(true).protocol(HTTP_20).ssl(true).browser(false), new ClusterResourceTest().withSecurity(true).protocol(HTTP_20).ssl(true).browser(true), }; } @Test public void testClusterDistribution() { CompletionStage<RestResponse> response = adminClient.cluster().distribution(); assertThat(response).isOk(); Json json = Json.read(join(response).getBody()); assertTrue(json.isArray()); List<Json> list = json.asJsonList(); assertEquals(NUM_SERVERS, list.size()); Pattern pattern = Pattern.compile(this.getClass().getSimpleName() + "-Node[a-zA-Z]$"); for (Json node : list) { assertTrue(node.at("memory_available").asLong() > 0); assertTrue(node.at("memory_used").asLong() > 0); assertEquals(node.at("node_addresses").asJsonList().size(), 1); assertTrue(pattern.matcher(node.at("node_name").asString()).matches()); } } }
2,407
44.433962
102
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/CounterResourceTest.java
package org.infinispan.rest.resources; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON_TYPE; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Collection; import java.util.concurrent.CompletionStage; import org.infinispan.client.rest.RestCounterClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.counter.EmbeddedCounterManagerFactory; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.Storage; import org.infinispan.counter.configuration.AbstractCounterConfiguration; import org.infinispan.counter.configuration.ConvertUtil; import org.infinispan.manager.EmbeddedCacheManager; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.CounterResourceTest") public class CounterResourceTest extends AbstractRestResourceTest { @Override protected void defineCaches(EmbeddedCacheManager cm) { CounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager(cm); counterManager.defineCounter("weak", CounterConfiguration.builder(CounterType.WEAK).build()); counterManager.defineCounter("strong", CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG).build()); } @Override public Object[] factory() { return new Object[]{ new CounterResourceTest().withSecurity(false).browser(false), new CounterResourceTest().withSecurity(false).browser(true), new CounterResourceTest().withSecurity(true).browser(false), new CounterResourceTest().withSecurity(true).browser(true), }; } @Test public void testWeakCounterLifecycle() { CounterConfiguration counterConfig = CounterConfiguration.builder(CounterType.WEAK) .initialValue(5).storage(Storage.VOLATILE).concurrencyLevel(6).build(); createCounter("sample-counter", counterConfig); RestCounterClient counterClient = client.counter("sample-counter"); RestResponse response = join(counterClient.configuration(APPLICATION_JSON_TYPE)); Json jsonNode = Json.read(response.getBody()); Json config = jsonNode.at("weak-counter"); assertEquals(config.at("initial-value").asInteger(), 5); assertEquals(config.at("storage").asString(), "VOLATILE"); assertEquals(config.at("concurrency-level").asInteger(), 6); response = join(counterClient.delete()); assertThat(response).isOk(); response = join(counterClient.configuration()); assertThat(response).isNotFound(); } @Test public void testWeakCounterOps() { String name = "weak-test"; createCounter(name, CounterConfiguration.builder(CounterType.WEAK).initialValue(5).build()); RestCounterClient counterClient = client.counter(name); CompletionStage<RestResponse> response = counterClient.increment(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 6); response = counterClient.increment(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 7); response = counterClient.decrement(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 6); response = counterClient.decrement(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 5); response = counterClient.add(10); assertThat(response).hasNoContent(); waitForCounterToReach(name, 15); response = counterClient.reset(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 5); } @Test public void testStrongCounterOps() { String name = "strong-test"; createCounter(name, CounterConfiguration.builder(CounterType.BOUNDED_STRONG).lowerBound(0).upperBound(100) .initialValue(0).build()); RestCounterClient counterClient = client.counter(name); CompletionStage<RestResponse> response = counterClient.increment(); assertThat(response).hasReturnedText("1"); response = counterClient.increment(); assertThat(response).hasReturnedText("2"); response = counterClient.decrement(); assertThat(response).hasReturnedText("1"); response = counterClient.decrement(); assertThat(response).hasReturnedText("0"); response = counterClient.add(35); assertThat(response).hasReturnedText("35"); waitForCounterToReach(name, 35); response = counterClient.compareAndSet(5, 32); assertThat(response).hasReturnedText("false"); response = counterClient.compareAndSet(35, 50); assertThat(response).hasReturnedText("true"); waitForCounterToReach(name, 50); response = counterClient.compareAndSwap(50, 90); assertThat(response).hasReturnedText("50"); response = counterClient.get(); assertThat(response).hasReturnedText("90"); response = counterClient.getAndSet(10); assertThat(response).hasReturnedText("90"); } @Test public void testCounterNames() { String name = "weak-one-%d"; for (int i = 0; i < 5; i++) { createCounter(String.format(name, i), CounterConfiguration.builder(CounterType.WEAK).initialValue(5).build()); } RestResponse response = join(client.counters()); assertThat(response).isOk(); Json jsonNode = Json.read(response.getBody()); Collection<String> counterNames = EmbeddedCounterManagerFactory.asCounterManager(cacheManagers.get(0)).getCounterNames(); int size = jsonNode.asList().size(); assertEquals(counterNames.size(), size); for (int i = 0; i < size; i++) { assertTrue(counterNames.contains(jsonNode.at(i).asString())); } } @Test public void testCounterCreation() { String counterName = "counter-creation"; createCounter(counterName, CounterConfiguration.builder(CounterType.WEAK).initialValue(1).build()); assertThat(doCounterCreateRequest(counterName, CounterConfiguration.builder(CounterType.WEAK).initialValue(1).build())).isNotModified(); assertThat(doCounterCreateRequest(counterName, CounterConfiguration.builder(CounterType.BOUNDED_STRONG).initialValue(2).build())).isNotModified(); } private CompletionStage<RestResponse> doCounterCreateRequest(String name, CounterConfiguration configuration) { AbstractCounterConfiguration config = ConvertUtil.configToParsedConfig(name, configuration); RestEntity restEntity = RestEntity.create(APPLICATION_JSON, counterConfigToJson(config)); return client.counter(name).create(restEntity); } private void createCounter(String name, CounterConfiguration configuration) { assertThat(doCounterCreateRequest(name, configuration)).isOk(); } private void waitForCounterToReach(String name, int i) { RestCounterClient counterClient = client.counter(name); eventually(() -> { RestResponse r = join(counterClient.get()); assertThat(r).isOk(); long value = Long.parseLong(r.getBody()); return value == i; }); } }
7,463
38.702128
152
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/MultiResourceTest.java
package org.infinispan.rest.resources; import static org.infinispan.client.rest.configuration.Protocol.HTTP_11; import static org.infinispan.client.rest.configuration.Protocol.HTTP_20; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.infinispan.client.rest.RestCounterClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.RestSchemaClient; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.configuration.AbstractCounterConfiguration; import org.infinispan.counter.configuration.ConvertUtil; import org.infinispan.rest.assertion.ResponseAssertion; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * Test for calling multiple resources concurrently. * * @since 12.0 */ @Test(groups = "functional", testName = "rest.MultiResourceTest") public class MultiResourceTest extends AbstractRestResourceTest { private ExecutorService service; @Override public Object[] factory() { return new Object[]{ new MultiResourceTest().withSecurity(false).protocol(HTTP_11).ssl(false).browser(false), new MultiResourceTest().withSecurity(false).protocol(HTTP_11).ssl(false).browser(true), new MultiResourceTest().withSecurity(true).protocol(HTTP_20).ssl(false).browser(false), new MultiResourceTest().withSecurity(true).protocol(HTTP_20).ssl(false).browser(true), new MultiResourceTest().withSecurity(true).protocol(HTTP_11).ssl(true).browser(false), new MultiResourceTest().withSecurity(true).protocol(HTTP_11).ssl(true).browser(true), new MultiResourceTest().withSecurity(true).protocol(HTTP_20).ssl(true).browser(false), new MultiResourceTest().withSecurity(true).protocol(HTTP_20).ssl(true).browser(true), }; } @BeforeMethod public void setUp() throws Exception { service = Executors.newFixedThreadPool(5); createCaches("cache1", "cache2"); createCounters("counter1", "counter2"); createSchema("1.proto", "message A1 {}"); createSchema("2.proto", "message B1 {}"); } @AfterMethod public void tearDown() { join(client.cache("cache1").delete()); join(client.cache("cache2").delete()); join(client.counter("counter1").delete()); join(client.counter("counter2").delete()); join(client.schemas().delete("1.proto")); join(client.schemas().delete("2.proto")); service.shutdown(); } @Test public void testMultiThreadedOps() throws Exception { CountDownLatch startLatch = new CountDownLatch(1); CompletableFuture<Boolean> r1 = doCacheReadWrite(startLatch, "cache1"); CompletableFuture<Boolean> r2 = doCacheReadWrite(startLatch, "cache2"); CompletableFuture<Boolean> r3 = doCounterReadAndWrite(startLatch, "counter1"); CompletableFuture<Boolean> r4 = doCounterReadAndWrite(startLatch, "counter2"); CompletableFuture<Boolean> r5 = doSchemaReadWrite(startLatch, "1.proto", "A"); CompletableFuture<Boolean> r6 = doSchemaReadWrite(startLatch, "2.proto", "B"); List<CompletableFuture<Boolean>> futures = Arrays.asList(r1, r2, r3, r4, r5, r6); startLatch.countDown(); for (CompletableFuture<Boolean> future : futures) { CompletableFutures.await(future, 10, TimeUnit.SECONDS); assertTrue(future.get()); } } private CompletableFuture<Boolean> doSchemaReadWrite(CountDownLatch startLatch, String protoName, String messagePrefix) { return CompletableFuture.supplyAsync(() -> { try { String messageFormat = "message %s%d {}"; startLatch.await(); createSchema(protoName, String.format(messageFormat, messagePrefix, 1)); createSchema(protoName, String.format(messageFormat, messagePrefix, 2)); createSchema(protoName, String.format(messageFormat, messagePrefix, 3)); String lastSchema = String.format(messageFormat, messagePrefix, 4); createSchema(protoName, lastSchema); assertEquals(lastSchema, getProtobuf(protoName)); return true; } catch (Throwable e) { e.printStackTrace(); return false; } }, service); } private CompletableFuture<Boolean> doCounterReadAndWrite(CountDownLatch startLatch, String counterName) { return CompletableFuture.supplyAsync(() -> { try { startLatch.await(); callCounterOp(counterName, "increment"); callCounterOp(counterName, "increment"); callCounterOp(counterName, "increment"); callCounterOp(counterName, "increment"); callCounterOp(counterName, "increment"); callCounterOp(counterName, "decrement"); callCounterOp(counterName, "decrement"); callCounterOp(counterName, "decrement"); RestCounterClient counterClient = client.counter(counterName); eventually(() -> { RestResponse r = join(counterClient.get()); ResponseAssertion.assertThat(r).isOk(); long value = Long.parseLong(r.getBody()); return value == 2; }); return true; } catch (Throwable e) { e.printStackTrace(); return false; } }, service); } private CompletableFuture<Boolean> doCacheReadWrite(CountDownLatch startLatch, String cacheName) { return CompletableFuture.supplyAsync(() -> { try { startLatch.await(); changeValue(cacheName, "1", "1"); changeValue(cacheName, "2", "2"); changeValue(cacheName, "3", "3"); changeValue(cacheName, "1", "1'"); changeValue(cacheName, "2", "2'"); changeValue(cacheName, "3", "3'"); assertEquals("1'", getValue(cacheName, "1")); assertEquals("2'", getValue(cacheName, "2")); assertEquals("3'", getValue(cacheName, "3")); return true; } catch (Throwable e) { e.printStackTrace(); return false; } }, service); } private void callCounterOp(String name, String op) { RestCounterClient counterClient = client.counter(name); RestResponse response = null; switch (op) { case "increment": response = join(counterClient.increment()); break; case "decrement": response = join(counterClient.decrement()); break; default: Assert.fail("Invalid operation " + op); } ResponseAssertion.assertThat(response).isOk(); } private String getValue(String cacheName, String key) { RestResponse response = join(client.cache(cacheName).get(key)); ResponseAssertion.assertThat(response).isOk(); return response.getBody(); } private void changeValue(String cacheName, String key, String value) { RestResponse response = join(client.cache(cacheName).put(key, value)); ResponseAssertion.assertThat(response).isOk(); } private void createSchema(String name, String value) throws Exception { RestSchemaClient schemas = client.schemas(); RestResponse response = join(schemas.put(name, value)); ResponseAssertion.assertThat(response).isOk(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(response.getBody()); assertEquals("null", jsonNode.get("error").asText()); } private String getProtobuf(String name) { RestSchemaClient schemas = client.schemas(); RestResponse response = join(schemas.get(name)); ResponseAssertion.assertThat(response).isOk(); return response.getBody(); } private void createCounters(String... names) { CounterConfiguration configuration = CounterConfiguration .builder(CounterType.BOUNDED_STRONG) .lowerBound(0).upperBound(100) .initialValue(0).build(); for (String counterName : names) { AbstractCounterConfiguration config = ConvertUtil.configToParsedConfig(counterName, configuration); RestResponse response = join(client.counter(counterName).create(RestEntity.create(APPLICATION_JSON, counterConfigToJson(config)))); ResponseAssertion.assertThat(response).isOk(); } } private void createCaches(String... names) { RestEntity jsonEntity = RestEntity.create(APPLICATION_JSON, "{}"); for (String cacheName : names) { CompletionStage<RestResponse> response = client.cache(cacheName).createWithConfiguration(jsonEntity, CacheContainerAdmin.AdminFlag.VOLATILE); ResponseAssertion.assertThat(response).isOk(); } } }
9,634
40.175214
150
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/WeakSSEListener.java
package org.infinispan.rest.resources; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import org.infinispan.commons.util.ByRef; import org.infinispan.test.TestException; import org.infinispan.util.KeyValuePair; /** * A listener for SSE without ordering restriction. */ public class WeakSSEListener extends SSEListener { private final ConcurrentMap<String, List<String>> backup = new ConcurrentHashMap<>(); @Override public void expectEvent(String type, String subString, Consumer<KeyValuePair<String, String>> consumer) throws InterruptedException { CompletableFuture<KeyValuePair<String, String>> waitEvent = CompletableFuture.supplyAsync(() -> { ByRef<KeyValuePair<String, String>> pair = new ByRef<>(null); backup.computeIfPresent(type, (k, v) -> { int index = -1; for (int i = 0; i < v.size() && pair.get() == null; i++) { if (v.get(i).contains(subString)) { pair.set(new KeyValuePair<>(k, v.get(i))); index = i; break; } } if (index >= 0) v.remove(index); return v; }); while (pair.get() == null) { try { KeyValuePair<String, String> event = events.poll(10, TimeUnit.SECONDS); assert event != null : "No event received"; if (type.equals(event.getKey()) && event.getValue().contains(subString)) { pair.set(event); break; } else { backup.compute(event.getKey(), (k, v) -> { if (v == null) v = new ArrayList<>(); v.add(event.getValue()); return v; }); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new TestException(e); } } assert pair.get() != null : "Should contain event with: " + subString; return pair.get(); }); try { KeyValuePair<String, String> pair = waitEvent.get(10, TimeUnit.SECONDS); consumer.accept(pair); } catch (ExecutionException | TimeoutException e) { throw new TestException(e); } } }
2,614
33.866667
136
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/ProtobufResourceTest.java
package org.infinispan.rest.resources; import static org.infinispan.commons.util.Util.getResourceAsString; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.CompletionStage; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.RestSchemaClient; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.query.remote.ProtobufMetadataManager; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.security.Security; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.ProtobufResourceTest") public class ProtobufResourceTest extends AbstractRestResourceTest { @Override public Object[] factory() { return new Object[]{ new ProtobufResourceTest().withSecurity(false).browser(false), new ProtobufResourceTest().withSecurity(false).browser(true), new ProtobufResourceTest().withSecurity(true).browser(false), new ProtobufResourceTest().withSecurity(true).browser(true), }; } @BeforeMethod(alwaysRun = true) @Override public void createBeforeMethod() { //Clear schema cache to avoid conflicts between methods Security.doAs(ADMIN, () -> cacheManagers.get(0).getCache(ProtobufMetadataManager.PROTOBUF_METADATA_CACHE_NAME).clear()); } public void listSchemasWhenEmpty() { CompletionStage<RestResponse> response = client.schemas().names(); ResponseAssertion.assertThat(response).isOk(); Json jsonNode = Json.read(join(response).getBody()); assertEquals(0, jsonNode.asList().size()); } @Test public void getNotExistingSchema() { CompletionStage<RestResponse> response = client.schemas().get("coco"); ResponseAssertion.assertThat(response).isNotFound(); } @Test public void updateNonExistingSchema() throws Exception { String person = getResourceAsString("person.proto", getClass().getClassLoader()); CompletionStage<RestResponse> response = client.schemas().put("person", person); ResponseAssertion.assertThat(response).isOk(); } @Test public void putAndGetWrongProtobuf() throws Exception { RestSchemaClient schemaClient = client.schemas(); String errorProto = getResourceAsString("error.proto", getClass().getClassLoader()); RestResponse response = join(schemaClient.post("error", errorProto)); String cause = "java.lang.IllegalStateException:" + " Syntax error in error.proto at 3:8: unexpected label: messoge"; ResponseAssertion.assertThat(response).isOk(); Json jsonNode = Json.read(response.getBody()); assertEquals("error.proto", jsonNode.at("name").asString()); assertEquals("Schema error.proto has errors", jsonNode.at("error").at("message").asString()); assertEquals(cause, jsonNode.at("error").at("cause").asString()); // Read adding .proto should also work response = join(schemaClient.get("error")); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentEqualToFile("error.proto"); checkListProtobufEndpointUrl("error.proto", cause); } @Test public void crudSchema() throws Exception { RestSchemaClient schemaClient = client.schemas(); String personProto = getResourceAsString("person.proto", getClass().getClassLoader()); // Create RestResponse response = join(schemaClient.post("person", personProto)); ResponseAssertion.assertThat(response).isOk(); Json jsonNode = Json.read(response.getBody()); assertTrue(jsonNode.at("error").isNull()); // Read response = join(schemaClient.get("person")); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentEqualToFile("person.proto"); // Read adding .proto should also work response = join(schemaClient.get("person.proto")); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentEqualToFile("person.proto"); // Update response = join(schemaClient.put("person", personProto)); ResponseAssertion.assertThat(response).isOk(); // Delete response = join(schemaClient.delete("person")); ResponseAssertion.assertThat(response).isOk(); response = join(schemaClient.get("person")); ResponseAssertion.assertThat(response).isNotFound(); } @Test public void createTwiceSchema() throws Exception { RestSchemaClient schemaClient = client.schemas(); String personProto = getResourceAsString("person.proto", getClass().getClassLoader()); CompletionStage<RestResponse> response = schemaClient.post("person", personProto); ResponseAssertion.assertThat(response).isOk(); response = schemaClient.post("person", personProto); ResponseAssertion.assertThat(response).isConflicted(); } @Test public void addAndGetListOrderedByName() throws Exception { RestSchemaClient schemaClient = client.schemas(); String personProto = getResourceAsString("person.proto", getClass().getClassLoader()); join(schemaClient.post("users", personProto)); join(schemaClient.post("people", personProto)); join(schemaClient.post("dancers", personProto)); RestResponse response = join(schemaClient.names()); ResponseAssertion.assertThat(response).isOk(); Json jsonNode = Json.read(response.getBody()); assertEquals(3, jsonNode.asList().size()); assertEquals("dancers.proto", jsonNode.at(0).at("name").asString()); assertEquals("people.proto", jsonNode.at(1).at("name").asString()); assertEquals("users.proto", jsonNode.at(2).at("name").asString()); } @Test public void getSchemaTypes() throws Exception { RestSchemaClient schemaClient = client.schemas(); String personProto = getResourceAsString("person.proto", getClass().getClassLoader()); join(schemaClient.post("users", personProto)); RestResponse response = join(schemaClient.types()); ResponseAssertion.assertThat(response).isOk(); Json jsonNode = Json.read(response.getBody()); assertEquals(4, jsonNode.asList().size()); assertTrue(jsonNode.asList().contains("org.infinispan.rest.search.entity.Person")); } @Test public void uploadEmptySchema() { CompletionStage<RestResponse> response = client.schemas().put("empty", ""); ResponseAssertion.assertThat(response).isBadRequest(); } private void checkListProtobufEndpointUrl(String fileName, String errorMessage) { RestSchemaClient schemaClient = client.schemas(); RestResponse response = join(schemaClient.names()); Json jsonNode = Json.read(response.getBody()); assertEquals(1, jsonNode.asList().size()); assertEquals(fileName, jsonNode.at(0).at("name").asString()); assertEquals("Schema error.proto has errors", jsonNode.at(0).at("error").at("message").asString()); assertEquals(errorMessage, jsonNode.at(0).at("error").at("cause").asString()); } }
7,222
38.043243
126
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/XSiteResourceTest.java
package org.infinispan.rest.resources; import static org.infinispan.commons.api.CacheContainerAdmin.AdminFlag.VOLATILE; import static org.infinispan.rest.helper.RestResponses.assertNoContent; import static org.infinispan.rest.helper.RestResponses.assertStatus; import static org.infinispan.rest.helper.RestResponses.assertSuccessful; import static org.infinispan.rest.helper.RestResponses.jsonResponseBody; import static org.infinispan.rest.helper.RestResponses.responseBody; import static org.infinispan.rest.helper.RestResponses.responseStatus; import static org.infinispan.test.TestingUtil.extractGlobalComponent; import static org.infinispan.test.TestingUtil.wrapGlobalComponent; import static org.infinispan.xsite.XSiteAdminOperations.OFFLINE; import static org.infinispan.xsite.XSiteAdminOperations.ONLINE; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Function; import java.util.stream.IntStream; import org.infinispan.Cache; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestCacheManagerClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.configuration.RestClientConfiguration; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.manager.EmbeddedCacheManagerAdmin; import org.infinispan.remoting.responses.SuccessfulResponse; import org.infinispan.remoting.transport.AbstractDelegatingTransport; import org.infinispan.remoting.transport.Transport; import org.infinispan.remoting.transport.XSiteResponse; import org.infinispan.remoting.transport.impl.XSiteResponseImpl; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.test.TestingUtil; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.infinispan.xsite.XSiteBackup; import org.infinispan.xsite.XSiteReplicateCommand; import org.infinispan.xsite.statetransfer.XSiteStatePushCommand; import org.infinispan.xsite.status.TakeOfflineManager; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import net.jcip.annotations.GuardedBy; /** * @since 10.0 */ @Test(groups = "xsite", testName = "rest.XSiteResourceTest") public class XSiteResourceTest extends AbstractMultipleSitesTest { private static final String LON = "LON-1"; private static final String NYC = "NYC-2"; private static final String SFO = "SFO-3"; private static final String CACHE_1 = "CACHE_1"; private static final String CACHE_2 = "CACHE_2"; private static final String CACHE_MANAGER = "default"; private final Map<String, RestServerHelper> restServerPerSite = new HashMap<>(2); private final Map<String, RestClient> clientPerSite = new HashMap<>(2); protected int defaultNumberOfSites() { return 3; } /** * @return the number of nodes per site. */ protected int defaultNumberOfNodes() { return 1; } @BeforeClass public void startServers() { sites.forEach(site -> { String siteName = site.getSiteName(); EmbeddedCacheManager cm = site.cacheManagers().iterator().next(); RestServerHelper restServerHelper = new RestServerHelper(cm); restServerHelper.start(TestResourceTracker.getCurrentTestShortName()); restServerPerSite.put(siteName, restServerHelper); RestClientConfiguration clientConfig = new RestClientConfigurationBuilder() .addServer().host("127.0.0.1") .port(restServerHelper.getPort()) .build(); RestClient client = RestClient.forConfiguration(clientConfig); clientPerSite.put(siteName, client); }); } private RestCacheClient getCacheClient(String site) { RestClient restClient = clientPerSite.get(site); return restClient.cache(CACHE_1); } @Override protected GlobalConfigurationBuilder defaultGlobalConfigurationForSite(int siteIndex) { GlobalConfigurationBuilder configurationBuilder = super.defaultGlobalConfigurationForSite(siteIndex); configurationBuilder.cacheManagerName("default"); return configurationBuilder; } @AfterClass(alwaysRun = true) public void clean() { clientPerSite.values().forEach(cli -> { try { cli.close(); } catch (IOException ignored) { } }); restServerPerSite.values().forEach(RestServerHelper::stop); } @AfterMethod(alwaysRun = true) public void cleanCache() { while (site(LON).cacheManagers().size() > 1) { site(LON).kill(1); site(LON).waitForClusterToForm(CACHE_1); site(LON).waitForClusterToForm(CACHE_2); } assertNoContent(getCacheClient(LON).clear()); assertNoContent(getCacheClient(NYC).clear()); } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.clustering().hash().numSegments(2); return builder; } @Test public void testObtainBackupStatus() { assertEquals(ONLINE, getBackupStatus(LON, NYC)); assertEquals(ONLINE, getBackupStatus(LON, SFO)); assertEquals(ONLINE, getBackupStatus(NYC, LON)); assertEquals(ONLINE, getBackupStatus(NYC, SFO)); } @Test public void testInvalidCache() { RestClient client = clientPerSite.get(LON); assertStatus(404, client.cache("invalid-cache").xsiteBackups()); } @Test public void testInvalidSite() { RestClient client = clientPerSite.get(LON); RestCacheClient cache = client.cache(CACHE_1); assertStatus(404, cache.backupStatus("invalid-site")); } @Test public void testOnlineOffline() { testOnlineOffline(LON, NYC); testOnlineOffline(NYC, LON); } @Test public void testBackups() { RestCacheClient cache = getCacheClient(LON); Json status = jsonResponseBody(cache.xsiteBackups()); assertEquals(ONLINE, status.at(NYC).at("status").asString()); // add a second node TestSite site = site(LON); EmbeddedCacheManager cm = site.addCacheManager(null, defaultGlobalConfigurationForSite(site.getSiteIndex()), defaultConfigurationForSite(site.getSiteIndex()), false); site.waitForClusterToForm(CACHE_1); site.waitForClusterToForm(CACHE_2); TakeOfflineManager takeOfflineManager = TestingUtil.extractComponent(cm.getCache(CACHE_1), TakeOfflineManager.class); takeOfflineManager.takeSiteOffline(NYC); String node1 = String.valueOf(site.cacheManagers().get(0).getAddress()); String node2 = String.valueOf(cm.getAddress()); status = jsonResponseBody(cache.xsiteBackups()); assertEquals("mixed", status.at(NYC).at("status").asString()); assertEquals(status.at(NYC).at("online").asJsonList().iterator().next().asString(), node1); assertEquals(status.at(NYC).at("offline").asJsonList().iterator().next().asString(), node2); assertFalse(status.at(NYC).has("mixed")); status = jsonResponseBody(cache.backupStatus(NYC)); assertEquals(ONLINE, status.at(node1).asString()); assertEquals(OFFLINE, status.at(node2).asString()); // bring NYC online takeOfflineManager.bringSiteOnline(NYC); status = jsonResponseBody(cache.xsiteBackups()); assertEquals(ONLINE, status.at(NYC).at("status").asString()); status = jsonResponseBody(cache.backupStatus(NYC)); assertEquals(ONLINE, status.at(node1).asString()); assertEquals(ONLINE, status.at(node2).asString()); } @Test public void testPushState() { RestCacheClient cache = getCacheClient(LON); RestCacheClient backupCache = getCacheClient(NYC); String key = "key"; String value = "value"; Function<String, Integer> keyOnBackup = k -> responseStatus(backupCache.get(key)); takeBackupOffline(LON, NYC); assertEquals(OFFLINE, getBackupStatus(LON, NYC)); assertEquals(ONLINE, getBackupStatus(LON, SFO)); assertNoContent(cache.put(key, value)); assertEquals(404, (int) keyOnBackup.apply(key)); assertSuccessful(cache.pushSiteState(NYC)); assertEquals(ONLINE, getBackupStatus(LON, NYC)); eventuallyEquals("OK", () -> pushStateStatus(cache, NYC)); assertEquals(200, responseStatus(backupCache.get(key))); } @Test public void testCancelPushState() throws Exception { RestCacheClient cache = getCacheClient(LON); RestCacheClient backupCache = getCacheClient(NYC); // Take backup offline takeBackupOffline(LON, NYC); assertEquals(OFFLINE, getBackupStatus(LON, NYC)); // Write in the cache int entries = 50; IntStream.range(0, entries).forEach(i -> assertNoContent(cache.put(String.valueOf(i), "value"))); // Backup should be empty assertEquals(entries, getCacheSize(cache)); assertEquals(0, getCacheSize(backupCache)); // Start state push BlockXSitePushStateTransport transport = BlockXSitePushStateTransport.replace(cache(LON, 0)); transport.startBlocking(); assertSuccessful(cache.pushSiteState(NYC)); transport.waitForCommand(); // Cancel push assertSuccessful(cache.cancelPushState(NYC)); transport.stopBlocking(); Json status = jsonResponseBody(cache.pushStateStatus()); assertEquals("CANCELED", status.at(NYC).asString()); // Clear status assertSuccessful(cache.clearPushStateStatus()); status = jsonResponseBody(cache.pushStateStatus()); assertEquals(2, status.asMap().size()); assertEquals("IDLE", status.asMap().get(NYC)); assertEquals("IDLE", status.asMap().get(SFO)); assertSuccessful(cache.cancelReceiveState(NYC)); } @Test public void testTakeOfflineConfig() { RestCacheClient cacheClient = getCacheClient(LON); Json takeOfflineConfig = jsonResponseBody(cacheClient.getXSiteTakeOfflineConfig(NYC)); assertEquals(0, takeOfflineConfig.at("after_failures").asInteger()); assertEquals(0, takeOfflineConfig.at("min_wait").asInteger()); assertNoContent(cacheClient.updateXSiteTakeOfflineConfig(NYC, 5, 1000)); takeOfflineConfig = jsonResponseBody(cacheClient.getXSiteTakeOfflineConfig(NYC)); assertEquals(5, takeOfflineConfig.at("after_failures").asInteger()); assertEquals(1000, takeOfflineConfig.at("min_wait").asInteger()); } @Test public void testInvalidInputTakeOffline() { RestClient restClient = clientPerSite.get(LON); String url = String.format("/rest/v2/caches/%s/x-site/backups/%s/take-offline-config", CACHE_1, NYC); assertStatus(400, restClient.raw().putValue(url, new HashMap<>(), "invalid", "application/json")); } @Test public void testGetStatusAllCaches() { RestClient restClient = clientPerSite.get(LON); assertAllSitesOnline(restClient); assertSuccessful(restClient.cache(CACHE_2).takeSiteOffline(NYC)); Json json = jsonResponseBody(restClient.cacheManager(CACHE_MANAGER).backupStatuses()); assertEquals(json.at(NYC).at("status").asString(), "mixed"); assertEquals(json.at(NYC).at("online").asJsonList().iterator().next().asString(), CACHE_1); assertEquals(json.at(NYC).at("offline").asJsonList().iterator().next().asString(), CACHE_2); json = jsonResponseBody(restClient.cacheManager(CACHE_MANAGER).backupStatus(NYC)); assertEquals(json.at("status").asString(), "mixed"); assertEquals(json.at("online").asJsonList().iterator().next().asString(), CACHE_1); assertEquals(json.at("offline").asJsonList().iterator().next().asString(), CACHE_2); assertSuccessful(restClient.cache(CACHE_2).bringSiteOnline(NYC)); assertAllSitesOnline(restClient); // add a second node TestSite site = site(LON); EmbeddedCacheManager cm = site.addCacheManager(null, defaultGlobalConfigurationForSite(site.getSiteIndex()), defaultConfigurationForSite(site.getSiteIndex()), true); site.waitForClusterToForm(CACHE_1); site.waitForClusterToForm(CACHE_2); TakeOfflineManager takeOfflineManager = TestingUtil.extractComponent(cm.getCache(CACHE_1), TakeOfflineManager.class); takeOfflineManager.takeSiteOffline(NYC); json = jsonResponseBody(restClient.cacheManager(CACHE_MANAGER).backupStatuses()); assertEquals(json.at(NYC).at("status").asString(), "mixed"); assertEquals(json.at(NYC).at("online").asJsonList().iterator().next().asString(), CACHE_2); assertTrue(json.at(NYC).at("offline").asJsonList().isEmpty()); assertEquals(json.at(NYC).at("mixed").asJsonList().iterator().next().asString(), CACHE_1); json = jsonResponseBody(restClient.cacheManager(CACHE_MANAGER).backupStatus(NYC)); assertEquals(json.at("status").asString(), "mixed"); assertEquals(json.at("online").asJsonList().iterator().next().asString(), CACHE_2); assertTrue(json.at("offline").asJsonList().isEmpty()); assertEquals(json.at("mixed").asJsonList().iterator().next().asString(), CACHE_1); takeOfflineManager.bringSiteOnline(NYC); } @Test public void testBringAllCachesOnlineOffline() { RestClient restClient = clientPerSite.get(LON); RestCacheManagerClient restCacheManagerClient = restClient.cacheManager(CACHE_MANAGER); assertSuccessful(restCacheManagerClient.takeOffline(SFO)); Json json = jsonResponseBody(restCacheManagerClient.backupStatuses()); assertEquals(json.at(SFO).at("status").asString(), "offline"); assertSuccessful(restCacheManagerClient.bringBackupOnline(SFO)); json = jsonResponseBody(restCacheManagerClient.backupStatuses()); assertEquals(json.at(SFO).at("status").asString(), "online"); } @Test public void testPushAllCaches() { RestClient restClientLon = clientPerSite.get(LON); RestClient restClientSfo = clientPerSite.get(SFO); RestCacheClient cache1Lon = restClientLon.cache(CACHE_1); RestCacheClient cache2Lon = restClientLon.cache(CACHE_2); RestCacheClient cache1Sfo = restClientSfo.cache(CACHE_1); RestCacheClient cache2Sfo = restClientSfo.cache(CACHE_2); // Take SFO offline for all caches assertSuccessful(restClientLon.cacheManager(CACHE_MANAGER).takeOffline(SFO)); Json backupStatuses = jsonResponseBody(restClientLon.cacheManager(CACHE_MANAGER).backupStatuses()); assertEquals("offline", backupStatuses.at(SFO).at("status").asString()); // Write to the caches int entries = 10; IntStream.range(0, entries).forEach(i -> { String key = String.valueOf(i); String value = "value"; assertNoContent(cache1Lon.put(key, value)); assertNoContent(cache2Lon.put(key, value)); }); // Backups should be empty assertEquals(0, getCacheSize(cache1Sfo)); assertEquals(0, getCacheSize(cache2Sfo)); // Start state push assertSuccessful(restClientLon.cacheManager(CACHE_MANAGER).pushSiteState(SFO)); // Backups go online online immediately assertEquals(ONLINE, getBackupStatus(LON, SFO)); // State push should eventually finish eventuallyEquals("OK", () -> pushStateStatus(cache1Lon, SFO)); eventuallyEquals("OK", () -> pushStateStatus(cache2Lon, SFO)); // ... and with state assertEquals(entries, getCacheSize(cache1Sfo)); assertEquals(entries, getCacheSize(cache2Sfo)); } private String pushStateStatus(RestCacheClient cacheClient, String siteName) { Json json = jsonResponseBody(cacheClient.pushStateStatus()); return json.at(siteName).asString(); } @Test public void testCancelPushAllCaches() throws Exception { RestClient restClientLon = clientPerSite.get(LON); RestCacheClient cache1Lon = restClientLon.cache(CACHE_1); RestCacheClient cache2Lon = restClientLon.cache(CACHE_2); assertNoContent(cache1Lon.put("k1", "v1")); assertNoContent(cache2Lon.put("k2", "v2")); // Block before pushing state on both caches BlockXSitePushStateTransport transport = BlockXSitePushStateTransport.replace(cache(LON, CACHE_1, 0)); transport.startBlocking(); // Trigger a state push assertSuccessful(restClientLon.cacheManager(CACHE_MANAGER).pushSiteState(SFO)); transport.waitForCommand(); // Cancel state push assertSuccessful(restClientLon.cacheManager(CACHE_MANAGER).cancelPushState(SFO)); transport.stopBlocking(); // Verify that push was cancelled for both caches Json pushStatusCache1 = jsonResponseBody(cache1Lon.pushStateStatus()); Json pushStatusCache2 = jsonResponseBody(cache2Lon.pushStateStatus()); assertEquals("CANCELED", pushStatusCache1.at(SFO).asString()); assertEquals("CANCELED", pushStatusCache2.at(SFO).asString()); } @Test public void testXsiteView() { assertXSiteView(jsonResponseBody(clientPerSite.get(LON).cacheManager(CACHE_MANAGER).info())); assertXSiteView(jsonResponseBody(clientPerSite.get(NYC).cacheManager(CACHE_MANAGER).info())); assertXSiteView(jsonResponseBody(clientPerSite.get(SFO).cacheManager(CACHE_MANAGER).info())); } private void assertXSiteView(Json rsp) { Map<String, Json> json = rsp.asJsonMap(); assertTrue(json.get("relay_node").asBoolean()); List<Object> view = json.get("sites_view").asList(); assertTrue(view.contains(LON)); assertTrue(view.contains(NYC)); assertTrue(view.contains(SFO)); assertEquals(3, view.size()); } private int getCacheSize(RestCacheClient cacheClient) { return Integer.parseInt(responseBody(cacheClient.size())); } private void testOnlineOffline(String site, String backup) { takeBackupOffline(site, backup); String siteStatus = getBackupStatus(site, backup); assertEquals(siteStatus, OFFLINE); bringBackupOnline(site, backup); siteStatus = getBackupStatus(site, backup); assertEquals(siteStatus, ONLINE); } private void takeBackupOffline(String site, String backup) { RestCacheClient client = getCacheClient(site); assertSuccessful(client.takeSiteOffline(backup)); } private void bringBackupOnline(String site, String backup) { RestCacheClient client = getCacheClient(site); assertSuccessful(client.bringSiteOnline(backup)); } private String getFirstCacheManagerAddress(String site) { TestSite testSite = sites.stream().filter(t -> t.getSiteName().equals(site)).findFirst().orElse(null); if (testSite == null) return null; EmbeddedCacheManager cacheManager = testSite.cacheManagers().iterator().next(); return cacheManager.getAddress().toString(); } private String getBackupStatus(String site, String backup) { RestCacheClient cacheClient = getCacheClient(site); String cacheManagerAddress = getFirstCacheManagerAddress(site); Json json = jsonResponseBody(cacheClient.backupStatus(backup)); return json.at(cacheManagerAddress).asString(); } private void assertAllSitesOnline(RestClient restClient, String... sites) { Json json = jsonResponseBody(restClient.cacheManager(CACHE_MANAGER).backupStatuses()); Arrays.stream(sites).forEach(s -> assertEquals(json.at(s).at("status").asString(), "online")); } @Override protected void afterSitesCreated() { // LON backs-up to SFO, NYC ConfigurationBuilder builder = defaultConfigurationForSite(0); builder.sites().addBackup().site(siteName(1)).strategy(BackupConfiguration.BackupStrategy.SYNC) .stateTransfer().chunkSize(5); builder.sites().addBackup().site(siteName(2)).strategy(BackupConfiguration.BackupStrategy.SYNC) .stateTransfer().chunkSize(5); defineCaches(0, builder.build()); defineCaches(2, builder.build()); site(0).waitForClusterToForm(CACHE_1); site(0).waitForClusterToForm(CACHE_2); site(2).waitForClusterToForm(CACHE_1); site(2).waitForClusterToForm(CACHE_2); // NYC backs up to LON, SFO builder = defaultConfigurationForSite(1); builder.sites().addBackup().site(siteName(0)).strategy(BackupConfiguration.BackupStrategy.SYNC) .stateTransfer().chunkSize(5); builder.sites().addBackup().site(siteName(2)).strategy(BackupConfiguration.BackupStrategy.SYNC) .stateTransfer().chunkSize(5); defineCaches(1, builder.build()); site(1).waitForClusterToForm(CACHE_1); site(1).waitForClusterToForm(CACHE_2); } private void defineCaches(int siteIndex, Configuration configuration) { EmbeddedCacheManagerAdmin admin = manager(siteIndex, 0).administration().withFlags(VOLATILE); admin.getOrCreateCache(CACHE_1, configuration); admin.getOrCreateCache(CACHE_2, configuration); } // unable to use org.infinispan.remoting.transport.ControlledTransport since it blocks non-blocking threads and the test hangs // the non-blocking threads are shared with Netty and channel read-writes hangs in there. public static class BlockXSitePushStateTransport extends AbstractDelegatingTransport { @GuardedBy("this") private final List<Runnable> pendingCommands; @GuardedBy("this") private boolean enabled; private BlockXSitePushStateTransport(Transport actual) { super(actual); this.pendingCommands = new ArrayList<>(2); this.enabled = false; } public static BlockXSitePushStateTransport replace(Cache<?, ?> cache) { return replace(cache.getCacheManager()); } public static BlockXSitePushStateTransport replace(EmbeddedCacheManager manager) { log.tracef("Replacing transport on %s", manager.getAddress()); Transport t = extractGlobalComponent(manager, Transport.class); if (t instanceof BlockXSitePushStateTransport) { return (BlockXSitePushStateTransport) t; } return wrapGlobalComponent(manager, Transport.class, BlockXSitePushStateTransport::new, true); } @Override public void start() { //avoid starting again } @Override public void stop() { log.trace("Stopping BlockXSitePushStateTransport"); super.stop(); } public synchronized void startBlocking() { log.trace("Start blocking XSiteStatePushCommand"); this.enabled = true; } public void stopBlocking() { log.trace("Stop blocking XSiteStatePushCommand"); List<Runnable> copy; synchronized (this) { this.enabled = false; copy = new ArrayList<>(pendingCommands); pendingCommands.clear(); } copy.forEach(Runnable::run); } public synchronized void waitForCommand() throws InterruptedException, TimeoutException { log.trace("Waiting for XSiteStatePushCommand"); long endTime = TIME_SERVICE.expectedEndTime(30, TimeUnit.SECONDS); long timeLeftMillis; while (pendingCommands.isEmpty() && (timeLeftMillis = TIME_SERVICE.remainingTime(endTime, TimeUnit.MILLISECONDS)) > 0) { this.wait(timeLeftMillis); } if (pendingCommands.isEmpty()) { throw new TimeoutException(); } } @Override public <O> XSiteResponse<O> backupRemotely(XSiteBackup backup, XSiteReplicateCommand<O> rpcCommand) { synchronized (this) { if (enabled && rpcCommand instanceof XSiteStatePushCommand) { XSiteResponseImpl<O> toReturn = new XSiteResponseImpl<>(TIME_SERVICE, backup); pendingCommands.add(() -> { XSiteResponse<O> real = super.backupRemotely(backup, rpcCommand); real.whenComplete((o, throwable) -> toReturn.accept(SuccessfulResponse.create(o), throwable)); }); this.notifyAll(); return toReturn; } } return super.backupRemotely(backup, rpcCommand); } } }
25,008
39.272142
172
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/CacheResourceTest.java
package org.infinispan.rest.resources; import static io.netty.handler.codec.http.HttpHeaderNames.ACCEPT_ENCODING; import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS; import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS; import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS; import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD; import static io.netty.handler.codec.http.HttpHeaderNames.HOST; import static io.netty.handler.codec.http.HttpHeaderNames.ORIGIN; import static java.util.Collections.singletonMap; import static org.infinispan.client.rest.configuration.Protocol.HTTP_11; import static org.infinispan.client.rest.configuration.Protocol.HTTP_20; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT; 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_SERIALIZED_OBJECT; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML_TYPE; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import static org.infinispan.commons.util.Util.getResourceAsString; import static org.infinispan.dataconversion.Gzip.decompress; import static org.infinispan.rest.JSONConstants.TYPE; import static org.infinispan.rest.RequestHeader.IF_MODIFIED_SINCE; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import static org.testng.AssertJUnit.assertEquals; import java.io.IOException; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import org.assertj.core.api.Assertions; import org.infinispan.Cache; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestRawClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.DateUtils; import org.infinispan.rest.RequestHeader; import org.infinispan.rest.ResponseHeader; import org.infinispan.rest.TestClass; import org.infinispan.rest.configuration.RestServerConfiguration; import org.infinispan.rest.configuration.RestServerConfigurationBuilder; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.rest.search.entity.Person; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.Security; import org.infinispan.server.core.dataconversion.JsonTranscoder; import org.infinispan.server.core.dataconversion.XMLTranscoder; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.CacheResourceTest") public class CacheResourceTest extends BaseCacheResourceTest { @Override protected void defineCaches(EmbeddedCacheManager cm) { super.defineCaches(cm); ConfigurationBuilder object = getDefaultCacheBuilder(); object.encoding().key().mediaType(TEXT_PLAIN_TYPE); object.encoding().value().mediaType(APPLICATION_OBJECT_TYPE); ConfigurationBuilder legacyStorageCache = getDefaultCacheBuilder(); legacyStorageCache.encoding().key().mediaType("application/x-java-object;type=java.lang.String"); cm.defineConfiguration("objectCache", object.build()); cm.defineConfiguration("legacy", legacyStorageCache.build()); cm.defineConfiguration("rest", getDefaultCacheBuilder().build()); } static { System.setProperty("infinispan.server.rest.cors-allow", "http://infinispan.org"); } @Override public Object[] factory() { return new Object[]{ new CacheResourceTest().withSecurity(false).protocol(HTTP_11).ssl(false).browser(false), new CacheResourceTest().withSecurity(false).protocol(HTTP_11).ssl(false).browser(true), new CacheResourceTest().withSecurity(true).protocol(HTTP_20).ssl(false).browser(false), new CacheResourceTest().withSecurity(true).protocol(HTTP_20).ssl(false).browser(true), new CacheResourceTest().withSecurity(true).protocol(HTTP_11).ssl(true).browser(false), new CacheResourceTest().withSecurity(true).protocol(HTTP_11).ssl(true).browser(true), new CacheResourceTest().withSecurity(true).protocol(HTTP_20).ssl(true).browser(false), new CacheResourceTest().withSecurity(true).protocol(HTTP_20).ssl(true).browser(true), }; } @Test public void testLegacyPredefinedCache() { putStringValueInCache("rest", "k1", "v1"); CompletionStage<RestResponse> response = client.cache("rest").get("k1"); assertThat(response).isOk(); } @Test public void shouldReadWriteToLegacyCache() { //given putStringValueInCache("legacy", "test", "test"); //when CompletionStage<RestResponse> response = client.cache("legacy").get("test", TEXT_PLAIN_TYPE); //then assertThat(response).isOk(); assertThat(response).hasContentType("text/plain"); assertThat(response).hasReturnedText("test"); } @Test public void shouldConvertExistingSerializableObjectToJson() { //given TestClass testClass = new TestClass(); testClass.setName("test"); RestCacheClient objectCache = client.cache("objectCache"); join(objectCache.put("test", RestEntity.create(APPLICATION_JSON, testClass.toJson().toString()))); //when CompletionStage<RestResponse> response = objectCache.get("test", APPLICATION_JSON_TYPE); //then assertThat(response).isOk(); assertThat(response).hasContentType("application/json"); assertThat(response).hasReturnedText("{\"" + TYPE + "\":\"" + TestClass.class.getName() + "\",\"name\":\"test\"}"); } @Test public void shouldConvertExistingSerializableObjectToXml() { //given TestClass testClass = new TestClass(); testClass.setName("test"); RestCacheClient objectCache = client.cache("objectCache"); String xml = "<org.infinispan.rest.TestClass><name>test</name></org.infinispan.rest.TestClass>"; join(objectCache.put("test", RestEntity.create(APPLICATION_XML, xml))); //when RestResponse response = join(objectCache.get("test", APPLICATION_XML_TYPE)); //then assertThat(response).isOk(); assertThat(response).hasContentType("application/xml"); assertThat(response).hasReturnedText(xml); } @Test public void shouldReadAsBinaryWithPojoCache() { //given RestCacheClient pojoCache = client.cache("pojoCache"); String key = "test"; TestClass value = new TestClass(); value.setName("test"); join(pojoCache.put(key, value.toJson().toString())); //when RestResponse response = join(pojoCache.get(key, APPLICATION_OCTET_STREAM_TYPE)); //then assertThat(response).isOk(); assertThat(response).hasContentType(APPLICATION_OCTET_STREAM_TYPE); } @Test public void shouldReadTextWithPojoCache() { //given RestCacheClient pojoCache = client.cache("pojoCache"); String key = "k1"; String value = "v1"; join(pojoCache.put(key, value)); //when RestResponse response = join(pojoCache.get(key)); //then assertThat(response).isOk(); assertThat(response).hasContentType(TEXT_PLAIN_TYPE); assertThat(response).hasReturnedText(value); } @Test public void shouldReadByteArrayWithPojoCache() { //given Cache cache = restServer().getCacheManager().getCache("pojoCache").getAdvancedCache(); cache.put("k1", "v1".getBytes()); //when CompletionStage<RestResponse> response = client.cache("pojoCache").get("k1", APPLICATION_OCTET_STREAM_TYPE); //then assertThat(response).hasReturnedBytes("v1".getBytes()); assertThat(response).isOk(); assertThat(response).hasContentType(APPLICATION_OCTET_STREAM_TYPE); } @Test public void shouldReadAsJsonWithPojoCache() { //given TestClass testClass = new TestClass(); testClass.setName("test"); RestCacheClient pojoCache = client.cache("pojoCache"); join(pojoCache.put("test", RestEntity.create(APPLICATION_JSON, testClass.toJson().toString()))); //when CompletionStage<RestResponse> response = pojoCache.get("test", APPLICATION_JSON_TYPE); //then assertThat(response).isOk(); assertThat(response).hasContentType(APPLICATION_JSON_TYPE); assertThat(response).hasReturnedText("{\"" + TYPE + "\":\"org.infinispan.rest.TestClass\",\"name\":\"test\"}"); } @Test public void shouldNegotiateFromPojoCacheWithoutAccept() { //given TestClass testClass = new TestClass(); testClass.setName("test"); String json = testClass.toJson().toString(); RestCacheClient pojoCache = client.cache("pojoCache"); String key = "k1"; join(pojoCache.put("k1", json)); //when RestResponse response = join(pojoCache.get(key, Collections.emptyMap())); //then assertThat(response).isOk(); assertThat(response).hasContentType(MediaType.TEXT_PLAIN_TYPE); assertThat(response).hasReturnedText(json); } @Test public void shouldWriteTextContentWithPjoCache() { //given putStringValueInCache("pojoCache", "key1", "data"); //when CompletionStage<RestResponse> response = client.cache("pojoCache").get("key1", TEXT_PLAIN_TYPE); //then assertThat(response).isOk(); assertThat(response).hasReturnedText("data"); assertThat(response).hasContentType(TEXT_PLAIN_TYPE); } @Test public void shouldWriteOctetStreamToDefaultCache() { //given putBinaryValueInCache("default", "keyA", "<hey>ho</hey>".getBytes(), MediaType.APPLICATION_OCTET_STREAM); //when CompletionStage<RestResponse> response = client.cache("default").get("keyA"); //then assertThat(response).isOk(); assertThat(response).hasReturnedBytes("<hey>ho</hey>".getBytes()); assertThat(response).hasContentType(APPLICATION_OCTET_STREAM_TYPE); } @Test public void shouldIgnoreDisabledCaches() { putStringValueInCache("default", "K", "V"); RestCacheClient cacheClient = client.cache("default"); CompletionStage<RestResponse> response = cacheClient.get("K"); assertThat(response).isOk(); if (security) { Security.doAs(TestingUtil.makeSubject(AuthorizationPermission.ADMIN.name()),() -> restServer().ignoreCache("default")); } else { restServer().ignoreCache("default"); } response = cacheClient.get("K"); assertThat(response).isServiceUnavailable(); if (security) { Security.doAs(TestingUtil.makeSubject(AuthorizationPermission.ADMIN.name()), () -> restServer().unignoreCache("default")); } else { restServer().unignoreCache("default"); } response = cacheClient.get("K"); assertThat(response).isOk(); } @Test public void shouldDeleteExistingValueEvenWithoutMetadata() { RestCacheClient defaultCache = client.cache("default"); join(defaultCache.put("test", "test")); //when CompletionStage<RestResponse> response = defaultCache.remove("test"); //then assertThat(response).isOk(); Assertions.assertThat(join(defaultCache.size()).getBody()).isEqualTo("0"); } @Test public void testCORSPreflight() { String url = String.format("/rest/v2/caches/%s/%s", "default", "key"); RestRawClient rawClient = client.raw(); join(client.cache("default").put("key", "value")); Map<String, String> headers = new HashMap<>(); headers.put(HOST.toString(), "localhost"); headers.put(ORIGIN.toString(), "http://localhost:" + restServer().getPort()); headers.put(ACCESS_CONTROL_REQUEST_METHOD.toString(), "GET"); CompletionStage<RestResponse> preFlight = rawClient.options(url, headers); assertThat(preFlight).isOk(); assertThat(preFlight).hasNoContent(); assertThat(preFlight).containsAllHeaders(ACCESS_CONTROL_ALLOW_ORIGIN.toString(), ACCESS_CONTROL_ALLOW_METHODS.toString(), ACCESS_CONTROL_ALLOW_HEADERS.toString()); assertThat(preFlight).hasHeaderWithValues(ACCESS_CONTROL_ALLOW_HEADERS.toString(), (String[]) RequestHeader.toArray()); } @Test public void testCorsGET() { int port = restServer().getPort(); putStringValueInCache("default", "test", "test"); Map<String, String> headers = singletonMap(ORIGIN.toString(), "http://127.0.0.1:" + port); CompletionStage<RestResponse> response = client.cache("default").get("test", headers); assertThat(response).isOk(); assertThat(response).containsAllHeaders("access-control-allow-origin"); assertThat(response).hasHeaderWithValues(ACCESS_CONTROL_EXPOSE_HEADERS.toString(), (String[]) ResponseHeader.toArray()); } @Test public void testCorsAllowedJVMProp() { CompletionStage<RestResponse> response = client.raw() .get("/rest/v2/caches", singletonMap(ORIGIN.toString(), "http://infinispan.org")); assertThat(response).isOk(); assertThat(response).containsAllHeaders("access-control-allow-origin"); } @Test public void testCorsSameOrigin() { Map<String, String> headers = new HashMap<>(); String scheme = ssl ? "https://" : "http://"; headers.put(ORIGIN.toString(), scheme + "origin-host.org"); headers.put(HOST.toString(), "origin-host.org"); CompletionStage<RestResponse> response = client.raw().get("/rest/v2/caches", headers); assertThat(response).isOk(); } @Test public void testCORSAllOrigins() throws IOException { RestServerHelper restServerHelper = null; RestClient client = null; try { RestServerConfigurationBuilder restBuilder = new RestServerConfigurationBuilder(); restBuilder.cors().addNewRule().allowOrigins(new String[]{"*"}); restBuilder.host("localhost").port(0); restServerHelper = RestServerHelper.defaultRestServer(); RestServerConfiguration build = restBuilder.build(); restServerHelper.serverConfigurationBuilder().read(build); configureServer(restServerHelper); restServerHelper.start("test"); RestClientConfigurationBuilder clientConfig = getClientConfig("admin", "admin"); clientConfig.clearServers().addServer().host("localhost").port(restServerHelper.getPort()); client = RestClient.forConfiguration(clientConfig.build()); RestResponse response = join(client.cache("default") .get("test", singletonMap(ORIGIN.toString(), "http://host.example.com:5576"))); assertThat(response).containsAllHeaders("access-control-allow-origin"); } finally { client.close(); if (restServerHelper != null) restServerHelper.stop(); } } @Test public void testIfModifiedHeaderForCache() { putStringValueInCache("expiration", "test", "test"); RestCacheClient cacheClient = client.cache("expiration"); RestResponse resp = join(cacheClient.get("test")); String dateLast = resp.headers().get("Last-Modified").get(0); CompletionStage<RestResponse> sameLastModAndIfModified = cacheClient.get("test", createHeaders(IF_MODIFIED_SINCE, dateLast)); assertThat(sameLastModAndIfModified).isNotModified(); putStringValueInCache("expiration", "test", "test-new"); RestResponse lastmodAfterIfModified = join(cacheClient.get("test")); dateLast = lastmodAfterIfModified.headers().get("Last-Modified").get(0); assertThat(lastmodAfterIfModified).isOk(); Map<String, String> header = createHeaders(IF_MODIFIED_SINCE, plus1Day(dateLast)); CompletionStage<RestResponse> lastmodBeforeIfModified = cacheClient.get("test", header); assertThat(lastmodBeforeIfModified).isNotModified(); } private String plus1Day(String rfc1123Date) { ZonedDateTime plus = DateUtils.parseRFC1123(rfc1123Date).plus(1, ChronoUnit.DAYS); return DateUtils.toRFC1123(plus.toEpochSecond() * 1000); } @Test public void testCompression() throws Exception { String payload = getResourceAsString("person.proto", getClass().getClassLoader()); putStringValueInCache("default", "k", payload); String path = String.format("/rest/v2/caches/%s/%s", "default", "k"); RestResponse response = join(client.raw().get(path, singletonMap(ACCEPT_ENCODING.toString(), "none"))); assertThat(response).hasNoContentEncoding(); assertThat(response).hasContentLength(payload.getBytes().length); response = join(client.raw().get(path, singletonMap(ACCEPT_ENCODING.toString(), "gzip"))); assertThat(response).hasGzipContentEncoding(); assertEquals(decompress(response.getBodyAsByteArray()), payload); } @Test public void testReplaceExistingObject() { String initialJson = "{\"" + TYPE + "\":\"org.infinispan.rest.TestClass\",\"name\":\"test\"}"; String changedJson = "{\"" + TYPE + "\":\"org.infinispan.rest.TestClass\",\"name\":\"test2\"}"; RestResponse response = writeJsonToCache("key", initialJson, "objectCache"); assertThat(response).isOk(); response = writeJsonToCache("key", changedJson, "objectCache"); assertThat(response).isOk(); response = join(client.cache("objectCache").get("key", APPLICATION_JSON_TYPE)); Json jsonNode = Json.read(response.getBody()); assertEquals(jsonNode.at("name").asString(), "test2"); } private RestResponse writeJsonToCache(String key, String json, String cacheName) { RestEntity restEntity = RestEntity.create(APPLICATION_JSON, json); return join(client.cache(cacheName).put(key, restEntity)); } @Test public void testServerDeserialization() throws Exception { Object value = new Person(); byte[] jsonMarshalled = (byte[]) new JsonTranscoder().transcode(value, APPLICATION_OBJECT, APPLICATION_JSON); byte[] xmlMarshalled = (byte[]) new XMLTranscoder().transcode(value, APPLICATION_OBJECT, APPLICATION_XML); byte[] javaMarshalled = new JavaSerializationMarshaller().objectToByteBuffer(value); String expectError = "Class '" + value.getClass().getName() + "' blocked by deserialization allow list"; RestEntity jsonEntity = RestEntity.create(APPLICATION_JSON, jsonMarshalled); RestEntity xmlEntity = RestEntity.create(APPLICATION_XML, xmlMarshalled); RestEntity javaEntity = RestEntity.create(APPLICATION_SERIALIZED_OBJECT, javaMarshalled); CompletionStage<RestResponse> jsonResponse = client.cache("objectCache").put("addr2", jsonEntity); assertThat(jsonResponse).isError(); assertThat(jsonResponse).containsReturnedText(expectError); CompletionStage<RestResponse> xmlResponse = client.cache("objectCache").put("addr3", xmlEntity); assertThat(xmlResponse).isError(); assertThat(xmlResponse).containsReturnedText(expectError); CompletionStage<RestResponse> serializationResponse = client.cache("objectCache").put("addr4", javaEntity); assertThat(serializationResponse).isError(); assertThat(serializationResponse).containsReturnedText(expectError); } }
20,289
40.492843
169
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/ServerResourceTest.java
package org.infinispan.rest.resources; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.CompletionStage; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.util.Version; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.server.core.MockProtocolServer; import org.testng.annotations.Test; /** * @since 14.0 */ @Test(groups = "functional", testName = "rest.ServerResourceTest") public class ServerResourceTest extends AbstractRestResourceTest { @Override public Object[] factory() { return new Object[]{ new ServerResourceTest().withSecurity(false), new ServerResourceTest().withSecurity(true), }; } @Test public void testServerInfo() { CompletionStage<RestResponse> response = client.server().info(); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).containsReturnedText(Version.printVersion()); } @Test public void testServerConnectorNames() { CompletionStage<RestResponse> response = adminClient.server().connectorNames(); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).containsReturnedText("DummyProtocol"); } @Test public void testServerConnectorDetail() { CompletionStage<RestResponse> response = adminClient.server().connector("DummyProtocol"); ResponseAssertion.assertThat(response).isOk(); String body = join(response).getBody(); Json jsonNode = Json.read(body); assertEquals("DummyProtocol", jsonNode.at("name").asString()); assertEquals(MockProtocolServer.DEFAULT_CACHE_NAME, jsonNode.at("default-cache").asString()); assertTrue(jsonNode.at("enabled").asBoolean()); assertTrue(jsonNode.at("ip-filter-rules").asJsonList().isEmpty()); assertEquals("localhost", jsonNode.at("host").asString()); assertTrue(jsonNode.has("port")); assertTrue(jsonNode.has("local-connections")); assertTrue(jsonNode.has("global-connections")); assertTrue(jsonNode.has("io-threads")); assertTrue(jsonNode.has("pending-tasks")); assertTrue(jsonNode.has("total-bytes-read")); assertTrue(jsonNode.has("total-bytes-written")); assertTrue(jsonNode.has("send-buffer-size")); assertTrue(jsonNode.has("receive-buffer-size")); } @Test public void testServerReport() { CompletionStage<RestResponse> response = adminClient.server().report(); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType("application/gzip"); } }
2,834
37.835616
99
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/StaticResourceTest.java
package org.infinispan.rest.resources; import static io.netty.handler.codec.http.HttpHeaderNames.ACCEPT_ENCODING; import static java.util.Collections.singletonMap; import static org.infinispan.client.rest.configuration.Protocol.HTTP_11; import static org.infinispan.client.rest.configuration.Protocol.HTTP_20; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML; import static org.infinispan.commons.dataconversion.MediaType.TEXT_CSS; import static org.infinispan.commons.dataconversion.MediaType.TEXT_HTML; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN; import static org.infinispan.rest.RequestHeader.IF_MODIFIED_SINCE; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestRawClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.util.Util; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.DateUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * @since 10.0 */ @Test(groups = "functional", testName = "rest.StaticResourceTest") public class StaticResourceTest extends AbstractRestResourceTest { private static final Map<String, String> NO_COMPRESSION = singletonMap(ACCEPT_ENCODING.toString(), "none"); private RestClient noRedirectsClient; @BeforeClass(alwaysRun = true) public void createBeforeClass() throws Throwable { super.createBeforeClass(); RestClientConfigurationBuilder builder = super.getClientConfig("admin", "admin"); builder.followRedirects(false).addServer().host(restServer().getHost()).port(restServer().getPort()); noRedirectsClient = RestClient.forConfiguration(builder.build()); } @AfterClass public void afterClass() { super.afterClass(); Util.close(noRedirectsClient); } @Override protected void defineCaches(EmbeddedCacheManager cm) { } private RestResponse call(String path) { RestRawClient rawClient = client.raw(); return join(rawClient.get(path, NO_COMPRESSION)); } private RestResponse call(String path, String ifModifiedSince) { Map<String, String> allHeaders = new HashMap<>(NO_COMPRESSION); allHeaders.put(IF_MODIFIED_SINCE.getValue(), ifModifiedSince); allHeaders.putAll(NO_COMPRESSION); RestRawClient rawClient = client.raw(); return join(rawClient.get(path, allHeaders)); } @Override public Object[] factory() { return new Object[]{ new StaticResourceTest().withSecurity(false).protocol(HTTP_11).ssl(false).browser(false), new StaticResourceTest().withSecurity(false).protocol(HTTP_11).ssl(false).browser(true), new StaticResourceTest().withSecurity(true).protocol(HTTP_20).ssl(false).browser(false), new StaticResourceTest().withSecurity(true).protocol(HTTP_20).ssl(false).browser(true), new StaticResourceTest().withSecurity(true).protocol(HTTP_11).ssl(true).browser(false), new StaticResourceTest().withSecurity(true).protocol(HTTP_11).ssl(true).browser(true), new StaticResourceTest().withSecurity(true).protocol(HTTP_20).ssl(true).browser(false), new StaticResourceTest().withSecurity(true).protocol(HTTP_20).ssl(true).browser(true), }; } @Test public void testGetFile() { RestResponse response = call("/static/nonexistent.html"); assertThat(response).isNotFound(); response = call("/static"); assertResponse(response, "static-test/index.html", "<h1>Hello</h1>", TEXT_HTML); response = call("/static/index.html"); assertResponse(response, "static-test/index.html", "<h1>Hello</h1>", TEXT_HTML); response = call("/static/xml/file.xml"); assertResponse(response, "static-test/xml/file.xml", "<distributed-cache", MediaType.fromString("text/xml"), APPLICATION_XML); response = call("/static/other/text/file.txt"); assertResponse(response, "static-test/other/text/file.txt", "This is a text file", TEXT_PLAIN); } @Test public void testConsole() { RestResponse response1 = call("/console/page.htm"); RestResponse response2 = call("/console/folder/test.css"); RestResponse response3 = call("/console"); RestResponse response4 = call("/console/cache/people"); RestResponse response5 = call("/console/cache/peo.ple"); assertResponse(response1, "static-test/console/page.htm", "console", TEXT_HTML); assertResponse(response2, "static-test/console/folder/test.css", ".a", TEXT_CSS); assertThat(response2).isOk(); assertResponse(response3, "static-test/console/index.html", "console", TEXT_HTML); assertThat(response4).isOk(); assertThat(response5).isOk(); RestResponse response = call("/console/"); assertThat(response).isOk(); response = call("/console/create"); assertThat(response).isOk(); response = call("/notconsole/"); assertThat(response).isNotFound(); } private void assertResponse(RestResponse response, String path, String returnedText, MediaType... possibleTypes) { assertThat(response).isOk(); assertThat(response).hasMediaType(possibleTypes); assertThat(response).containsReturnedText(returnedText); assertCacheHeaders(path, response); assertThat(response).hasValidDate(); } private void assertCacheHeaders(String path, RestResponse response) { int expireDuration = 60 * 60 * 24 * 31; File test = getTestFile(path); assertNotNull(test); assertThat(response).hasContentLength(test.length()); assertThat(response).hasLastModified(test.lastModified()); assertThat(response).hasCacheControlHeaders("private, max-age=" + expireDuration); assertThat(response).expiresAfter(expireDuration); } @Test public void testCacheHeaders() { String path = "/static/index.html"; long lastModified = getTestFile("static-test/index.html").lastModified(); RestResponse response = call(path, DateUtils.toRFC1123(lastModified)); assertThat(response).isNotModified(); assertThat(response).hasNoContent(); response = call(path, "Sun, 15 Aug 1971 15:00:00 GMT"); assertThat(response).isOk(); assertThat(response).containsReturnedText("<h1>Hello</h1>"); response = call(path, DateUtils.toRFC1123(System.currentTimeMillis())); assertThat(response).isNotModified(); assertThat(response).hasNoContent(); } @Test public void testRedirect() { RestResponse response = join(noRedirectsClient.raw().get("/")); assertThat(response).isRedirect(); assertThat(response).hasNoContent(); assertEquals("/console/welcome", response.headers().get("Location").get(0)); } private static File getTestFile(String path) { URL resource = StaticResourceTest.class.getClassLoader().getResource(path); if (resource == null) return null; try { Path p = Paths.get(resource.toURI()); return p.toFile(); } catch (URISyntaxException ignored) { } return null; } }
7,675
38.979167
132
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/SSEListener.java
package org.infinispan.rest.resources; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.BlockingDeque; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import org.infinispan.client.rest.RestEventListener; import org.infinispan.client.rest.RestResponse; import org.infinispan.util.KeyValuePair; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 13.0 **/ public class SSEListener implements RestEventListener { protected static final Consumer<KeyValuePair<String, String>> NO_OP = ignore -> {}; private static final Log log = LogFactory.getLog(SSEListener.class); BlockingDeque<KeyValuePair<String, String>> events = new LinkedBlockingDeque<>(); CountDownLatch openLatch = new CountDownLatch(1); @Override public void onOpen(RestResponse response) { log.tracef("open"); openLatch.countDown(); } @Override public void onMessage(String id, String type, String data) { log.tracef("Received %s %s %s", id, type, data); this.events.add(new KeyValuePair<>(type, data)); } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return openLatch.await(timeout, unit); } public void expectEvent(String type, String subString) throws InterruptedException { expectEvent(type, subString, NO_OP); } public void expectEvent(String type, String subString, Consumer<KeyValuePair<String, String>> consumer) throws InterruptedException { KeyValuePair<String, String> event = events.poll(10, TimeUnit.SECONDS); assertNotNull(event); assertEquals(type, event.getKey()); assertTrue(event.getValue().contains(subString)); consumer.accept(event); } }
2,024
33.913793
136
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/BaseCacheResourceTest.java
package org.infinispan.rest.resources; import static java.nio.charset.StandardCharsets.UTF_8; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_SERIALIZED_OBJECT; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_SERIALIZED_OBJECT_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_WWW_FORM_URLENCODED; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML_TYPE; import static org.infinispan.commons.dataconversion.MediaType.MATCH_ALL_TYPE; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import static org.infinispan.rest.RequestHeader.ACCEPT_HEADER; import static org.infinispan.rest.RequestHeader.IF_NONE_MATCH; import static org.infinispan.rest.RequestHeader.KEY_CONTENT_TYPE_HEADER; import static org.infinispan.rest.ResponseHeader.MAX_IDLE_TIME_HEADER; import static org.infinispan.rest.ResponseHeader.TIME_TO_LIVE_HEADER; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import org.assertj.core.api.Assertions; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestRawClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.counter.EmbeddedCounterManagerFactory; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.RequestHeader; import org.infinispan.rest.ResponseHeader; import org.infinispan.rest.RestTestSCI; import org.infinispan.rest.TestClass; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; @Test(groups = "functional") public abstract class BaseCacheResourceTest extends AbstractRestResourceTest { private void defineCounters(EmbeddedCacheManager cm) { CounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager(cm); counterManager.defineCounter("weak", CounterConfiguration.builder(CounterType.WEAK).build()); counterManager.defineCounter("strong", CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG).build()); } private static final long DEFAULT_LIFESPAN = 45190; private static final long DEFAULT_MAX_IDLE = 1859446; private static final long DEFAULT_LIFESPAN_SECONDS = DEFAULT_LIFESPAN / 1000; private static final long DEFAULT_MAX_IDLE_SECONDS = DEFAULT_MAX_IDLE / 1000; protected void defineCaches(EmbeddedCacheManager cm) { defineCounters(cm); ConfigurationBuilder expirationConfiguration = getDefaultCacheBuilder(); expirationConfiguration.expiration().lifespan(DEFAULT_LIFESPAN).maxIdle(DEFAULT_MAX_IDLE); ConfigurationBuilder xmlCacheConfiguration = getDefaultCacheBuilder(); xmlCacheConfiguration.encoding().value().mediaType("application/xml"); ConfigurationBuilder jsonCacheConfiguration = getDefaultCacheBuilder(); jsonCacheConfiguration.encoding().value().mediaType("application/json"); ConfigurationBuilder octetStreamCacheConfiguration = getDefaultCacheBuilder(); octetStreamCacheConfiguration.encoding().value().mediaType("application/octet-stream"); ConfigurationBuilder unknownContentCacheConfiguration = getDefaultCacheBuilder(); unknownContentCacheConfiguration.encoding().value().mediaType("application/unknown"); ConfigurationBuilder javaSerialized = getDefaultCacheBuilder(); javaSerialized.encoding().value().mediaType(APPLICATION_SERIALIZED_OBJECT_TYPE); ConfigurationBuilder text = getDefaultCacheBuilder(); text.encoding().key().mediaType(TEXT_PLAIN_TYPE); text.encoding().value().mediaType(TEXT_PLAIN_TYPE); ConfigurationBuilder pojoCache = getDefaultCacheBuilder(); pojoCache.encoding().key().mediaType(APPLICATION_OBJECT_TYPE); pojoCache.encoding().value().mediaType(APPLICATION_OBJECT_TYPE); cm.defineConfiguration("default", getDefaultCacheBuilder().build()); cm.defineConfiguration("expiration", expirationConfiguration.build()); cm.defineConfiguration("xml", xmlCacheConfiguration.build()); cm.defineConfiguration("json", jsonCacheConfiguration.build()); cm.defineConfiguration("binary", octetStreamCacheConfiguration.build()); cm.defineConfiguration("unknown", unknownContentCacheConfiguration.build()); cm.defineConfiguration("serialized", javaSerialized.build()); cm.defineConfiguration("textCache", text.build()); cm.defineConfiguration("pojoCache", pojoCache.build()); } @Test public void shouldGetNonExistingValue() { CompletionStage<RestResponse> response = client.cache("default").get("nonExisting"); ResponseAssertion.assertThat(response).doesntExist(); } @Test public void shouldReturnNotExistingOnWrongContext() { putStringValueInCache("default", "test", "test"); RestRawClient rawClient = client.raw(); String path = String.format("/wrongContext/%s/%s", "default", "test"); CompletionStage<RestResponse> response = rawClient.get(path); //then ResponseAssertion.assertThat(response).doesntExist(); } @Test public void shouldGetAsciiValueStoredInSpecificFormat() { putStringValueInCache("default", "test", "test"); CompletionStage<RestResponse> response = client.cache("default").get("test", TEXT_PLAIN_TYPE); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType("text/plain"); ResponseAssertion.assertThat(response).hasReturnedText("test"); } @Test public void shouldHaveProperEtagWhenGettingValue() { //given putStringValueInCache("default", "test", "test"); CompletionStage<RestResponse> response = client.cache("default").get("test", TEXT_PLAIN_TYPE); //then ResponseAssertion.assertThat(response).hasEtag(); ResponseAssertion.assertThat(response).hasHeaderMatching("ETag", "-\\d+"); } @Test public void shouldReturnExtendedHeaders() { //given putStringValueInCache("default", "test", "test"); //when CompletionStage<RestResponse> response = client.cache("default").get("test", TEXT_PLAIN_TYPE, true); //then ResponseAssertion.assertThat(response).hasExtendedHeaders(); } @Test public void shouldGetUtf8ValueStoredInSpecificFormat() { //given putStringValueInCache("default", "test", "test"); //when CompletionStage<RestResponse> response = client.cache("default").get("test", "text/plain;charset=UTF-8"); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType("text/plain;charset=UTF-8"); ResponseAssertion.assertThat(response).hasReturnedText("test"); } @Test public void shouldGetJsonValueStoredInSpecificFormat() { //given putJsonValueInCache("json", "test", "{\"name\": \"test\"}"); //when CompletionStage<RestResponse> response = client.cache("json").get("test", APPLICATION_JSON_TYPE); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType("application/json"); ResponseAssertion.assertThat(response).hasReturnedText("{\"name\": \"test\"}"); } @Test public void shouldGetXmlValueStoredInSpecificFormat() { //given putStringValueInCache("xml", "test", "<xml><name>test</name></xml>"); //when CompletionStage<RestResponse> response = client.cache("xml").get("test", APPLICATION_XML_TYPE); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType("application/xml"); ResponseAssertion.assertThat(response).hasReturnedText("<xml><name>test</name></xml>"); } @Test public void shouldGetValueStoredInUnknownFormat() { //given putStringValueInCache("default", "test", "test"); //when CompletionStage<RestResponse> response = client.cache("default").get("test"); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType(APPLICATION_OCTET_STREAM_TYPE); ResponseAssertion.assertThat(response).hasReturnedText("test"); } @Test public void shouldGetOctetStreamValueStoredInSpecificFormat() throws Exception { //given TestClass testClass = new TestClass(); testClass.setName("test"); putBinaryValueInCache("serialized", "test", convertToBytes(testClass), APPLICATION_SERIALIZED_OBJECT); //when RestResponse response = join(client.cache("serialized").get("test")); TestClass convertedObject = convertFromBytes(response.getBodyAsByteArray()); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType(APPLICATION_SERIALIZED_OBJECT.toString()); ResponseAssertion.assertThat(response).hasNoCharset(); Assertions.assertThat(convertedObject.getName()).isEqualTo("test"); } @Test public void shouldConvertExistingObjectToText() { //given putStringValueInCache("default", "test", "test"); //when CompletionStage<RestResponse> response = client.cache("default").get("test", TEXT_PLAIN_TYPE); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType("text/plain"); ResponseAssertion.assertThat(response).hasReturnedText("test"); } @Test public void shouldConvertExistingObjectToTextUtf8() { //given putStringValueInCache("default", "test", "test"); //when CompletionStage<RestResponse> response = client.cache("default").get("test", "text/plain;charset=UTF-8"); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType("text/plain"); ResponseAssertion.assertThat(response).hasReturnedText("test"); } @Test public void shouldGetExistingValueWithoutOutputUsingHEAD() { //given putStringValueInCache("default", "test", "test"); //when CompletionStage<RestResponse> response = client.cache("default").head("test"); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasNoContent(); } private void putInCache(String cacheName, Object key, String keyContentType, String value, String contentType) { RestEntity entity = RestEntity.create(MediaType.fromString(contentType), value); CompletionStage<RestResponse> response = client.cache(cacheName).put(key.toString(), keyContentType, entity); ResponseAssertion.assertThat(response).isOk(); } private byte[] convertToBytes(Object object) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { out.writeObject(object); return bos.toByteArray(); } } private <T> T convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException { try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes)) { ObjectInputStream in = new ObjectInputStream(bis); return (T) in.readObject(); } } @Test public void shouldDeleteExistingValue() throws Exception { putStringValueInCache("default", "test", "test"); //when CompletionStage<RestResponse> response = client.cache("default").remove("test"); //then ResponseAssertion.assertThat(response).isOk(); Assertions.assertThat(restServer().getCacheManager().getCache("default")).isEmpty(); } @Test public void shouldDeleteExistingValueWithAcceptHeader() throws Exception { putBinaryValueInCache("serialized", "test", convertToBytes(42), APPLICATION_SERIALIZED_OBJECT); Map<String, String> headers = createHeaders(ACCEPT_HEADER, APPLICATION_SERIALIZED_OBJECT_TYPE); CompletionStage<RestResponse> headResponse = client.cache("serialized").head("test", headers); ResponseAssertion.assertThat(headResponse).isOk(); ResponseAssertion.assertThat(headResponse).hasContentType("application/x-java-serialized-object"); headers = createHeaders(ACCEPT_HEADER, "text/plain;charset=UTF-8"); CompletionStage<RestResponse> response = client.cache("serialized").remove("test", headers); //then ResponseAssertion.assertThat(response).isOk(); Assertions.assertThat(restServer().getCacheManager().getCache("binary")).isEmpty(); } @Test public void shouldDeleteNonExistingValue() throws Exception { putStringValueInCache("default", "test", "test"); //when CompletionStage<RestResponse> response = client.cache("default").remove("doesnt_exist"); //then ResponseAssertion.assertThat(response).isNotFound(); } @Test public void shouldDeleteEntireCache() throws Exception { putStringValueInCache("default", "test", "test"); //when CompletionStage<RestResponse> response = client.cache("default").clear(); //then ResponseAssertion.assertThat(response).isOk(); Assertions.assertThat(restServer().getCacheManager().getCache("default")).isEmpty(); } @Test public void shouldGetAllEntriesFromEmptyCache() { //when CompletionStage<RestResponse> response = client.cache("default").keys("text/plain; charset=utf-8"); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasReturnedText("[]"); } @Test public void shouldGetAllKeysConvertedToJson() throws Exception { //given putStringValueInCache("textCache", "key1", "test1"); putStringValueInCache("textCache", "key2", "test2"); //when CompletionStage<RestResponse> response = client.cache("textCache").keys(APPLICATION_JSON_TYPE); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType("application/json"); // keys can be returned in any order ResponseAssertion.assertThat(response).hasReturnedText("[\"key2\",\"key1\"]", "[\"key1\",\"key2\"]"); } @Test public void shouldAcceptMultipleAcceptHeaderValues() throws Exception { //given putStringValueInCache("textCache", "key1", "test1"); //when CompletionStage<RestResponse> response = client.cache("textCache").get("key1", "ignored/wrong , text/plain"); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType("text/plain"); ResponseAssertion.assertThat(response).hasReturnedText("test1"); } @Test public void shouldNotAcceptUnknownContentType() throws Exception { //given putStringValueInCache("default", "key1", "test1"); //when CompletionStage<RestResponse> response = client.cache("default").get("key1", "application/wrong-content-type"); //then ResponseAssertion.assertThat(response).isNotAcceptable(); } @Test public void shouldNotAcceptUnknownContentTypeWithHead() throws Exception { putStringValueInCache("default", "key1", "test1"); Map<String, String> headers = createHeaders(ACCEPT_HEADER, "garbage"); CompletionStage<RestResponse> response = client.cache("default").head("key1", headers); ResponseAssertion.assertThat(response).isNotAcceptable(); } @Test public void shouldNotReturnValueIfSendingCorrectETag() throws Exception { //given putStringValueInCache("default", "test", "test"); //when RestResponse firstResponse = join(client.cache("default").get("test")); String etagFromFirstCall = firstResponse.headers().get("ETag").get(0); Map<String, String> headers = createHeaders(IF_NONE_MATCH, etagFromFirstCall); CompletionStage<RestResponse> secondResponse = client.cache("default").get("test", headers); //then Assertions.assertThat(etagFromFirstCall).isNotNull().isNotEmpty(); ResponseAssertion.assertThat(secondResponse).isNotModified(); } @Test public void shouldReturnEntityWhenSendingWrongETag() throws Exception { //given putStringValueInCache("default", "test", "test"); Map<String, String> headers = createHeaders(IF_NONE_MATCH, "Invalid-etag"); //when CompletionStage<RestResponse> response = client.cache("default").get("test", headers); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasReturnedText("test"); } @Test public void shouldPutTextValueInCache() { //when RestEntity restEntity = RestEntity.create(MediaType.fromString("text/plain;charset=UTF-8"), "Hey!"); CompletionStage<RestResponse> response = client.cache("default").post("test", restEntity); ResponseAssertion.assertThat(response).isOk(); RestResponse getResponse = join(client.cache("default").get("test")); //then ResponseAssertion.assertThat(getResponse).isOk(); ResponseAssertion.assertThat(getResponse).hasEtag(); Assertions.assertThat(getResponse.getBody()).isEqualTo("Hey!"); } @Test public void shouldReturnJsonWithDefaultConfig() throws Exception { String value = "\"Hey!\""; putStringValueInCache("textCache", "test", value); CompletionStage<RestResponse> getResponse = client.cache("textCache").get("test", APPLICATION_JSON_TYPE); ResponseAssertion.assertThat(getResponse).isOk(); ResponseAssertion.assertThat(getResponse).hasReturnedText(value); } @Test public void shouldPutUnknownFormatValueInCache() { //when RestEntity restEntity = RestEntity.create(MediaType.fromString("application/unknown"), "Hey!"); CompletionStage<RestResponse> response = client.cache("unknown").post("test", restEntity); ResponseAssertion.assertThat(response).isOk(); RestResponse getResponse = join(client.cache("unknown").get("test")); //then ResponseAssertion.assertThat(getResponse).isOk(); ResponseAssertion.assertThat(getResponse).hasEtag(); Assertions.assertThat(getResponse.getBody()).isEqualTo("Hey!"); } @Test public void shouldPutSerializedValueInCache() throws Exception { //when TestClass testClass = new TestClass(); testClass.setName("test"); CompletionStage<RestResponse> response = client.cache("serialized") .post("test", RestEntity.create(APPLICATION_SERIALIZED_OBJECT, convertToBytes(testClass))); ResponseAssertion.assertThat(response).isOk(); RestResponse getResponse = join(client.cache("serialized").get("test", APPLICATION_SERIALIZED_OBJECT_TYPE)); TestClass valueFromCache = convertFromBytes(getResponse.getBodyAsByteArray()); ResponseAssertion.assertThat(getResponse).hasEtag(); Assertions.assertThat(valueFromCache.getName()).isEqualTo("test"); } @Test public void shouldConflictWhenTryingToReplaceExistingEntryUsingPost() throws Exception { //given putStringValueInCache("default", "test", "test"); //when RestEntity restEntity = RestEntity.create(MediaType.fromString("text/plain;charset=UTF-8"), "Hey!"); CompletionStage<RestResponse> response = client.cache("default").post("test", restEntity); //then ResponseAssertion.assertThat(response).isConflicted(); } @Test public void shouldUpdateEntryWhenReplacingUsingPut() throws Exception { //given putStringValueInCache("default", "test", "test"); //when join(client.cache("default").put("test", "Hey!")); RestResponse getResponse = join(client.cache("default").get("test")); //then ResponseAssertion.assertThat(getResponse).isOk(); Assertions.assertThat(getResponse.getBody()).isEqualTo("Hey!"); } @Test public void shouldPutEntryWithDefaultTllAndIdleTime() { //when CompletionStage<RestResponse> response = client.cache("expiration").post("test", "test"); ResponseAssertion.assertThat(response).isOk(); RestResponse getResponse = join(client.cache("expiration").get("test")); //then ResponseAssertion.assertThat(getResponse).isOk(); Assertions.assertThat(getLifespan(getResponse)).isEqualTo(DEFAULT_LIFESPAN_SECONDS); Assertions.assertThat(getMaxIdle(getResponse)).isEqualTo(DEFAULT_MAX_IDLE_SECONDS); } private Long getLifespan(RestResponse response) { return getLongHeader(response, TIME_TO_LIVE_HEADER); } private Long getMaxIdle(RestResponse response) { return getLongHeader(response, MAX_IDLE_TIME_HEADER); } private Long getLongHeader(RestResponse response, ResponseHeader responseHeader) { String header = response.getHeader(responseHeader.getValue()); if (header == null) { return null; } return Long.parseLong(header); } @Test public void shouldPutImmortalEntryWithMinusOneTtlAndIdleTime() { RestCacheClient expirationCache = client.cache("expiration"); //when CompletionStage<RestResponse> response = expirationCache.put("test", "test", -1, -1); ResponseAssertion.assertThat(response).isOk(); RestResponse getResponse = join(expirationCache.get("test")); //then ResponseAssertion.assertThat(getResponse).isOk(); Assertions.assertThat(getLifespan(getResponse)).isNull(); Assertions.assertThat(getMaxIdle(getResponse)).isNull(); } @Test public void shouldPutImmortalEntryWithZeroTtlAndIdleTime() { RestCacheClient expirationCache = client.cache("expiration"); //when CompletionStage<RestResponse> response = expirationCache.post("test", "test", 0, 0); ResponseAssertion.assertThat(response).isOk(); RestResponse getResponse = join(expirationCache.get("test")); //then ResponseAssertion.assertThat(getResponse).isOk(); Assertions.assertThat(getLifespan(getResponse)).isEqualTo(DEFAULT_LIFESPAN_SECONDS); Assertions.assertThat(getMaxIdle(getResponse)).isEqualTo(DEFAULT_MAX_IDLE_SECONDS); } @Test public void testErrorPropagation() throws Exception { putStringValueInCache("xml", "key", "<value/>"); CompletionStage<RestResponse> response = client.cache("xml").get("key", APPLICATION_JSON_TYPE); ResponseAssertion.assertThat(response).isNotAcceptable(); ResponseAssertion.assertThat(response).containsReturnedText("Cannot convert to application/json"); } @Test public void shouldPutEntryWithTtlAndIdleTime() { final RestCacheClient expirationCache = client.cache("expiration"); //when CompletionStage<RestResponse> response = expirationCache.post("test", "test", 50, 50); ResponseAssertion.assertThat(response).isOk(); RestResponse getResponse = join(expirationCache.get("test")); //then ResponseAssertion.assertThat(getResponse).isOk(); Assertions.assertThat(getLifespan(getResponse)).isEqualTo(50); Assertions.assertThat(getMaxIdle(getResponse)).isEqualTo(50); } @Test public void shouldPutLargeObject() { byte[] payload = new byte[1_000_000]; final RestCacheClient binaryCache = client.cache("binary"); CompletionStage<RestResponse> response = binaryCache.post("test", RestEntity.create(APPLICATION_OCTET_STREAM, payload)); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasEtag(); RestResponse getResponse = join(binaryCache.get("test")); Assertions.assertThat(getResponse.getBodyAsByteArray().length).isEqualTo(1_000_000); } @Test public void shouldFailTooLargeObject() { //when byte[] payload = new byte[1_100_000]; RestEntity restEntity = RestEntity.create(APPLICATION_OCTET_STREAM, payload); CompletionStage<RestResponse> response = client.cache("default").post("test", restEntity); //then ResponseAssertion.assertThat(response).isPayloadTooLarge(); } @Test public void testWildcardAccept() throws Exception { putStringValueInCache("default", "test", "test"); CompletionStage<RestResponse> getResponse = client.cache("default").get("test", MATCH_ALL_TYPE); ResponseAssertion.assertThat(getResponse).isOk(); ResponseAssertion.assertThat(getResponse).hasReturnedText("test"); } protected RestResponse get(String cacheName, Object key, String keyContentType, String acceptHeader) { Map<String, String> headers = new HashMap<>(); if (acceptHeader != null) { headers.put(ACCEPT_HEADER.getValue(), acceptHeader); } if (keyContentType != null) { headers.put(KEY_CONTENT_TYPE_HEADER.getValue(), keyContentType); } RestResponse response = join(client.cache(cacheName).get(key.toString(), headers)); ResponseAssertion.assertThat(response).isOk(); return response; } protected RestResponse get(String cacheName, Object key, String acceptHeader) { return get(cacheName, key, null, acceptHeader); } @Test public void shouldAcceptUrlEncodedContentForDefaultCache() throws Exception { String value = "word1 word2"; String urlEncoded = URLEncoder.encode(value, "UTF-8"); putBinaryValueInCache("default", "test", urlEncoded.getBytes(UTF_8), APPLICATION_WWW_FORM_URLENCODED); RestResponse getResponse = get("default", "test", TEXT_PLAIN_TYPE); ResponseAssertion.assertThat(getResponse).hasReturnedText(value); ResponseAssertion.assertThat(getResponse).hasContentType(TEXT_PLAIN_TYPE); } @Test public void shouldNegotiateFromDefaultCacheWithoutAccept() throws Exception { putStringValueInCache("default", "test", "test"); RestResponse getResponse = get("default", "test", null); ResponseAssertion.assertThat(getResponse).hasReturnedText("test"); ResponseAssertion.assertThat(getResponse).hasContentType(APPLICATION_OCTET_STREAM_TYPE); } @Test public void shouldNegotiateFromDefaultCacheWithAccept() throws Exception { String value = "\"test\""; putStringValueInCache("default", "test", value); RestResponse jsonResponse = get("default", "test", "application/json"); ResponseAssertion.assertThat(jsonResponse).hasReturnedText(value); ResponseAssertion.assertThat(jsonResponse).hasContentType("application/json"); RestResponse textResponse = get("default", "test", "text/plain"); ResponseAssertion.assertThat(textResponse).hasReturnedText(value); ResponseAssertion.assertThat(textResponse).hasContentType("text/plain"); RestResponse binaryResponse = get("default", "test", APPLICATION_OCTET_STREAM_TYPE); ResponseAssertion.assertThat(binaryResponse).hasReturnedBytes(value.getBytes(UTF_8)); ResponseAssertion.assertThat(binaryResponse).hasContentType(APPLICATION_OCTET_STREAM_TYPE); } @Test public void shouldNegotiateFromDefaultCacheWithBinary() throws Exception { TestClass testClass = new TestClass(); Marshaller marshaller = TestingUtil.createProtoStreamMarshaller(RestTestSCI.INSTANCE); byte[] javaSerialized = marshaller.objectToByteBuffer(testClass); putBinaryValueInCache("default", "test", javaSerialized, APPLICATION_OCTET_STREAM); RestResponse response = get("default", "test", APPLICATION_OCTET_STREAM_TYPE); ResponseAssertion.assertThat(response).hasContentType(APPLICATION_OCTET_STREAM_TYPE); ResponseAssertion.assertThat(response).hasReturnedBytes(javaSerialized); } @Test public void shouldNegotiateFromDefaultCacheWithWildcardAccept() throws Exception { putStringValueInCache("default", "test", "test"); RestResponse getResponse = get("default", "test", "*/*"); ResponseAssertion.assertThat(getResponse).isOk(); ResponseAssertion.assertThat(getResponse).hasReturnedText("test"); ResponseAssertion.assertThat(getResponse).hasContentType(APPLICATION_OCTET_STREAM_TYPE); } @Test public void shouldNegotiateFromDefaultCacheWithMultipleAccept() throws Exception { String value = "1432"; putStringValueInCache("default", "test", value); RestResponse sameWeightResponse = get("default", "test", "text/html,application/xhtml+xml,*/*"); ResponseAssertion.assertThat(sameWeightResponse).isOk(); ResponseAssertion.assertThat(sameWeightResponse).hasReturnedText(value); ResponseAssertion.assertThat(sameWeightResponse).hasContentType(APPLICATION_OCTET_STREAM_TYPE); RestResponse weightedResponse = get("default", "test", "text/plain;q=0.1, application/json;q=0.8, */*;q=0.7"); ResponseAssertion.assertThat(weightedResponse).isOk(); ResponseAssertion.assertThat(weightedResponse).hasReturnedText(value); ResponseAssertion.assertThat(weightedResponse).hasContentType(APPLICATION_JSON_TYPE); } @Test public void shouldNegotiateFromJsonCacheWithoutAccept() throws Exception { String cacheName = "json"; String key = "1"; String value = "{\"id\": 1}"; putJsonValueInCache(cacheName, key, value); RestResponse getResponse = get(cacheName, key, null); ResponseAssertion.assertThat(getResponse).hasReturnedText(value); ResponseAssertion.assertThat(getResponse).hasContentType(APPLICATION_JSON_TYPE); } @Test public void shouldNegotiateFromJsonCacheWithAccept() throws Exception { String cacheName = "json"; String key = "1"; String value = "{\"id\": 1}"; putJsonValueInCache(cacheName, key, value); RestResponse jsonResponse = get(cacheName, key, APPLICATION_JSON_TYPE); ResponseAssertion.assertThat(jsonResponse).hasReturnedText(value); ResponseAssertion.assertThat(jsonResponse).hasContentType(APPLICATION_JSON_TYPE); RestResponse textResponse = get(cacheName, key, TEXT_PLAIN_TYPE); ResponseAssertion.assertThat(textResponse).hasReturnedBytes(value.getBytes(UTF_8)); ResponseAssertion.assertThat(textResponse).hasContentType(TEXT_PLAIN_TYPE); } @Test public void shouldNegotiateFromJsonCacheWithWildcardAccept() throws Exception { String cacheName = "json"; String key = "1"; String value = "{\"id\": 1}"; putJsonValueInCache(cacheName, key, value); RestResponse jsonResponse = get(cacheName, key, "*/*"); ResponseAssertion.assertThat(jsonResponse).isOk(); ResponseAssertion.assertThat(jsonResponse).hasReturnedText(value); ResponseAssertion.assertThat(jsonResponse).hasContentType(APPLICATION_JSON_TYPE); } @Test public void shouldNegotiateFromJsonCacheWithMultipleAccept() throws Exception { String cacheName = "json"; String key = "1"; String value = "{\"id\": 1}"; putJsonValueInCache(cacheName, key, value); RestResponse jsonResponse = get(cacheName, key, "text/html,*/*"); ResponseAssertion.assertThat(jsonResponse).isOk(); ResponseAssertion.assertThat(jsonResponse).hasReturnedText(value); ResponseAssertion.assertThat(jsonResponse).hasContentType(APPLICATION_JSON_TYPE); RestResponse binaryResponse = get(cacheName, key, "application/xml, text/plain; q=0.71, */*;q=0.7"); ResponseAssertion.assertThat(binaryResponse).isOk(); ResponseAssertion.assertThat(binaryResponse).hasReturnedText(value); ResponseAssertion.assertThat(binaryResponse).hasContentType(TEXT_PLAIN_TYPE); } @Test public void shouldNegotiateOnlySupportedFromDefaultCacheWithMultipleAccept() throws Exception { String value = "<test/>"; putStringValueInCache("default", "test", value); RestResponse getResponse = get("default", "test", "text/html, application/xml"); ResponseAssertion.assertThat(getResponse).hasReturnedText("<test/>"); ResponseAssertion.assertThat(getResponse).hasContentType("application/xml"); } @Test public void shouldHandleInvalidPath() { String Url = String.format("/rest/v2/caches/%s", "asdjsad"); Map<String, String> headers = createHeaders(ACCEPT_HEADER, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); CompletionStage<RestResponse> response = client.raw().get(Url, headers); ResponseAssertion.assertThat(response).isNotFound(); } @Test public void shouldHandleIncompletePath() { String Url = String.format("/rest/v2/caches/%s?action", "default"); CompletionStage<RestResponse> response = client.raw().get(Url); ResponseAssertion.assertThat(response).isBadRequest(); } @Test public void testIntegerKeysXmlToTextValues() { Integer key = 123; String keyContentType = "application/x-java-object;type=java.lang.Integer"; String valueContentType = "application/xml; charset=UTF-8"; String value = "<root>test</root>"; putInCache("default", key, keyContentType, value, valueContentType); RestResponse response = get("default", key, keyContentType, "text/plain"); ResponseAssertion.assertThat(response).hasReturnedText(value); } @Test public void testIntKeysAndJSONToTextValues() { Integer key = 1234; String keyContentType = "application/x-java-object;type=java.lang.Integer"; String value = "{\"a\": 1}"; putInCache("default", key, keyContentType, value, APPLICATION_JSON_TYPE); RestResponse response = get("default", key, keyContentType, TEXT_PLAIN_TYPE); ResponseAssertion.assertThat(response).hasReturnedText(value); } @Test public void testIntKeysTextToXMLValues() { Integer key = 12345; String keyContentType = "application/x-java-object;type=java.lang.Integer"; String value = "<foo>bar</foo>"; putInCache("default", key, keyContentType, value, TEXT_PLAIN_TYPE); RestResponse response = get("default", key, keyContentType, APPLICATION_XML_TYPE); ResponseAssertion.assertThat(response).hasReturnedText(value); } @Test public void testInvalidXMLConversion() throws Exception { String key = "invalid-xml-key"; String invalidXML = "foo"; putInCache("default", key, invalidXML, TEXT_PLAIN_TYPE); CompletionStage<RestResponse> response = client.cache("default").get(key, APPLICATION_XML_TYPE); ResponseAssertion.assertThat(response).containsReturnedText("<string>foo</string>"); } protected Map<String, String> createHeaders(RequestHeader header, String value) { Map<String, String> headers = new HashMap<>(); headers.put(header.getValue(), value); return headers; } }
35,689
37.751357
132
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/ContainerResourceTest.java
package org.infinispan.rest.resources; import static org.infinispan.client.rest.configuration.Protocol.HTTP_11; import static org.infinispan.client.rest.configuration.Protocol.HTTP_20; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML_TYPE; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.infinispan.configuration.cache.CacheMode.DIST_SYNC; import static org.infinispan.configuration.cache.CacheMode.LOCAL; import static org.infinispan.partitionhandling.PartitionHandling.DENY_READ_WRITES; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import java.io.Closeable; import java.io.IOException; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.infinispan.client.rest.RestCacheManagerClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.io.StringBuilderWriter; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.eviction.EvictionStrategy; import org.infinispan.globalstate.ConfigurationStorage; import org.infinispan.health.HealthStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.Security; import org.infinispan.test.TestingUtil; import org.infinispan.topology.LocalTopologyManager; import org.infinispan.util.ControlledTimeService; import org.testng.AssertJUnit; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.ContainerResourceTest") public class ContainerResourceTest extends AbstractRestResourceTest { private static final String PERSISTENT_LOCATION = tmpDirectory(ContainerResourceTest.class.getName()); private static final String CACHE_1 = "cache1"; private static final String CACHE_2 = "cache2"; private static final String DEFAULT_CACHE = "defaultcache"; private static final String INVALID_CACHE = "invalid"; private static final String CACHE_MANAGER_NAME = "default"; public static final String TEMPLATE_CONFIG = "template"; private Configuration cache2Config; private Configuration templateConfig; private RestCacheManagerClient cacheManagerClient, adminCacheManagerClient; private ControlledTimeService timeService; @Override public Object[] factory() { return new Object[]{ new ContainerResourceTest().withSecurity(true).protocol(HTTP_11).browser(false), new ContainerResourceTest().withSecurity(true).protocol(HTTP_11).browser(true), new ContainerResourceTest().withSecurity(false).protocol(HTTP_11).browser(false), new ContainerResourceTest().withSecurity(false).protocol(HTTP_11).browser(true), new ContainerResourceTest().withSecurity(true).protocol(HTTP_20).browser(false), new ContainerResourceTest().withSecurity(true).protocol(HTTP_20).browser(true), new ContainerResourceTest().withSecurity(false).protocol(HTTP_20).browser(false), new ContainerResourceTest().withSecurity(false).protocol(HTTP_20).browser(true), }; } @Override protected GlobalConfigurationBuilder getGlobalConfigForNode(int id) { GlobalConfigurationBuilder config = super.getGlobalConfigForNode(id); config.globalState().enable() .configurationStorage(ConfigurationStorage.OVERLAY) .persistentLocation(Paths.get(PERSISTENT_LOCATION, Integer.toString(id)).toString()) .metrics().accurateSize(true); return config; } @Override protected void createCacheManagers() throws Exception { Util.recursiveFileRemove(PERSISTENT_LOCATION); super.createCacheManagers(); cacheManagerClient = client.cacheManager(CACHE_MANAGER_NAME); adminCacheManagerClient = adminClient.cacheManager(CACHE_MANAGER_NAME); timeService = new ControlledTimeService(); cacheManagers.forEach(cm -> TestingUtil.replaceComponent(cm, TimeService.class, timeService, true)); } @Override protected void defineCaches(EmbeddedCacheManager cm) { Configuration cache1Config = getCache1Config(); cache2Config = getCache2Config(); ConfigurationBuilder templateConfigBuilder = new ConfigurationBuilder(); templateConfigBuilder.template(true).clustering().cacheMode(LOCAL).encoding().key().mediaType(TEXT_PLAIN_TYPE); templateConfig = templateConfigBuilder.build(); cm.defineConfiguration(CACHE_1, cache1Config); cm.defineConfiguration(CACHE_2, cache2Config); cm.defineConfiguration(TEMPLATE_CONFIG, templateConfig); } private Configuration getCache1Config() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.statistics().enable().clustering().cacheMode(DIST_SYNC).partitionHandling().whenSplit(DENY_READ_WRITES); return builder.build(); } private Configuration getCache2Config() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.statistics().enable().clustering().cacheMode(LOCAL).encoding().key().mediaType(TEXT_PLAIN_TYPE); builder.memory().maxCount(1000).storage(StorageType.HEAP).whenFull(EvictionStrategy.REMOVE); return builder.build(); } @Test public void testHealth() { RestResponse response = join(cacheManagerClient.health()); ResponseAssertion.assertThat(response).isOk(); Json jsonNode = Json.read(response.getBody()); Json clusterHealth = jsonNode.at("cluster_health"); // One of the caches is in FAILED state assertEquals(clusterHealth.at("health_status").asString(), HealthStatus.FAILED.toString()); assertEquals(clusterHealth.at("number_of_nodes").asInteger(), 2); assertEquals(clusterHealth.at("node_names").asJsonList().size(), 2); Json cacheHealth = jsonNode.at("cache_health"); List<String> cacheNames = extractCacheNames(cacheHealth); assertTrue(cacheNames.contains(CACHE_1)); assertTrue(cacheNames.contains(CACHE_2)); response = join(cacheManagerClient.health(true)); ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasNoContent(); } @Test public void testCacheConfigs() { String accept = "text/plain; q=0.9, application/json; q=0.6"; RestResponse response = join(cacheManagerClient.cacheConfigurations(accept)); ResponseAssertion.assertThat(response).isOk(); String json = response.getBody(); Json jsonNode = Json.read(json); Map<String, String> cachesAndConfig = cacheAndConfig(jsonNode); assertEquals(cachesAndConfig.get(TEMPLATE_CONFIG), cacheConfigToJson(TEMPLATE_CONFIG, templateConfig)); assertEquals(cachesAndConfig.get(CACHE_2), cacheConfigToJson(CACHE_2, cache2Config)); } @Test public void testCacheConfigsTemplates() { String accept = "text/plain; q=0.9, application/json; q=0.6"; RestResponse response = join(cacheManagerClient.templates(accept)); ResponseAssertion.assertThat(response).isOk(); String json = response.getBody(); Json jsonNode = Json.read(json); Map<String, String> cachesAndConfig = cacheAndConfig(jsonNode); assertEquals(cachesAndConfig.get(TEMPLATE_CONFIG), cacheConfigToJson(TEMPLATE_CONFIG, templateConfig)); assertFalse(cachesAndConfig.containsKey(CACHE_1)); assertFalse(cachesAndConfig.containsKey(CACHE_2)); } @Test public void testCaches() { RestResponse response = join(cacheManagerClient.caches()); ResponseAssertion.assertThat(response).isOk(); String json = response.getBody(); Json jsonNode = Json.read(json); List<String> names = find(jsonNode, "name"); Set<String> expectedNames = Util.asSet(DEFAULT_CACHE, CACHE_1, CACHE_2, INVALID_CACHE); assertEquals(expectedNames, new HashSet<>(names)); List<String> status = find(jsonNode, "status"); assertTrue(status.contains("RUNNING")); List<String> types = find(jsonNode, "type"); assertTrue(types.contains("local-cache")); assertTrue(types.contains("distributed-cache")); List<String> simpleCaches = find(jsonNode, "simple_cache"); assertTrue(simpleCaches.contains("false")); List<String> transactional = find(jsonNode, "transactional"); assertTrue(transactional.contains("false")); List<String> persistent = find(jsonNode, "persistent"); assertTrue(persistent.contains("false")); List<String> bounded = find(jsonNode, "bounded"); List<String> notBoundedCaches = bounded.stream().filter(b -> "false".equals(b)).collect(Collectors.toList()); List<String> boundedCaches = bounded.stream().filter(b -> "true".equals(b)).collect(Collectors.toList()); assertEquals(1, boundedCaches.size()); assertEquals(3, notBoundedCaches.size()); List<String> secured = find(jsonNode, "secured"); assertTrue(secured.contains("false")); List<String> indexed = find(jsonNode, "indexed"); assertTrue(indexed.contains("false")); List<String> hasRemoteBackup = find(jsonNode, "has_remote_backup"); assertTrue(hasRemoteBackup.contains("false")); List<String> health = find(jsonNode, "health"); assertTrue(health.contains("HEALTHY")); List<String> isRebalancingEnabled = find(jsonNode, "rebalancing_enabled"); assertTrue(isRebalancingEnabled.contains("true")); } @Test public void testCachesWithIgnoreCache() { if (security) { Security.doAs(TestingUtil.makeSubject(AuthorizationPermission.ADMIN.name()), () -> serverStateManager.ignoreCache(CACHE_1)); } else { serverStateManager.ignoreCache(CACHE_1); } RestResponse response = join(cacheManagerClient.caches()); ResponseAssertion.assertThat(response).isOk(); String json = response.getBody(); Json jsonNode = Json.read(json); List<String> names = find(jsonNode, "name"); Set<String> expectedNames = Util.asSet(DEFAULT_CACHE, CACHE_1, CACHE_2, INVALID_CACHE); assertEquals(expectedNames, new HashSet<>(names)); List<String> status = find(jsonNode, "status"); assertTrue(status.contains("RUNNING")); assertTrue(status.contains("IGNORED")); } private List<String> find(Json array, String name) { return array.asJsonList().stream().map(j -> j.at(name).getValue().toString()).collect(Collectors.toList()); } @Test public void testGetGlobalConfig() { RestResponse response = join(adminCacheManagerClient.globalConfiguration()); ResponseAssertion.assertThat(response).isOk(); String json = response.getBody(); EmbeddedCacheManager embeddedCacheManager = cacheManagers.get(0); GlobalConfiguration globalConfiguration = embeddedCacheManager.withSubject(ADMIN).getCacheManagerConfiguration(); StringBuilderWriter sw = new StringBuilderWriter(); try (ConfigurationWriter w = ConfigurationWriter.to(sw).withType(APPLICATION_JSON).build()) { new ParserRegistry().serialize(w, globalConfiguration, Collections.emptyMap()); } assertEquals(sw.toString(), json); } @Test public void testGetGlobalConfigXML() { RestResponse response = join(adminCacheManagerClient.globalConfiguration(APPLICATION_XML_TYPE)); ResponseAssertion.assertThat(response).isOk(); String xml = response.getBody(); ParserRegistry parserRegistry = new ParserRegistry(); ConfigurationBuilderHolder builderHolder = parserRegistry.parse(xml); GlobalConfigurationBuilder globalConfigurationBuilder = builderHolder.getGlobalConfigurationBuilder(); assertNotNull(globalConfigurationBuilder.build()); } @Test public void testInfo() { RestResponse response = join(cacheManagerClient.info()); ResponseAssertion.assertThat(response).isOk(); String json = response.getBody(); Json cmInfo = Json.read(json); assertFalse(cmInfo.at("version").asString().isEmpty()); assertEquals(2, cmInfo.at("cluster_members").asList().size()); assertEquals(2, cmInfo.at("cluster_members_physical_addresses").asList().size()); assertEquals("LON-1", cmInfo.at("local_site").asString()); assertTrue(cmInfo.at("relay_node").asBoolean()); assertEquals(1, cmInfo.at("relay_nodes_address").asList().size()); assertEquals(1, cmInfo.at("sites_view").asList().size()); assertEquals("LON-1", cmInfo.at("sites_view").asList().get(0)); assertTrue(cmInfo.at("rebalancing_enabled").asBoolean()); } @Test public void testStats() { RestResponse response = join(adminCacheManagerClient.stats()); ResponseAssertion.assertThat(response).isOk(); String json = response.getBody(); Json cmStats = Json.read(json); assertTrue(cmStats.at("statistics_enabled").asBoolean()); assertEquals(0, cmStats.at("stores").asInteger()); assertEquals(0, cmStats.at("number_of_entries").asInteger()); // Advance 1 second for the cached stats to expire timeService.advance(1000); cacheManagers.iterator().next().getCache(CACHE_1).put("key", "value"); cmStats = Json.read(join(adminCacheManagerClient.stats()).getBody()); assertEquals(1, cmStats.at("stores").asInteger()); assertEquals(1, cmStats.at("number_of_entries").asInteger()); } @Test public void testConfigListener() throws InterruptedException, IOException { SSEListener sseListener = new SSEListener(); try (Closeable ignored = adminClient.raw().listen("/rest/v2/container/config?action=listen&includeCurrentState=true", Collections.emptyMap(), sseListener)) { AssertJUnit.assertTrue(sseListener.openLatch.await(10, TimeUnit.SECONDS)); // Assert that all of the existing caches and templates have a corresponding event sseListener.expectEvent("create-template", TEMPLATE_CONFIG); sseListener.expectEvent("create-cache", "___protobuf_metadata"); sseListener.expectEvent("create-cache", CACHE_2); sseListener.expectEvent("create-cache", INVALID_CACHE); sseListener.expectEvent("create-cache", CACHE_1); sseListener.expectEvent("create-cache", DEFAULT_CACHE); sseListener.expectEvent("create-cache", "___script_cache"); // Assert that new cache creations create an event createCache("{\"local-cache\":{\"encoding\":{\"media-type\":\"text/plain\"}}}", "listen1"); sseListener.expectEvent("create-cache", "text/plain"); createCache("{\"local-cache\":{\"encoding\":{\"media-type\":\"application/octet-stream\"}}}", "listen2"); sseListener.expectEvent("create-cache", "application/octet-stream"); // Assert that deletions create an event assertThat(client.cache("listen1").delete()).isOk(); sseListener.expectEvent("remove-cache", "listen1"); } } private void createCache(String json, String name) { RestEntity jsonEntity = RestEntity.create(APPLICATION_JSON, json); CompletionStage<RestResponse> response = client.cache(name).createWithConfiguration(jsonEntity); assertThat(response).isOk(); } @Test public void testRebalancingActions() { assertRebalancingStatus(true); RestResponse response = join(adminCacheManagerClient.disableRebalancing()); ResponseAssertion.assertThat(response).isOk(); assertRebalancingStatus(false); response = join(adminCacheManagerClient.enableRebalancing()); ResponseAssertion.assertThat(response).isOk(); assertRebalancingStatus(true); } private void assertRebalancingStatus(boolean enabled) { for (EmbeddedCacheManager cm : cacheManagers) { eventuallyEquals(enabled, () -> { try { return TestingUtil.extractGlobalComponent(cm, LocalTopologyManager.class).isRebalancingEnabled(); } catch (Exception e) { fail("Unexpected exception", e); return !enabled; } }); } } private Map<String, String> cacheAndConfig(Json list) { Map<String, String> result = new HashMap<>(); list.asJsonList().forEach(node -> result.put(node.at("name").asString(), node.at("configuration").toString())); return result; } private List<String> extractCacheNames(Json cacheStatuses) { return cacheStatuses.asJsonList().stream().map(j -> j.at("cache_name").asString()).collect(Collectors.toList()); } }
17,828
42.698529
163
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/CacheResourceV2Test.java
package org.infinispan.rest.resources; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.client.rest.configuration.Protocol.HTTP_11; import static org.infinispan.client.rest.configuration.Protocol.HTTP_20; import static org.infinispan.commons.api.CacheContainerAdmin.AdminFlag.VOLATILE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OCTET_STREAM; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_YAML; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_YAML_TYPE; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.infinispan.commons.util.EnumUtil.EMPTY_BIT_SET; import static org.infinispan.commons.util.Util.getResourceAsString; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.context.Flag.SKIP_CACHE_LOAD; import static org.infinispan.context.Flag.SKIP_INDEXING; import static org.infinispan.globalstate.GlobalConfigurationManager.CONFIG_STATE_CACHE_NAME; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; import static org.infinispan.rest.RequestHeader.ACCEPT_HEADER; import static org.infinispan.rest.RequestHeader.KEY_CONTENT_TYPE_HEADER; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.xml.parsers.DocumentBuilderFactory; import org.assertj.core.api.Assertions; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestRawClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.configuration.io.NamingStrategy; import org.infinispan.commons.configuration.io.PropertyReplacer; import org.infinispan.commons.configuration.io.URLConfigurationResourceResolver; import org.infinispan.commons.configuration.io.yaml.YamlConfigurationReader; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.container.versioning.NumericVersion; import org.infinispan.container.versioning.SimpleClusteredVersion; import org.infinispan.factories.ComponentRegistry; import org.infinispan.globalstate.ConfigurationStorage; import org.infinispan.globalstate.GlobalConfigurationManager; import org.infinispan.globalstate.ScopedState; import org.infinispan.globalstate.impl.CacheState; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.metadata.Metadata; import org.infinispan.partitionhandling.AvailabilityMode; import org.infinispan.partitionhandling.PartitionHandling; import org.infinispan.partitionhandling.impl.PartitionHandlingManager; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.reactive.publisher.impl.ClusterPublisherManager; import org.infinispan.reactive.publisher.impl.DeliveryGuarantee; import org.infinispan.reactive.publisher.impl.SegmentPublisherSupplier; import org.infinispan.rest.ResponseHeader; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.test.TestException; import org.infinispan.test.TestingUtil; import org.infinispan.topology.LocalTopologyManager; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.reporters.Files; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import io.reactivex.rxjava3.core.Flowable; import okhttp3.internal.http2.StreamResetException; @Test(groups = "functional", testName = "rest.CacheResourceV2Test") public class CacheResourceV2Test extends AbstractRestResourceTest { // Wild guess: an empty index shouldn't be more than this many bytes private static final long MAX_EMPTY_INDEX_SIZE = 300L; // Wild guess: a non-empty index (populated with addData) should be more than this many bytes private static final long MIN_NON_EMPTY_INDEX_SIZE = 1000L; private static final String PERSISTENT_LOCATION = tmpDirectory(CacheResourceV2Test.class.getName()); private static final String PROTO_SCHEMA = " /* @Indexed */ \n" + " message Entity { \n" + " /* @Field */ \n" + " required int32 value=1; \n" + " optional string description=2; \n" + " } \n" + " /* @Indexed */ \n" + " message Another { \n" + " /* @Field */ \n" + " required int32 value=1; \n" + " optional string description=2; \n" + " }"; protected CacheMode cacheMode; @Override protected String parameters() { return "[security=" + security + ", protocol=" + protocol.toString() + ", ssl=" + ssl + ", cacheMode=" + cacheMode + ", browser=" + browser +"]"; } protected CacheResourceV2Test withCacheMode(CacheMode cacheMode) { this.cacheMode = cacheMode; return this; } @Override protected void defineCaches(EmbeddedCacheManager cm) { ConfigurationBuilder configurationBuilder = getDefaultCacheBuilder(); if (cacheMode != null) { // We force num owners to 1 so that some operations have to go to a remote node configurationBuilder.clustering().cacheMode(cacheMode).hash().numOwners(1); } cm.defineConfiguration("default", configurationBuilder.build()); cm.defineConfiguration("proto", getProtoCacheBuilder().build()); cm.defineConfiguration("simple-text", getTextCacheBuilder().build()); Cache<String, String> metadataCache = cm.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.putIfAbsent("sample.proto", PROTO_SCHEMA); assertFalse(metadataCache.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX)); cm.defineConfiguration("indexedCache", getIndexedPersistedCache().build()); cm.defineConfiguration("denyReadWritesCache", getDefaultCacheBuilder().clustering().partitionHandling().whenSplit(PartitionHandling.DENY_READ_WRITES).build()); } public ConfigurationBuilder getProtoCacheBuilder() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); return builder; } public ConfigurationBuilder getTextCacheBuilder() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.encoding().mediaType(TEXT_PLAIN_TYPE); return builder; } @Override public Object[] factory() { return new Object[]{ new CacheResourceV2Test().withSecurity(false).protocol(HTTP_11).ssl(false).browser(false), new CacheResourceV2Test().withSecurity(false).protocol(HTTP_11).ssl(false).browser(true), new CacheResourceV2Test().withSecurity(true).protocol(HTTP_20).ssl(false).browser(false), new CacheResourceV2Test().withSecurity(true).protocol(HTTP_20).ssl(false).browser(true), new CacheResourceV2Test().withSecurity(true).protocol(HTTP_11).ssl(true).browser(false), new CacheResourceV2Test().withSecurity(true).protocol(HTTP_11).ssl(true).browser(true), new CacheResourceV2Test().withSecurity(true).protocol(HTTP_20).ssl(true).browser(false), new CacheResourceV2Test().withSecurity(true).protocol(HTTP_20).ssl(true).browser(true), new CacheResourceV2Test().withCacheMode(CacheMode.DIST_SYNC).withSecurity(false).protocol(HTTP_11).ssl(false).browser(false), new CacheResourceV2Test().withCacheMode(CacheMode.DIST_SYNC).withSecurity(false).protocol(HTTP_11).ssl(false).browser(true), new CacheResourceV2Test().withCacheMode(CacheMode.DIST_SYNC).withSecurity(true).protocol(HTTP_20).ssl(false).browser(false), new CacheResourceV2Test().withCacheMode(CacheMode.DIST_SYNC).withSecurity(true).protocol(HTTP_20).ssl(false).browser(true), new CacheResourceV2Test().withCacheMode(CacheMode.DIST_SYNC).withSecurity(true).protocol(HTTP_11).ssl(true).browser(false), new CacheResourceV2Test().withCacheMode(CacheMode.DIST_SYNC).withSecurity(true).protocol(HTTP_11).ssl(true).browser(true), new CacheResourceV2Test().withCacheMode(CacheMode.DIST_SYNC).withSecurity(true).protocol(HTTP_20).ssl(true).browser(false), new CacheResourceV2Test().withCacheMode(CacheMode.DIST_SYNC).withSecurity(true).protocol(HTTP_20).ssl(true).browser(true), }; } private ConfigurationBuilder getIndexedPersistedCache() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.statistics().enable(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("Entity") .addIndexedEntity("Another") .statistics().enable() .persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).shared(true).storeName("store"); return builder; } @Override protected void createCacheManagers() throws Exception { Util.recursiveFileRemove(PERSISTENT_LOCATION); super.createCacheManagers(); } @Override protected GlobalConfigurationBuilder getGlobalConfigForNode(int id) { GlobalConfigurationBuilder config = super.getGlobalConfigForNode(id); config.globalState().enable() .configurationStorage(ConfigurationStorage.OVERLAY) .persistentLocation(Paths.get(PERSISTENT_LOCATION, Integer.toString(id)).toString()) .metrics().accurateSize(true); return config; } @Test public void testCacheV2KeyOps() { RestCacheClient cacheClient = client.cache("default"); RestResponse response = join(cacheClient.post("key", "value")); assertThat(response).isOk(); response = join(cacheClient.post("key", "value")); assertThat(response).isConflicted().hasReturnedText("An entry already exists"); response = join(cacheClient.put("key", "value-new")); assertThat(response).isOk(); response = join(cacheClient.get("key")); assertThat(response).hasReturnedText("value-new"); response = join(cacheClient.head("key")); assertThat(response).isOk(); assertThat(response).hasNoContent(); response = join(cacheClient.remove("key")); assertThat(response).isOk(); response = join(cacheClient.get("key")); assertThat(response).isNotFound(); } @Test public void testCreateCacheEncodedName() { testCreateAndUseCache("a/"); testCreateAndUseCache("a/b/c"); testCreateAndUseCache("a-b-c"); testCreateAndUseCache("áb\\ćé/+-$"); testCreateAndUseCache("org.infinispan.cache"); testCreateAndUseCache("a%25bc"); } @Test public void testCreateCacheEncoding() { String cacheName = "encoding-test"; String json = "{\"local-cache\":{\"encoding\":{\"media-type\":\"text/plain\"}}}"; createCache(json, cacheName); String cacheConfig = getCacheConfig(APPLICATION_JSON_TYPE, cacheName); Json encoding = Json.read(cacheConfig).at(cacheName).at("local-cache").at("encoding"); Json mediaType = encoding.at("media-type"); assertEquals(TEXT_PLAIN_TYPE, mediaType.asString()); } private void testCreateAndUseCache(String name) { String cacheConfig = "{\"distributed-cache\":{\"mode\":\"SYNC\"}}"; RestCacheClient cacheClient = client.cache(name); RestEntity config = RestEntity.create(APPLICATION_JSON, cacheConfig); CompletionStage<RestResponse> response = cacheClient.createWithConfiguration(config); assertThat(response).isOk(); CompletionStage<RestResponse> sizeResponse = cacheClient.size(); assertThat(sizeResponse).isOk(); assertThat(sizeResponse).containsReturnedText("0"); RestResponse namesResponse = join(client.caches()); assertThat(namesResponse).isOk(); List<String> names = Json.read(namesResponse.getBody()).asJsonList().stream().map(Json::asString).collect(Collectors.toList()); assertTrue(names.contains(name)); CompletionStage<RestResponse> putResponse = cacheClient.post("key", "value"); assertThat(putResponse).isOk(); CompletionStage<RestResponse> getResponse = cacheClient.get("key"); assertThat(getResponse).isOk(); assertThat(getResponse).containsReturnedText("value"); } @Test public void testCreateAndAlterCache() { String cacheConfig = "{\n" + " \"distributed-cache\" : {\n" + " \"mode\" : \"SYNC\",\n" + " \"statistics\" : true,\n" + " \"encoding\" : {\n" + " \"key\" : {\n" + " \"media-type\" : \"application/x-protostream\"\n" + " },\n" + " \"value\" : {\n" + " \"media-type\" : \"application/x-protostream\"\n" + " }\n" + " },\n" + " \"expiration\" : {\n" + " \"lifespan\" : \"60000\"\n" + " },\n" + " \"memory\" : {\n" + " \"max-count\" : \"1000\",\n" + " \"when-full\" : \"REMOVE\"\n" + " }\n" + " }\n" + "}\n"; String cacheConfigAlter = "{\n" + " \"distributed-cache\" : {\n" + " \"mode\" : \"SYNC\",\n" + " \"statistics\" : true,\n" + " \"encoding\" : {\n" + " \"key\" : {\n" + " \"media-type\" : \"application/x-protostream\"\n" + " },\n" + " \"value\" : {\n" + " \"media-type\" : \"application/x-protostream\"\n" + " }\n" + " },\n" + " \"expiration\" : {\n" + " \"lifespan\" : \"30000\"\n" + " },\n" + " \"memory\" : {\n" + " \"max-count\" : \"2000\",\n" + " \"when-full\" : \"REMOVE\"\n" + " }\n" + " }\n" + "}\n"; String cacheConfigConflict = "{\n" + " \"distributed-cache\" : {\n" + " \"mode\" : \"ASYNC\"\n" + " }\n" + "}\n"; RestCacheClient cacheClient = client.cache("mutable"); CompletionStage<RestResponse> response = cacheClient.createWithConfiguration(RestEntity.create(APPLICATION_JSON, cacheConfig)); assertThat(response).isOk(); response = cacheClient.updateWithConfiguration(RestEntity.create(APPLICATION_JSON, cacheConfigAlter)); assertThat(response).isOk(); response = cacheClient.configuration(); assertThat(response).isOk(); String configFromServer = join(response).getBody(); assertTrue(configFromServer.contains("\"expiration\":{\"lifespan\":\"30000\"}")); assertTrue(configFromServer.contains("\"memory\":{\"max-count\":\"2000\"")); response = cacheClient.updateWithConfiguration(RestEntity.create(APPLICATION_JSON, cacheConfigConflict)); assertThat(response).isBadRequest(); } @Test public void testUpdateFailure() { String cacheConfig = "localCache:\n encoding:\n mediaType: \"application/x-protostream\"\n"; String cacheConfigAlter = "localCache:\n encoding:\n mediaType: \"application/x-java-serialized-object\"\n"; RestCacheClient cacheClient = client.cache("updateFailure"); CompletionStage<RestResponse> response = cacheClient.createWithConfiguration(RestEntity.create(APPLICATION_YAML, cacheConfig)); assertThat(response).isOk(); response = cacheClient.updateWithConfiguration(RestEntity.create(APPLICATION_YAML, cacheConfigAlter)); assertThat(response).isBadRequest(); String body = join(response).getBody(); assertThat(body).contains("ISPN000961: Incompatible attribute"); } @Test public void testMutableAttributes() { String cacheName = "mutable-attributes"; String json = "{\"local-cache\":{\"encoding\":{\"media-type\":\"text/plain\"}}}"; RestCacheClient cacheClient = createCache(adminClient, json, cacheName); CompletionStage<RestResponse> response = cacheClient.configurationAttributes(true); assertThat(response).isOk(); Json attributes = Json.read(join(response).getBody()); assertEquals(13, attributes.asJsonMap().size()); assertEquals("long", attributes.at("clustering.remote-timeout").at("type").asString()); assertEquals(15000, attributes.at("clustering.remote-timeout").at("value").asLong()); assertThat(attributes.at("indexing.indexed-entities").at("type").asString()).isEqualTo("set"); assertThat(attributes.at("indexing.indexed-entities").at("value").asList()).isEmpty(); } public void testUpdateConfigurationAttribute() { String protoSchema = "package org.infinispan;\n\n" + "/**\n" + " * @Indexed\n" + " */\n" + "message Developer {\n" + " /**\n" + " * @Basic\n" + " */\n" + " optional string nick = 1;\n" + " /**\n" + " * @Basic(sortable=true)\n" + " */\n" + " optional int32 contributions = 2;\n" + "}\n" + "/**\n" + " * @Indexed\n" + " */\n" + "message Engineer { \n" + " /**\n" + " * @Basic\n" + " */\n" + " optional string nick = 1;\n" + " /**\n" + " * @Basic(sortable=true)\n" + " */\n" + " optional int32 contributions = 2;\n" + "}\n"; // Register schema RestResponse restResponse = join(client.schemas().put("dev.proto", protoSchema)); assertThat(restResponse).isOk(); // Create the indexed cache ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable().storage(LOCAL_HEAP).addIndexedEntities("org.infinispan.Developer"); String cacheConfig = cacheConfigToJson("developers", builder.build()); RestCacheClient cacheClient = adminClient.cache("developers"); RestEntity config = RestEntity.create(APPLICATION_JSON, cacheConfig); CompletionStage<RestResponse> response = cacheClient.createWithConfiguration(config); assertThat(response).isOk(); response = cacheClient.updateConfigurationAttribute("indexing.indexed-entities", "org.infinispan.Developer org.infinispan.Engineer"); assertThat(response).isOk(); response = cacheClient.configuration(); assertThat(response).isOk(); String configFromServer = join(response).getBody(); assertThat(configFromServer) .contains("\"indexed-entities\":[\"org.infinispan.Engineer\",\"org.infinispan.Developer\"]"); } @Test public void testCacheV2LifeCycle() throws Exception { String xml = getResourceAsString("cache.xml", getClass().getClassLoader()); String json = getResourceAsString("cache.json", getClass().getClassLoader()); RestEntity xmlEntity = RestEntity.create(APPLICATION_XML, xml); RestEntity jsonEntity = RestEntity.create(APPLICATION_JSON, json); CompletionStage<RestResponse> response = client.cache("cache1").createWithConfiguration(xmlEntity, VOLATILE); assertThat(response).isOk(); assertPersistence("cache1", false); response = client.cache("cache2").createWithConfiguration(jsonEntity); assertThat(response).isOk(); assertPersistence("cache2", true); String mediaList = "application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; response = client.cache("cache1").configuration(mediaList); assertThat(response).isOk(); String cache1Cfg = join(response).getBody(); response = client.cache("cache2").configuration(); assertThat(response).isOk(); String cache2Cfg = join(response).getBody(); assertEquals(cache1Cfg, cache2Cfg.replace("cache2", "cache1")); response = client.cache("cache1").configuration("application/xml"); assertThat(response).isOk(); String cache1Xml = join(response).getBody(); ParserRegistry registry = new ParserRegistry(); Configuration xmlConfig = registry.parse(cache1Xml).getCurrentConfigurationBuilder().build(); assertEquals(1200000, xmlConfig.clustering().l1().lifespan()); assertEquals(60500, xmlConfig.clustering().stateTransfer().timeout()); response = client.cache("cache1").configuration("application/xml; q=0.9"); assertThat(response).isOk(); } @Test public void testCreateDeleteCache() throws Exception { createDeleteCache(getResourceAsString("cache.xml", getClass().getClassLoader())); } @Test public void testCreateDeleteCacheFromFragment() throws Exception { createDeleteCache(getResourceAsString("cache-fragment.xml", getClass().getClassLoader())); } private void createDeleteCache(String xml) { RestEntity xmlEntity = RestEntity.create(APPLICATION_XML, xml); RestCacheClient cacheClient = client.cache("cacheCRUD"); CompletionStage<RestResponse> response = cacheClient.createWithConfiguration(xmlEntity, VOLATILE); assertThat(response).isOk(); response = cacheClient.stats(); assertThat(response).isOk().hasJson().hasProperty("current_number_of_entries").is(-1); response = cacheClient.delete(); assertThat(response).isOk(); response = cacheClient.stats(); assertThat(response).isNotFound().hasReturnedText("ISPN012010: Cache with name 'cacheCRUD' not found amongst the configured caches"); } private void assertPersistence(String name, boolean persisted) { EmbeddedCacheManager cm = cacheManagers.iterator().next(); Cache<ScopedState, CacheState> configCache = cm.getCache(CONFIG_STATE_CACHE_NAME); assertEquals(persisted, configCache.entrySet() .stream().anyMatch(e -> e.getKey().getName().equals(name) && !e.getValue().getFlags().contains(VOLATILE))); } @Test public void testCacheV2Stats() { String cacheJson = "{ \"distributed-cache\" : { \"statistics\":true } }"; RestCacheClient cacheClient = client.cache("statCache"); RestEntity jsonEntity = RestEntity.create(APPLICATION_JSON, cacheJson); CompletionStage<RestResponse> response = cacheClient.createWithConfiguration(jsonEntity, VOLATILE); assertThat(response).isOk(); putStringValueInCache("statCache", "key1", "data"); putStringValueInCache("statCache", "key2", "data"); response = cacheClient.stats(); assertThat(response).isOk(); Json jsonNode = Json.read(join(response).getBody()); assertEquals(jsonNode.at("current_number_of_entries").asInteger(), 2); assertEquals(jsonNode.at("stores").asInteger(), 2); response = cacheClient.clear(); assertThat(response).isOk(); response = cacheClient.stats(); assertThat(response).isOk().hasJson().hasProperty("current_number_of_entries").is(0); } @Test @TestForIssue(jiraKey = "ISPN-14957") public void getCacheInfoInternalCache() { RestCacheClient scriptCache = client.cache("___script_cache"); CompletionStage<RestResponse> details = scriptCache.details(); assertThat(details).isOk(); RestResponse response = join(details); String body = response.getBody(); assertThat(body).isNotBlank(); } @Test public void testCacheV2Distribution() { String cacheJson = "{ \"distributed-cache\" : { \"statistics\":true, \"memory\" : {" + "\"storage\": \"OFF_HEAP\", \"max-size\": \"1MB\" } } }"; RestCacheClient cacheClient = client.cache("distributionCache"); RestEntity jsonEntity = RestEntity.create(APPLICATION_JSON, cacheJson); CompletionStage<RestResponse> response = cacheClient.createWithConfiguration(jsonEntity, VOLATILE); assertThat(response).isOk(); putStringValueInCache("distributionCache", "key1", "data"); putStringValueInCache("distributionCache", "key2", "data"); response = cacheClient.distribution(); assertThat(response).isOk(); Json jsonNode = Json.read(join(response).getBody()); assertTrue(jsonNode.isArray()); List<Json> jsons = jsonNode.asJsonList(); assertEquals(NUM_SERVERS, jsons.size()); Pattern pattern = Pattern.compile(this.getClass().getSimpleName() + "-Node[a-zA-Z]$"); Map<String, Long> previousSizes = new HashMap<>(); for (Json node : jsons) { assertEquals(node.at("memory_entries").asInteger(), 2); assertEquals(node.at("total_entries").asInteger(), 2); assertEquals(node.at("node_addresses").asJsonList().size(), 1); assertTrue(pattern.matcher(node.at("node_name").asString()).matches()); assertTrue(node.at("memory_used").asLong() > 0); previousSizes.put(node.at("node_name").asString(), node.at("memory_used").asLong()); } response = cacheClient.clear(); assertThat(response).isOk(); response = cacheClient.distribution(); assertThat(response).isOk(); jsonNode = Json.read(join(response).getBody()); assertTrue(jsonNode.isArray()); jsons = jsonNode.asJsonList(); assertEquals(NUM_SERVERS, jsons.size()); for (Json node : jsons) { assertEquals(node.at("memory_entries").asInteger(), 0); assertEquals(node.at("total_entries").asInteger(), 0); // Even though the cache was cleared, it still occupies some space. assertTrue(node.at("memory_used").asLong() > 0); // But less space than before. assertTrue(node.at("memory_used").asLong() < previousSizes.get(node.at("node_name").asString())); } } @Test public void testCacheV2KeyDistribution() { final String cacheName = "keyDistribution"; String cacheJson = "{ \"distributed-cache\" : { \"statistics\":true } }"; createCache(cacheJson, cacheName); RestCacheClient cacheClient = client.cache(cacheName); putStringValueInCache(cacheName, "key1", "data"); putStringValueInCache(cacheName, "key2", "data"); Map<String, Boolean> sample = Map.of("key1", true, "key2", true, "unknown", false); for (Map.Entry<String, Boolean> entry : sample.entrySet()) { CompletionStage<RestResponse> response = cacheClient.distribution(entry.getKey()); assertThat(response).isOk(); try (RestResponse restResponse = join(response)) { Json jsonNode = Json.read(restResponse.getBody()); assertEquals((boolean) entry.getValue(), jsonNode.at("contains_key").asBoolean()); assertTrue(jsonNode.at("owners").isArray()); List<Json> distribution = jsonNode.at("owners").asJsonList(); assertEquals(NUM_SERVERS, distribution.size()); Pattern pattern = Pattern.compile(this.getClass().getSimpleName() + "-Node[a-zA-Z]$"); for (Json node : distribution) { assertEquals(node.at("node_addresses").asJsonList().size(), 1); assertTrue(pattern.matcher(node.at("node_name").asString()).matches()); assertTrue(node.has("primary")); } if (entry.getValue()) { assertTrue(distribution.stream().anyMatch(n -> n.at("primary").asBoolean())); } else { assertTrue(distribution.stream().noneMatch(n -> n.at("primary").asBoolean())); } } catch (Exception e) { throw new TestException(e); } } } @Test public void testCacheSize() { for (int i = 0; i < 100; i++) { putInCache("default", i, "" + i, APPLICATION_JSON_TYPE); } CompletionStage<RestResponse> response = client.cache("default").size(); assertThat(response).isOk(); assertThat(response).containsReturnedText("100"); } @Test public void testCacheFullDetail() { RestResponse response = join(client.cache("default").details()); Json document = Json.read(response.getBody()); assertThat(response).isOk(); assertThat(document.at("stats")).isNotNull(); assertThat(document.at("size")).isNotNull(); assertThat(document.at("configuration")).isNotNull(); assertThat(document.at("rehash_in_progress")).isNotNull(); assertThat(document.at("persistent")).isNotNull(); assertThat(document.at("bounded")).isNotNull(); assertThat(document.at("indexed")).isNotNull(); assertThat(document.at("has_remote_backup")).isNotNull(); assertThat(document.at("secured")).isNotNull(); assertThat(document.at("indexing_in_progress")).isNotNull(); assertThat(document.at("queryable")).isNotNull(); assertThat(document.at("rebalancing_enabled")).isNotNull(); assertThat(document.at("key_storage").asString()).isEqualTo("application/unknown"); assertThat(document.at("value_storage").asString()).isEqualTo("application/unknown"); response = join(client.cache("proto").details()); document = Json.read(response.getBody()); assertThat(document.at("key_storage").asString()).isEqualTo("application/x-protostream"); assertThat(document.at("value_storage").asString()).isEqualTo("application/x-protostream"); } public void testCacheQueryable() { // Default config createCache(new ConfigurationBuilder(), "cacheNotQueryable"); Json details = getCacheDetail("cacheNotQueryable"); assertFalse(details.at("queryable").asBoolean()); // Indexed ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable().storage(LOCAL_HEAP); builder.indexing().enable().addIndexedEntity("Entity"); createCache(builder, "cacheIndexed"); details = getCacheDetail("cacheIndexed"); assertTrue(details.at("queryable").asBoolean()); // NonIndexed ConfigurationBuilder proto = new ConfigurationBuilder(); proto.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); createCache(proto, "cacheQueryable"); details = getCacheDetail("cacheQueryable"); assertTrue(details.at("queryable").asBoolean()); } @Test public void testCreateInvalidCache() { String invalidConfig = "<infinispan>\n" + " <cache-container>\n" + " <replicated-cache name=\"books\">\n" + " <encoding media-type=\"application/x-java-object\"/>\n" + " <indexing>\n" + " <indexed-entities>\n" + " <indexed-entity>Dummy</indexed-entity>\n" + " </indexed-entities>\n" + " </indexing>\n" + " </replicated-cache>\n" + " </cache-container>\n" + "</infinispan>"; CompletionStage<RestResponse> response = client.cache("CACHE").createWithConfiguration(RestEntity.create(APPLICATION_XML, invalidConfig)); assertThat(response).isBadRequest().containsReturnedText("Cannot instantiate class 'Dummy'"); response = client.cache("CACHE").exists(); assertThat(response).isOk(); CompletionStage<RestResponse> healthResponse = client.cacheManager("default").health(); assertThat(healthResponse).isOk().containsReturnedText("{\"status\":\"FAILED\",\"cache_name\":\"CACHE\"}"); // The only way to recover from a broken cache is to delete it response = client.cache("CACHE").delete(); assertThat(response).isOk(); response = client.cache("CACHE").exists(); assertThat(response).isNotFound(); invalidConfig = "<distributed-cache>\n" + " <encoding>\n" + " <key media-type=\"application/x-protostream\"/>\n" + " <value media-type=\"application/x-protostream\"/>\n" + " </encoding\n" + "</distributed-cache>\n"; response = client.cache("CACHE").createWithConfiguration(RestEntity.create(APPLICATION_XML, invalidConfig)); assertThat(response).isBadRequest().hasReturnedText("expected > to finish end tag not < from line 2 (position: TEXT seen ...<value media-type=\"application/x-protostream\"/>\\n </encoding\\n<... @6:2) "); response = client.cache("CACHE").exists(); assertThat(response).isNotFound(); invalidConfig = "<distributed-cache>\n" + " <encoding>\n" + " <key media-type=\"application/x-protostream\"/>\n" + " <value media-type=\"application/x-protostrea\"/>\n" + " </encoding>\n" + "</distributed-cache>"; response = client.cache("CACHE").createWithConfiguration(RestEntity.create(APPLICATION_XML, invalidConfig)); assertThat(response).isBadRequest().hasReturnedText("ISPN000492: Cannot find transcoder between 'application/x-java-object' to 'application/x-protostrea'"); response = client.cache("CACHE").delete(); assertThat(response).isOk(); } private RestCacheClient createCache(ConfigurationBuilder builder, String name) { return createCache(cacheConfigToJson(name, builder.build()), name); } private RestCacheClient createCache(RestClient c, String json, String name) { RestEntity jsonEntity = RestEntity.create(APPLICATION_JSON, json); RestCacheClient cache = c.cache(name); CompletionStage<RestResponse> response = cache.createWithConfiguration(jsonEntity); assertThat(response).isOk(); return cache; } private RestCacheClient createCache(String json, String name) { return createCache(client, json, name); } private Json getCacheDetail(String name) { RestResponse response = join(client.cache(name).details()); assertThat(response).isOk(); return Json.read(response.getBody()); } @Test public void testCacheNames() { CompletionStage<RestResponse> response = client.caches(); assertThat(response).isOk(); Json jsonNode = Json.read(join(response).getBody()); Set<String> cacheNames = cacheManagers.get(0).getCacheNames(); int size = jsonNode.asList().size(); assertEquals(cacheNames.size(), size); for (int i = 0; i < size; i++) { assertTrue(cacheNames.contains(jsonNode.at(i).asString())); } } @Test public void testCacheHealth() { String cacheName = "default"; CompletionStage<RestResponse> response = client.cache(cacheName).health(); assertThat(response).isOk().hasReturnedText("HEALTHY"); Cache<?, ?> cache = cacheManagers.get(0).getCache(cacheName); ComponentRegistry cr = TestingUtil.extractComponentRegistry(cache); PartitionHandlingManager phm = cr.getComponent(PartitionHandlingManager.class); PartitionHandlingManager spyPhm = Mockito.spy(phm); Mockito.when(spyPhm.getAvailabilityMode()).thenReturn(AvailabilityMode.DEGRADED_MODE); TestingUtil.replaceComponent(cache, PartitionHandlingManager.class, spyPhm, true); response = client.cache(cacheName).health(); assertThat(response).isOk().hasReturnedText("DEGRADED"); response = client.cache("UnknownCache").health(); assertThat(response).isNotFound(); } @Test public void testFlags() { RestResponse response = insertEntity(1, 1000); assertThat(response).isOk(); assertIndexed(1000); response = insertEntity(2, 1200, SKIP_INDEXING.toString(), SKIP_CACHE_LOAD.toString()); assertThat(response).isOk(); assertNotIndexed(1200); response = insertEntity(3, 1200, "Invalid"); assertThat(response).isBadRequest().containsReturnedText("No enum constant org.infinispan.context.Flag.Invalid"); } @Test public void testValidateCacheQueryable() { registerSchema("simple.proto", "message Simple { required int32 value=1;}"); correctReportNotQueryableCache("jsonCache", new ConfigurationBuilder().encoding().mediaType(APPLICATION_JSON_TYPE).build()); } private void correctReportNotQueryableCache(String name, Configuration configuration) { createAndWriteToCache(name, configuration); RestResponse response = queryCache(name); assertThat(response).isBadRequest(); Json json = Json.read(response.getBody()); assertTrue(json.at("error").at("cause").toString().matches(".*ISPN028015.*")); } private RestResponse queryCache(String name) { return join(client.cache(name).query("FROM Simple")); } private void createAndWriteToCache(String name, Configuration configuration) { String jsonConfig = cacheConfigToJson(name, configuration); RestEntity configEntity = RestEntity.create(APPLICATION_JSON, jsonConfig); CompletionStage<RestResponse> response = client.cache(name).createWithConfiguration(configEntity); assertThat(response).isOk(); RestEntity valueEntity = RestEntity.create(APPLICATION_JSON, "{\"_type\":\"Simple\",\"value\":1}"); response = client.cache(name).post("1", valueEntity); assertThat(response).isOk(); } @Test public void testKeyStreamWithFailure() { String exceptionMessage = "Expected failure"; Cache<?, ?> c = cacheManagers.get(0).getCache("default"); ComponentRegistry ccr = TestingUtil.extractComponentRegistry(c); ClusterPublisherManager<?, ?> cpm = ccr.getClusterPublisherManager().running(); ClusterPublisherManager<?, ?> spyCpm = Mockito.spy(cpm); Mockito.doAnswer(ivk -> { SegmentPublisherSupplier<Object> sps = (SegmentPublisherSupplier<Object>) ivk.callRealMethod(); SegmentPublisherSupplier<Object> spySps = Mockito.spy(sps); Mockito.doAnswer(ignore -> Flowable.error(new RuntimeException(exceptionMessage))) .when(spySps).publisherWithoutSegments(); return spySps; }).when(spyCpm).keyPublisher(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(EMPTY_BIT_SET), Mockito.eq(DeliveryGuarantee.EXACTLY_ONCE), Mockito.eq(1000), Mockito.any()); TestingUtil.replaceComponent(c, ClusterPublisherManager.class, spyCpm, true); if (protocol == HTTP_11) { Exceptions.expectCompletionException(IOException.class, "unexpected end of stream on .*", client.cache("default").keys()); } else { // OkHttp wraps the exception in a StreamResetException. Exceptions.expectCompletionException(StreamResetException.class, "stream was reset: .*", client.cache("default").keys()); } TestingUtil.replaceComponent(c, ClusterPublisherManager.class, cpm, true); } @Test public void testEntryStreamWithFailure() { String exceptionMessage = "Expected failure"; Cache<?, ?> c = cacheManagers.get(0).getCache("default"); ComponentRegistry ccr = TestingUtil.extractComponentRegistry(c); ClusterPublisherManager<?, ?> cpm = ccr.getClusterPublisherManager().running(); ClusterPublisherManager<?, ?> spyCpm = Mockito.spy(cpm); Mockito.doAnswer(ivk -> { SegmentPublisherSupplier<Object> sps = (SegmentPublisherSupplier<Object>) ivk.callRealMethod(); SegmentPublisherSupplier<Object> spySps = Mockito.spy(sps); Mockito.doAnswer(ignore -> Flowable.error(new RuntimeException(exceptionMessage))) .when(spySps).publisherWithoutSegments(); return spySps; }).when(spyCpm).entryPublisher(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(EMPTY_BIT_SET), Mockito.eq(DeliveryGuarantee.EXACTLY_ONCE), Mockito.eq(1000), Mockito.any()); TestingUtil.replaceComponent(c, ClusterPublisherManager.class, spyCpm, true); if (protocol == HTTP_11) { Exceptions.expectCompletionException(IOException.class, "unexpected end of stream on .*", client.cache("default").entries()); } else { // OkHttp wraps the exception in a StreamResetException. Exceptions.expectCompletionException(StreamResetException.class, "stream was reset: .*", client.cache("default").entries()); } TestingUtil.replaceComponent(c, ClusterPublisherManager.class, cpm, true); } @Test public void testMultiByte() { putTextEntryInCache("default", "José", "Uberlândia"); RestResponse response = join(client.cache("default").keys()); String body = response.getBody(); Collection<Json> singleSet = Json.read(body).asJsonList(); assertEquals(1, singleSet.size()); assertTrue(singleSet.contains(Json.factory().string("José"))); response = join(client.cache("default").entries()); body = response.getBody(); singleSet = Json.read(body).asJsonList(); assertEquals(1, singleSet.size()); Json entity = singleSet.stream().findFirst().orElseThrow(); assertTrue(entity.has("key")); assertTrue(entity.has("value")); assertEquals(entity.at("key").asString(), "José"); assertEquals(entity.at("value").asString(), "Uberlândia"); } @Test public void testGetAllKeys() { RestResponse response = join(client.cache("default").keys()); Collection<?> emptyKeys = Json.read(response.getBody()).asJsonList(); assertEquals(0, emptyKeys.size()); putTextEntryInCache("default", "1", "value"); response = join(client.cache("default").keys()); Collection<?> singleSet = Json.read(response.getBody()).asJsonList(); assertEquals(1, singleSet.size()); int entries = 10; for (int i = 0; i < entries; i++) { putTextEntryInCache("default", String.valueOf(i), "value"); } response = join(client.cache("default").keys()); Set<?> keys = Json.read(response.getBody()).asJsonList().stream().map(Json::asInteger).collect(Collectors.toSet()); assertEquals(entries, keys.size()); assertTrue(IntStream.range(0, entries).allMatch(keys::contains)); response = join(client.cache("default").keys(5)); Set<?> keysLimited = Json.read(response.getBody()).asJsonList().stream().map(Json::asInteger).collect(Collectors.toSet()); assertEquals(5, keysLimited.size()); } @Test public void testGetAllKeysWithDifferentType() { String cacheJson = "{ \"distributed-cache\": { \"mode\": \"SYNC\"," + " \"encoding\": {" + " \"key\": {\"media-type\": \"application/json\"}," + " \"value\": {\"media-type\": \"application/xml\"}}}}"; String value = "<?xml version=\"1.0\"?>\n" + "<log category=\"CLUSTER\">\n" + " <content level=\"INFO\" message=\"hello\" detail=\"testing\"/>\n" + " <meta instant=\"42\" context=\"testing\" scope=\"\" who=\"\"/>\n" + "</log>\n"; String cacheName = "xmlCaching"; RestCacheClient cacheClient = client.cache(cacheName); RestEntity jsonEntity = RestEntity.create(APPLICATION_JSON, cacheJson); CompletionStage<RestResponse> r = cacheClient.createWithConfiguration(jsonEntity, VOLATILE); assertThat(r).isOk(); RestResponse response = join(client.cache(cacheName).keys()); Collection<?> emptyKeys = Json.read(response.getBody()).asJsonList(); assertEquals(0, emptyKeys.size()); // Test key with escape. putInCache(cacheName, "{\"text\": \"I'm right \\\\\"here\\\\\".\"}", APPLICATION_JSON_TYPE, value, APPLICATION_XML); response = join(client.cache(cacheName).keys()); Collection<?> singleSet = Json.read(response.getBody()).asJsonList(); assertEquals(1, singleSet.size()); join(client.cache(cacheName).clear()); int entries = 10; for (int i = 0; i < entries; i++) { putInCache(cacheName, String.format("{\"v\": %d}", i), APPLICATION_JSON_TYPE, value, APPLICATION_XML); } response = join(client.cache(cacheName).keys()); List<Json> keys = Json.read(response.getBody()).asJsonList(); assertEquals(entries, keys.size()); response = join(client.cache(cacheName).keys(5)); List<?> keysLimited = Json.read(response.getBody()).asJsonList(); assertEquals(5, keysLimited.size()); } private void putInCache(String cacheName, String key, String keyType, String value, MediaType valueType) { CompletionStage<RestResponse> r = client.cache(cacheName).put(key, keyType, RestEntity.create(valueType, value)); ResponseAssertion.assertThat(r).isOk(); } @Test public void testStreamEntries() { RestResponse response = join(client.cache("default").entries()); Collection<?> emptyEntries = Json.read(response.getBody()).asJsonList(); assertEquals(0, emptyEntries.size()); putTextEntryInCache("default", "key_0", "value_0"); response = join(client.cache("default").entries()); Collection<?> singleSet = Json.read(response.getBody()).asJsonList(); assertEquals(1, singleSet.size()); for (int i = 0; i < 20; i++) { putTextEntryInCache("default", "key_" + i, "value_" + i); } response = join(client.cache("default").entries()); List<Json> jsons = Json.read(response.getBody()).asJsonList(); assertEquals(20, jsons.size()); response = join(client.cache("default").entries(3)); jsons = Json.read(response.getBody()).asJsonList(); assertEquals(3, jsons.size()); Json first = jsons.get(0); String entry = first.toPrettyString(); assertThat(entry).contains("\"key\" : \"key_"); assertThat(entry).contains("\"value\" : \"value_"); assertThat(entry).doesNotContain("timeToLiveSeconds"); assertThat(entry).doesNotContain("maxIdleTimeSeconds"); assertThat(entry).doesNotContain("created"); assertThat(entry).doesNotContain("lastUsed"); assertThat(entry).doesNotContain("expireTime"); } @Test public void testStreamComplexProtobufEntries() { RestResponse response = join(client.cache("indexedCache").entries(-1, false)); Collection<?> emptyEntries = Json.read(response.getBody()).asJsonList(); assertEquals(0, emptyEntries.size()); insertEntity(3, "Another", 3, "Three"); response = join(client.cache("indexedCache").entries(-1, true)); if (response.getStatus() != 200) { Assertions.fail(response.getBody()); } List<Json> jsons = Json.read(response.getBody()).asJsonList(); assertThat(jsons).hasSize(1); response = join(client.cache("indexedCache").keys()); if (response.getStatus() != 200) { Assertions.fail(response.getBody()); } jsons = Json.read(response.getBody()).asJsonList(); assertThat(jsons).hasSize(1); assertThat(jsons).contains(Json.factory().string("3")); } private String asString(Json json) { return json.isObject() ? json.toString() : json.asString(); } private void testStreamEntriesFromCache(String cacheName, MediaType cacheMediaType, MediaType writeMediaType, Map<String, String> data) { // Create the cache with the supplied encoding createCache(cacheName, cacheMediaType); // Write entries with provided data and writeMediaType data.forEach((key, value) -> writeEntry(key, value, cacheName, writeMediaType)); // Get entries RestCacheClient cacheClient = client.cache(cacheName); RestResponse response = join(cacheClient.entries(true)); Map<String, String> entries = entriesAsMap(response); // Obtain the negotiated media type of the entries String contentTypeHeader = response.getHeader(ResponseHeader.VALUE_CONTENT_TYPE_HEADER.getValue()); // Check entries are in the required format assertEquals(data.size(), entries.size()); entries.forEach((key, value) -> assertEquals(value, data.get(key))); // Change an entry using the content type returned from the previous call to getEntries String aKey = data.keySet().iterator().next(); String aValue = data.get(aKey); String changedValue = aValue.replace("value", "value-changed"); writeEntry(aKey, changedValue, cacheName, MediaType.fromString(contentTypeHeader)); // Check changed entry entries = entriesAsMap(join(cacheClient.entries(true))); assertEquals(changedValue, entries.get(aKey)); } public void testStreamFromXMLCache() { Map<String, String> data = new HashMap<>(); data.put("<id>1</id>", "<value>value1</value>"); data.put("<id>2</id>", "<value>value2</value>"); testStreamEntriesFromCache("xml", APPLICATION_XML, APPLICATION_XML, data); } public void testStreamFromTextPlainCache() { Map<String, String> data = new HashMap<>(); data.put("key-1", "value-1"); data.put("key-2", "value-2"); testStreamEntriesFromCache("text", TEXT_PLAIN, TEXT_PLAIN, data); } public void testStreamFromJSONCache() { Map<String, String> data = new HashMap<>(); data.put("1", "{\"value\":1}"); data.put("2", "{\"value\":2}"); testStreamEntriesFromCache("json", APPLICATION_JSON, APPLICATION_JSON, data); } public void testStreamFromDefaultCache() { Map<String, String> data = new HashMap<>(); data.put("0x01", "0x010203"); data.put("0x02", "0x020406"); testStreamEntriesFromCache("noEncoding", null, APPLICATION_OCTET_STREAM.withEncoding("hex"), data); } private void createCache(String cacheName, MediaType mediaType) { RestCacheClient cacheClient = client.cache(cacheName); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); if (mediaType != null) builder.encoding().mediaType(mediaType.toString()); String jsonConfig = cacheConfigToJson(cacheName, builder.build()); RestEntity cacheConfig = RestEntity.create(APPLICATION_JSON, jsonConfig); RestResponse response = join(cacheClient.createWithConfiguration(cacheConfig)); assertThat(response).isOk(); } private void writeEntry(String key, String value, String cacheName, MediaType mediaType) { RestCacheClient cacheClient = client.cache(cacheName); RestResponse response; if (mediaType == null) { response = join(cacheClient.put(key, value)); } else { response = join(cacheClient.put(key, mediaType.toString(), RestEntity.create(mediaType, value))); } assertThat(response).isOk(); } private Map<String, String> entriesAsMap(RestResponse response) { assertThat(response).isOk(); List<Json> entries = Json.read(response.getBody()).asJsonList(); return entries.stream().collect(Collectors.toMap(j -> asString(j.at("key")), j -> asString(j.at("value")))); } @Test public void testStreamEntriesWithMetadata() { RestResponse response = join(client.cache("default").entries(-1, true)); Collection<?> emptyEntries = Json.read(response.getBody()).asJsonList(); assertEquals(0, emptyEntries.size()); putTextEntryInCache("default", "key_0", "value_0"); response = join(client.cache("default").entries(-1, true)); Collection<?> singleSet = Json.read(response.getBody()).asJsonList(); assertEquals(1, singleSet.size()); for (int i = 0; i < 20; i++) { putTextEntryInCache("default", "key_" + i, "value_" + i); } response = join(client.cache("default").entries(-1, true)); List<Json> jsons = Json.read(response.getBody()).asJsonList(); assertEquals(20, jsons.size()); response = join(client.cache("default").entries(3, true)); jsons = Json.read(response.getBody()).asJsonList(); assertEquals(3, jsons.size()); Json first = jsons.get(0); String entry = first.toPrettyString(); assertThat(entry).contains("\"key\" : \"key_"); assertThat(entry).contains("\"value\" : \"value_"); assertThat(entry).contains("\"timeToLiveSeconds\" : -1"); assertThat(entry).contains("\"maxIdleTimeSeconds\" : -1"); assertThat(entry).contains("\"created\" : -1"); assertThat(entry).contains("\"lastUsed\" : -1"); assertThat(entry).contains("\"expireTime\" : -1"); } @Test public void testStreamEntriesWithMetadataAndExpirationTimesConvertedToSeconds() { RestEntity textValue = RestEntity.create(TEXT_PLAIN, "value1"); join(client.cache("default").put("key1", TEXT_PLAIN_TYPE, textValue, 1000, 5000)); RestResponse response = join(client.cache("default").entries(1, true)); List<Json> jsons = Json.read(response.getBody()).asJsonList(); assertEquals(1, jsons.size()); Json first = jsons.get(0); String entry = first.toPrettyString(); assertThat(entry).contains("\"key\" : \"key1"); assertThat(entry).contains("\"value\" : \"value1"); assertThat(entry).contains("\"timeToLiveSeconds\" : 1000"); assertThat(entry).contains("\"maxIdleTimeSeconds\" : 5000"); } @Test public void testProtobufMetadataManipulation() { // Special role {@link ProtobufMetadataManager#SCHEMA_MANAGER_ROLE} is needed for authz. Subject USER has it String cache = PROTOBUF_METADATA_CACHE_NAME; putStringValueInCache(cache, "file1.proto", "message A{}"); putStringValueInCache(cache, "file2.proto", "message B{}"); putStringValueInCache(cache, "sample.proto", PROTO_SCHEMA); RestResponse response = join(client.cache(PROTOBUF_METADATA_CACHE_NAME).keys()); String contentAsString = response.getBody(); Collection<?> keys = Json.read(contentAsString).asJsonList(); assertEquals(3, keys.size()); } @Test public void testVersionMetadata() { Metadata metadata1 = new EmbeddedMetadata.Builder() .version(new NumericVersion(7)).build(); Metadata metadata2 = new EmbeddedMetadata.Builder() .version(new SimpleClusteredVersion(3, 9)).build(); Cache<String, String> embeddedCache = cacheManagers.get(0).getCache("simple-text"); AdvancedCache<String, String> advancedCache = embeddedCache.getAdvancedCache(); advancedCache.put("key-1", "value-1", metadata1); advancedCache.put("key-2", "value-2", metadata2); advancedCache.put("key-3", "value-3"); RestCacheClient cacheClient = client.cache("simple-text"); RestResponse response = join(cacheClient.entries(100, true)); assertThat(response).isOk(); String body = response.getBody(); Assert.assertTrue(body.contains("key-1")); Assert.assertTrue(body.contains("key-2")); Assert.assertTrue(body.contains("key-3")); List<Json> returnedEntries = Json.read(body).asJsonList(); Assert.assertEquals(3, returnedEntries.size()); for (int i = 0; i < 3; i++) { Json entry = returnedEntries.get(0); String key = entry.at("key").asString(); Json version = entry.at("version"); Json topologyId = entry.at("topologyId"); switch (key) { case "key-1": Assert.assertEquals(7L, version.asLong()); assertNull(topologyId); break; case "key-2": Assert.assertEquals(3L, version.asLong()); Assert.assertEquals(7, topologyId.asInteger()); break; case "key-3": assertNull(version); assertNull(topologyId); break; default: fail("unexpected key: " + key); } } } @Test public void testGetProtoCacheConfig() { testGetProtoCacheConfig(APPLICATION_XML_TYPE); testGetProtoCacheConfig(APPLICATION_JSON_TYPE); } @Test public void testRebalancingActions() { String cacheName = "default"; assertRebalancingStatus(cacheName, true); RestCacheClient cacheClient = adminClient.cache(cacheName); RestResponse response = join(cacheClient.disableRebalancing()); ResponseAssertion.assertThat(response).isOk(); assertRebalancingStatus(cacheName, false); response = join(cacheClient.enableRebalancing()); ResponseAssertion.assertThat(response).isOk(); assertRebalancingStatus(cacheName, true); } private void assertRebalancingStatus(String cacheName, boolean enabled) { for (EmbeddedCacheManager cm : cacheManagers) { eventuallyEquals(enabled, () -> { try { return TestingUtil.extractGlobalComponent(cm, LocalTopologyManager.class).isCacheRebalancingEnabled(cacheName); } catch (Exception e) { fail("Unexpected exception", e); return !enabled; } }); } } private void testGetProtoCacheConfig(String accept) { getCacheConfig(accept, PROTOBUF_METADATA_CACHE_NAME); } private String getCacheConfig(String accept, String name) { RestResponse response = join(client.cache(name).configuration(accept)); assertThat(response).isOk(); return response.getBody(); } @Test public void testConversionFromXML() { testConversionFromXML0("distributed-cache"); testConversionFromXML0("distributed-cache-configuration"); } private void testConversionFromXML0(String root) { RestRawClient rawClient = client.raw(); String xml = String.format( "<%s name=\"cacheName\" mode=\"SYNC\" configuration=\"parent\">\n" + " <memory storage=\"OBJECT\" max-count=\"20\"/>\n" + "</%s>", root, root ); CompletionStage<RestResponse> response = rawClient.post("/rest/v2/caches?action=convert", Collections.singletonMap("Accept", APPLICATION_JSON_TYPE), xml, APPLICATION_XML_TYPE); assertThat(response).isOk(); checkJSON(response, "cacheName", root); response = rawClient.post("/rest/v2/caches?action=convert", Collections.singletonMap("Accept", APPLICATION_YAML_TYPE), xml, APPLICATION_XML_TYPE); assertThat(response).isOk(); checkYaml(response, "cacheName", root); } @Test public void testConversionFromJSON() throws Exception { testConversionFromJSON0("distributed-cache"); testConversionFromJSON0("distributed-cache-configuration"); } private void testConversionFromJSON0(String root) throws Exception { RestRawClient rawClient = client.raw(); String json = String.format("{\"%s\":{\"configuration\":\"parent\",\"mode\":\"SYNC\",\"memory\":{\"storage\":\"OBJECT\",\"max-count\":\"20\"}}}", root); CompletionStage<RestResponse> response = rawClient.post("/rest/v2/caches?action=convert", Collections.singletonMap("Accept", APPLICATION_XML_TYPE), json, APPLICATION_JSON_TYPE); assertThat(response).isOk(); checkXML(response, root); response = rawClient.post("/rest/v2/caches?action=convert", Collections.singletonMap("Accept", APPLICATION_YAML_TYPE), json, APPLICATION_JSON_TYPE); assertThat(response).isOk(); checkYaml(response, "", root); } @Test public void testConversionFromYAML() throws Exception { testConversionFromYAML0("distributedCache"); testConversionFromYAML0("distributedCacheConfiguration"); } private void testConversionFromYAML0(String root) throws Exception { RestRawClient rawClient = client.raw(); String yaml = String.format("%s:\n" + " mode: 'SYNC'\n" + " configuration: 'parent'\n" + " memory:\n" + " storage: 'OBJECT'\n" + " maxCount: 20", root); CompletionStage<RestResponse> response = rawClient.post("/rest/v2/caches?action=convert", Collections.singletonMap("Accept", APPLICATION_XML_TYPE), yaml, APPLICATION_YAML_TYPE); assertThat(response).isOk(); checkXML(response, root); response = rawClient.post("/rest/v2/caches?action=convert", Collections.singletonMap("Accept", APPLICATION_JSON_TYPE), yaml, APPLICATION_YAML_TYPE); assertThat(response).isOk(); checkJSON(response, "", root); } @Test public void testBrokenConfiguration() throws IOException { for (String name : Arrays.asList("broken.xml", "broken.yaml", "broken.json")) { CompletionStage<RestResponse> response = createCacheFromResource(name); String body = join(response).getBody(); assertThat(body).contains("ISPN000327: Cannot find a parser for element 'error' in namespace '' at ["); } } private CompletionStage<RestResponse> createCacheFromResource(String name) throws IOException { String cfg; try (InputStream is = CacheResourceV2Test.class.getResourceAsStream("/" + name)) { cfg = Files.readFile(is); } RestEntity entity = RestEntity.create(MediaType.fromExtension(name), cfg); RestCacheClient cache = client.cache(name); return cache.createWithConfiguration(entity); } private void checkJSON(CompletionStage<RestResponse> response, String name, String rootElement) { Json jsonNode = Json.read(join(response).getBody()); if (!name.isBlank()) { jsonNode = jsonNode.at(name); } Json distCache = jsonNode.at(NamingStrategy.KEBAB_CASE.convert(rootElement)); Json memory = distCache.at("memory"); assertEquals("SYNC", distCache.at("mode").asString()); assertEquals("parent", distCache.at("configuration").asString()); assertEquals(20, memory.at("max-count").asInteger()); } private void checkXML(CompletionStage<RestResponse> response, String rootElement) throws Exception { String xml = join(response).getBody(); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))); Element root = doc.getDocumentElement(); assertEquals(NamingStrategy.KEBAB_CASE.convert(rootElement), root.getTagName()); assertEquals("parent", root.getAttribute("configuration")); assertEquals("SYNC", root.getAttribute("mode")); NodeList children = root.getElementsByTagName("memory"); assertEquals(1, children.getLength()); Element memory = (Element) children.item(0); assertEquals("OBJECT", memory.getAttribute("storage")); assertEquals("20", memory.getAttribute("max-count")); } private void checkYaml(CompletionStage<RestResponse> response, String name, String root) { String rootElement = NamingStrategy.CAMEL_CASE.convert(root); try (YamlConfigurationReader yaml = new YamlConfigurationReader(new StringReader(join(response).getBody()), new URLConfigurationResourceResolver(null), new Properties(), PropertyReplacer.DEFAULT, NamingStrategy.KEBAB_CASE)) { Map<String, Object> config = yaml.asMap(); assertEquals("parent", getYamlProperty(config, name, rootElement, "configuration")); assertEquals("SYNC", getYamlProperty(config, name, rootElement, "mode")); assertEquals("OBJECT", getYamlProperty(config, name, rootElement, "memory", "storage")); assertEquals("20", getYamlProperty(config, name, rootElement, "memory", "maxCount")); } } public static <T> T getYamlProperty(Map<String, Object> yaml, String... names) { for (int i = 0; i < names.length - 1; i++) { if (!names[i].isBlank()) { yaml = (Map<String, Object>) yaml.get(names[i]); if (yaml == null) { return null; } } } return (T) yaml.get(names[names.length - 1]); } @Test public void testCacheExists() { assertEquals(404, checkCache("nonexistent")); assertEquals(204, checkCache("invalid")); assertEquals(204, checkCache("default")); assertEquals(204, checkCache("indexedCache")); } @Test public void testCRUDWithProtobufPrimitives() throws Exception { RestCacheClient client = this.client.cache("proto"); MediaType integerType = MediaType.APPLICATION_OBJECT.withClassType(Integer.class); // Insert a pair of Integers RestEntity value = RestEntity.create(integerType, "1"); CompletionStage<RestResponse> response = client.put("1", integerType.toString(), value); assertThat(response).isOk(); // Change the value to another Integer RestEntity anotherValue = RestEntity.create(integerType, "2"); response = client.put("1", integerType.toString(), anotherValue); assertThat(response).isOk(); // Read the changed value as an integer Map<String, String> headers = new HashMap<>(); headers.put(KEY_CONTENT_TYPE_HEADER.getValue(), integerType.toString()); headers.put(ACCEPT_HEADER.getValue(), integerType.toString()); response = client.get("1", headers); assertThat(response).isOk(); assertThat(response).hasReturnedText("2"); // Read the changed value as protobuf headers = new HashMap<>(); headers.put(KEY_CONTENT_TYPE_HEADER.getValue(), integerType.toString()); headers.put(ACCEPT_HEADER.getValue(), MediaType.APPLICATION_PROTOSTREAM_TYPE); response = client.get("1", headers); assertThat(response).isOk(); assertThat(response).hasReturnedBytes(new ProtoStreamMarshaller().objectToByteBuffer(2)); } @Test public void indexMetamodel() { RestCacheClient cacheClient = adminClient.cache("indexedCache"); join(cacheClient.clear()); RestResponse response = join(cacheClient.indexMetamodel()); Json indexMetamodel = Json.read(response.getBody()); List<Json> indexes = indexMetamodel.asJsonList(); assertThat(indexes).hasSize(2); Json entity = indexes.get(0); assertThat(entity.at("entity-name").asString()).isEqualTo("Entity"); assertThat(entity.at("java-class").asString()).isEqualTo("[B"); assertThat(entity.at("index-name").asString()).isEqualTo("Entity"); Map<String, Json> valueFields = entity.at("value-fields").asJsonMap(); assertThat(valueFields).containsKey("value"); Json valueField = valueFields.get("value"); assertThat(valueField.at("multi-valued").asBoolean()).isFalse(); assertThat(valueField.at("multi-valued-in-root").asBoolean()).isFalse(); assertThat(valueField.at("type").asString()).isEqualTo(Integer.class.getName()); assertThat(valueField.at("projection-type").asString()).isEqualTo(Integer.class.getName()); assertThat(valueField.at("argument-type").asString()).isEqualTo(Integer.class.getName()); assertThat(valueField.at("searchable").asBoolean()).isTrue(); assertThat(valueField.at("sortable").asBoolean()).isFalse(); assertThat(valueField.at("projectable").asBoolean()).isFalse(); assertThat(valueField.at("aggregable").asBoolean()).isFalse(); assertThat(valueField.at("analyzer")).isNull(); assertThat(valueField.at("normalizer")).isNull(); Json another = indexes.get(1); assertThat(another.at("entity-name").asString()).isEqualTo("Another"); assertThat(another.at("java-class").asString()).isEqualTo("[B"); assertThat(another.at("index-name").asString()).isEqualTo("Another"); } @Test public void testSearchStatistics() { RestCacheClient cacheClient = adminClient.cache("indexedCache"); join(cacheClient.clear()); // Clear all stats RestResponse response = join(cacheClient.clearSearchStats()); assertThat(response).isOk(); response = join(cacheClient.searchStats()); Json statJson = Json.read(response.getBody()); assertIndexStatsEmpty(statJson.at("index")); assertAllQueryStatsEmpty(statJson.at("query")); // Insert some data insertEntity(1, "Entity", 1, "One"); insertEntity(11, "Entity", 11, "Eleven"); insertEntity(21, "Entity", 21, "Twenty One"); insertEntity(3, "Another", 3, "Three"); insertEntity(33, "Another", 33, "Thirty Three"); response = join(cacheClient.size()); assertThat(response).hasReturnedText("5"); response = join(cacheClient.searchStats()); assertThat(response).isOk(); // All stats should be zero in the absence of query statJson = Json.read(response.getBody()); assertAllQueryStatsEmpty(statJson.at("query")); // Execute some indexed queries String indexedQuery = "FROM Entity WHERE value > 5"; IntStream.range(0, 3).forEach(i -> { RestResponse response1 = join(cacheClient.query(indexedQuery)); assertThat(response1).isOk(); Json queryJson = Json.read(response1.getBody()); assertEquals(2, queryJson.at("hit_count").asInteger()); assertEquals(true, queryJson.at("hit_count_exact").asBoolean()); }); response = join(cacheClient.searchStats()); statJson = Json.read(response.getBody()); // Hybrid and non-indexed queries stats should be empty assertEquals(0, statJson.at("query").at("hybrid").at("count").asLong()); assertEquals(0, statJson.at("query").at("non_indexed").at("count").asLong()); Json queryStats = statJson.at("query"); assertQueryStatEmpty(queryStats.at("hybrid")); assertQueryStatEmpty(queryStats.at("non_indexed")); // Indexed queries should be recorded assertEquals(3, statJson.at("query").at("indexed_local").at("count").asLong()); assertTrue(statJson.at("query").at("indexed_local").at("average").asLong() > 0); assertTrue(statJson.at("query").at("indexed_local").at("max").asLong() > 0); assertEquals(3, statJson.at("query").at("indexed_distributed").at("count").asLong()); assertTrue(statJson.at("query").at("indexed_distributed").at("average").asLong() > 0); assertTrue(statJson.at("query").at("indexed_distributed").at("max").asLong() > 0); // Execute a hybrid query String hybrid = "FROM Entity WHERE value > 5 AND description = 'One'"; response = join(cacheClient.query(hybrid)); Json queryJson = Json.read(response.getBody()); assertEquals(0, queryJson.at("hit_count").asInteger()); assertEquals(true, queryJson.at("hit_count_exact").asBoolean()); response = join(cacheClient.searchStats()); statJson = Json.read(response.getBody()); // Hybrid queries should be recorded assertEquals(1, statJson.at("query").at("hybrid").at("count").asLong()); assertTrue(statJson.at("query").at("hybrid").at("average").asLong() > 0); assertTrue(statJson.at("query").at("hybrid").at("max").asLong() > 0); // Check index stats response = join(cacheClient.searchStats()); statJson = Json.read(response.getBody()); assertEquals(3, statJson.at("index").at("types").at("Entity").at("count").asInteger()); assertEquals(2, statJson.at("index").at("types").at("Another").at("count").asInteger()); assertThat(statJson.at("index").at("types").at("Entity").at("size").asLong()) .isGreaterThan(MIN_NON_EMPTY_INDEX_SIZE); assertThat(statJson.at("index").at("types").at("Another").at("size").asLong()) .isGreaterThan(MIN_NON_EMPTY_INDEX_SIZE); assertFalse(statJson.at("index").at("reindexing").asBoolean()); } @Test public void testIndexDataSyncInvalidSchema() { String notQuiteIndexed = "package schemas;\n" + " /* @Indexed */\n" + " message Entity {\n" + " optional string name=1;\n" + " }"; // Register schema RestResponse restResponse = join(client.schemas().put("schemas.proto", notQuiteIndexed)); assertThat(restResponse).isOk(); // Create the indexed cache ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable().storage(LOCAL_HEAP).addIndexedEntities("schemas.Entity"); String cacheConfig = cacheConfigToJson("sync-data-index", builder.build()); RestCacheClient cacheClient = client.cache("sync-data-index"); RestEntity config = RestEntity.create(APPLICATION_JSON, cacheConfig); CompletionStage<RestResponse> response = cacheClient.createWithConfiguration(config); assertThat(response).isOk(); // Write an entry, it should error String value = Json.object().set("_type", "schemas.Entity").set("name", "Jun").toString(); RestEntity restEntity = RestEntity.create(APPLICATION_JSON, value); restResponse = join(cacheClient.put("key", restEntity)); assertThat(restResponse).containsReturnedText("make sure at least one field has the @Field annotation"); // Cache should not have any data response = cacheClient.size(); assertThat(response).containsReturnedText("0"); } @Test public void testLazySearchMapping() { String proto = " package future;\n" + " /* @Indexed */\n" + " message Entity {\n" + " /* @Field */\n" + " optional string name=1;\n" + " }"; String value = Json.object().set("_type", "future.Entity").set("name", "Kim").toString(); RestEntity restEntity = RestEntity.create(APPLICATION_JSON, value); // Create a cache with a declared, not yet registered protobuf entity ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable().storage(LOCAL_HEAP).addIndexedEntities("future.Entity"); String cacheConfig = cacheConfigToJson("index-lazy", builder.build()); RestCacheClient cacheClient = client.cache("index-lazy"); RestEntity config = RestEntity.create(APPLICATION_JSON, cacheConfig); CompletionStage<RestResponse> response = cacheClient.createWithConfiguration(config); assertThat(response).isOk(); // Queries should return error RestResponse restResponse = join(cacheClient.query("From future.Entity")); assertThat(restResponse).containsReturnedText("Unknown type name : future.Entity"); // Writes too restResponse = join(cacheClient.put("key", restEntity)); assertThat(restResponse).containsReturnedText("Unknown type name : future.Entity"); // Register the protobuf restResponse = join(client.schemas().put("future.proto", proto)); assertThat(restResponse).isOk(); // All operations should work restResponse = join(cacheClient.put("key", restEntity)); assertThat(restResponse).isOk(); restResponse = join(cacheClient.query("From future.Entity")); assertThat(restResponse).isOk(); assertThat(restResponse).containsReturnedText("Kim"); } @Test public void testCacheListener() throws InterruptedException, IOException { SSEListener sseListener = new SSEListener(); Closeable listen = client.raw().listen("/rest/v2/caches/default?action=listen", Collections.singletonMap("Accept", "text/plain"), sseListener); assertTrue(sseListener.openLatch.await(10, TimeUnit.SECONDS)); putTextEntryInCache("default", "AKey", "AValue"); sseListener.expectEvent("cache-entry-created", "AKey"); removeTextEntryFromCache("default", "AKey"); sseListener.expectEvent("cache-entry-removed", "AKey"); listen.close(); } @Test public void testConnectStoreValidation() { RestCacheClient cacheClient = client.cache("default"); assertBadResponse(cacheClient, "true"); assertBadResponse(cacheClient, "2"); assertBadResponse(cacheClient, "[1,2,3]"); assertBadResponse(cacheClient, "\"random text\""); assertBadResponse(cacheClient, "{\"jdbc-store\":{\"shared\":true}}"); assertBadResponse(cacheClient, "{\"jdbc-store\":{\"shared\":true},\"remote-store\":{\"shared\":true}}"); } @Test public void testSourceConnected() { RestCacheClient cacheClient = client.cache("default"); RestResponse restResponse = join(cacheClient.sourceConnected()); ResponseAssertion.assertThat(restResponse).isNotFound(); } @Test public void testCacheAvailability() { RestCacheClient cacheClient = adminClient.cache("denyReadWritesCache"); RestResponse restResponse = join(cacheClient.getAvailability()); ResponseAssertion.assertThat(restResponse).isOk().containsReturnedText("AVAILABLE"); restResponse = join(cacheClient.setAvailability("DEGRADED_MODE")); ResponseAssertion.assertThat(restResponse).isOk(); eventuallyEquals("Availability status not updated!", "DEGRADED_MODE", () -> { RestResponse r = join(cacheClient.getAvailability()); ResponseAssertion.assertThat(r).isOk(); return r.getBody(); }); // Ensure that the endpoints can be utilised with internal caches RestCacheClient adminCacheClient = adminClient.cache(GlobalConfigurationManager.CONFIG_STATE_CACHE_NAME); restResponse = join(adminCacheClient.getAvailability()); ResponseAssertion.assertThat(restResponse).isOk().containsReturnedText("AVAILABLE"); // No-op in core as the cache uses the PreferAvailabilityStategy // Call to ensure that accessing internal cache doesn't throw an exception restResponse = join(adminCacheClient.setAvailability("DEGRADED_MODE")); ResponseAssertion.assertThat(restResponse).isOk(); // The availability will always be AVAILABLE restResponse = join(adminCacheClient.getAvailability()); ResponseAssertion.assertThat(restResponse).isOk().containsReturnedText("AVAILABLE"); } @Test public void testComparison() { RestRawClient rawClient = client.raw(); String xml = "<distributed-cache name=\"cacheName\" mode=\"SYNC\">\n" + "<memory storage=\"OBJECT\" max-count=\"20\"/>\n" + "</distributed-cache>"; String json20 = "{\"distributed-cache\":{\"memory\":{\"storage\":\"OBJECT\",\"max-count\":\"20\"}}}"; String json30 = "{\"distributed-cache\":{\"memory\":{\"storage\":\"OBJECT\",\"max-count\":\"30\"}}}"; String jsonrepl = "{\"replicated-cache\":{\"memory\":{\"storage\":\"OBJECT\",\"max-count\":\"30\"}}}"; Map<String, List<String>> form = new HashMap<>(); form.put("one", Collections.singletonList(xml)); form.put("two", Collections.singletonList(json20)); CompletionStage<RestResponse> response = rawClient.postMultipartForm("/rest/v2/caches?action=compare", Collections.emptyMap(), form); assertThat(response).isOk(); form = new HashMap<>(); form.put("one", Collections.singletonList(xml)); form.put("two", Collections.singletonList(json30)); response = rawClient.postMultipartForm("/rest/v2/caches?action=compare", Collections.emptyMap(), form); assertThat(response).isConflicted(); response = rawClient.postMultipartForm("/rest/v2/caches?action=compare&ignoreMutable=true", Collections.emptyMap(), form); assertThat(response).isOk(); form = new HashMap<>(); form.put("one", Collections.singletonList(xml)); form.put("two", Collections.singletonList(jsonrepl)); response = rawClient.postMultipartForm("/rest/v2/caches?action=compare&ignoreMutable=true", Collections.emptyMap(), form); assertThat(response).isConflicted(); form = new HashMap<>(); form.put("one", Collections.singletonList("{\"local-cache\":{\"statistics\":true,\"encoding\":{\"key\": {\"media-type\":\"text/plain\"} ,\"value\":{\"media-type\":\"text/plain\"}},\"memory\":{\"max-count\":\"50\"}}}")); form.put("two", Collections.singletonList("{\"local-cache\":{\"statistics\":true,\"encoding\":{\"key\":{\"media-type\":\"application/x-protostream\"},\"value\":{\"media-type\":\"application/x-protostream\"}},\"memory\":{\"max-count\":\"50\"}}}")); response = rawClient.postMultipartForm("/rest/v2/caches?action=compare&ignoreMutable=true", Collections.emptyMap(), form); assertThat(response).isConflicted(); assertEquals("ISPN000963: Invalid configuration in 'local-cache'\n" + " ISPN000961: Incompatible attribute 'local-cache.encoding.key.media-type' existing value='text/plain', new value='application/x-protostream'\n" + " ISPN000961: Incompatible attribute 'local-cache.encoding.value.media-type' existing value='text/plain', new value='application/x-protostream'", join(response).getBody()); } private void assertBadResponse(RestCacheClient client, String config) { RestResponse response = join(client.connectSource(RestEntity.create(APPLICATION_JSON, config))); ResponseAssertion.assertThat(response).isBadRequest(); ResponseAssertion.assertThat(response).containsReturnedText("Invalid remote-store JSON description"); } private void assertQueryStatEmpty(Json queryTypeStats) { assertEquals(0, queryTypeStats.at("count").asInteger()); assertEquals(0, queryTypeStats.at("max").asInteger()); assertEquals(0.0, queryTypeStats.at("average").asDouble()); assertNull(queryTypeStats.at("slowest")); } private void assertAllQueryStatsEmpty(Json queryStats) { queryStats.asJsonMap().forEach((name, s) -> assertQueryStatEmpty(s)); } private void assertIndexStatsEmpty(Json indexStats) { indexStats.at("types").asJsonMap().forEach((name, json) -> { assertEquals(0, json.at("count").asInteger()); // TODO Restore this assertion when Infinispan forces a merge after clearing a cache. // Currently the index size remains high after the cache was cleared, // because Infinispan doesn't force a merge. We're left with segments // where all documents have been marked for deletion. // In real-world usage that's no big deal, since Lucene will automatically // trigger a merge some time later, but for tests it means we can't require // that indexes are small *just* after a clear. // assertThat(json.at("size").asLong()).isLessThan(MAX_EMPTY_INDEX_SIZE); assertThat(json.at("size").asLong()).isGreaterThanOrEqualTo(0L); }); } private int checkCache(String name) { CompletionStage<RestResponse> response = client.cache(name).exists(); return join(response).getStatus(); } private void registerSchema(String name, String schema) { CompletionStage<RestResponse> response = client.schemas().put(name, schema); assertThat(response).isOk().hasNoErrors(); } private RestResponse insertEntity(int key, int value, String... flags) { String json = String.format("{\"_type\": \"Entity\",\"value\": %d}", value); RestEntity restEntity = RestEntity.create(APPLICATION_JSON, json); RestCacheClient cacheClient = client.cache("indexedCache"); return join(cacheClient.put(String.valueOf(key), restEntity, flags)); } private void insertEntity(int cacheKey, String type, int intValue, String stringValue) { Json json = Json.object().set("_type", type).set("value", intValue).set("description", stringValue); RestEntity restEntity = RestEntity.create(APPLICATION_JSON, json.toString()); RestCacheClient cacheClient = client.cache("indexedCache"); CompletionStage<RestResponse> response = cacheClient.put(String.valueOf(cacheKey), restEntity); assertThat(response).isOk(); } private void assertIndexed(int value) { assertIndex(value, true); } private void assertNotIndexed(int value) { assertIndex(value, false); } private void assertIndex(int value, boolean present) { String query = "FROM Entity WHERE value = " + value; RestResponse response = join(client.cache("indexedCache").query(query)); assertThat(response).isOk(); assertEquals(present, response.getBody().contains(String.valueOf(value))); } }
85,943
44.329114
253
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/CacheResourceOffHeapTest.java
package org.infinispan.rest.resources; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.CacheResourceOffHeapTest") public class CacheResourceOffHeapTest extends BaseCacheResourceTest { @Override public ConfigurationBuilder getDefaultCacheBuilder() { ConfigurationBuilder configurationBuilder = super.getDefaultCacheBuilder(); configurationBuilder.memory().storageType(StorageType.OFF_HEAP); return configurationBuilder; } @Override public Object[] factory() { return new Object[]{ new CacheResourceOffHeapTest().withSecurity(false).browser(false), new CacheResourceOffHeapTest().withSecurity(false).browser(true), new CacheResourceOffHeapTest().withSecurity(true).browser(false), new CacheResourceOffHeapTest().withSecurity(true).browser(true), }; } }
1,005
34.928571
81
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/TasksResourceTest.java
package org.infinispan.rest.resources; import static java.util.Collections.singletonMap; import static org.infinispan.client.rest.RestTaskClient.ResultType.ALL; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JAVASCRIPT; import static org.infinispan.commons.util.Util.getResourceAsString; import static org.testng.AssertJUnit.assertEquals; import java.util.Collections; import java.util.concurrent.CompletionStage; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.RestTaskClient; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.tasks.DummyTaskEngine; import org.infinispan.tasks.TaskManager; import org.infinispan.tasks.spi.TaskEngine; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; @Test(groups = "functional", testName = "rest.TasksResourceTest") public class TasksResourceTest extends AbstractRestResourceTest { @Override protected void defineCaches(EmbeddedCacheManager cm) { cm.defineConfiguration("default", getDefaultCacheBuilder().build()); GlobalComponentRegistry gcr = cm.getGlobalComponentRegistry(); TaskManager taskManager = gcr.getComponent(TaskManager.class); TaskEngine taskEngine = new DummyTaskEngine(); taskManager.registerTaskEngine(taskEngine); } @AfterClass public void tearDown() { } @Override public Object[] factory() { return new Object[]{ new TasksResourceTest().withSecurity(true).browser(false), new TasksResourceTest().withSecurity(true).browser(true), new TasksResourceTest().withSecurity(false).browser(false), new TasksResourceTest().withSecurity(false).browser(true), }; } @Test public void testTaskList() { RestTaskClient taskClient = adminClient.tasks(); RestResponse response = join(taskClient.list(ALL)); ResponseAssertion.assertThat(response).isOk(); Json jsonNode = Json.read(response.getBody()); assertEquals(DummyTaskEngine.DummyTaskTypes.values().length, jsonNode.asList().size()); Json task = jsonNode.at(0); assertEquals("Dummy", task.at("type").asString()); assertEquals("ONE_NODE", task.at("execution_mode").asString()); assertEquals("DummyRole", task.at("allowed_role").asString()); } @Test public void testTaskExec() { RestTaskClient taskClient = client.tasks(); RestResponse response = join(taskClient.exec("SUCCESSFUL_TASK")); ResponseAssertion.assertThat(response).isOk(); Json jsonNode = Json.read(response.getBody()); assertEquals("result", jsonNode.asString()); } @Test public void testParameterizedTaskExec() { RestTaskClient taskClient = client.tasks(); CompletionStage<RestResponse> response = taskClient.exec("PARAMETERIZED_TASK", singletonMap("parameter", "Hello")); ResponseAssertion.assertThat(response).isOk(); Json jsonNode = Json.read(join(response).getBody()); assertEquals("Hello", jsonNode.asString()); } @Test public void testFailingTaskExec() { RestTaskClient taskClient = client.tasks(); CompletionStage<RestResponse> response = taskClient.exec("FAILING_TASK"); ResponseAssertion.assertThat(response).isError(); } @Test public void testTaskUpload() throws Exception { RestTaskClient taskClient = client.tasks(); String script = getResourceAsString("hello.js", getClass().getClassLoader()); RestEntity scriptEntity = RestEntity.create(APPLICATION_JAVASCRIPT, script); CompletionStage<RestResponse> response = taskClient.uploadScript("hello", scriptEntity); ResponseAssertion.assertThat(response).isOk(); response = taskClient.exec("hello", Collections.singletonMap("greetee", "Friend")); ResponseAssertion.assertThat(response).isOk(); Json jsonNode = Json.read(join(response).getBody()); assertEquals("Hello Friend", jsonNode.asString()); response = taskClient.downloadScript("hello"); ResponseAssertion.assertThat(response).isOk(); assertEquals(script, join(response).getBody()); } @Test public void testCacheTask() { RestTaskClient taskClient = client.tasks(); CompletionStage<RestResponse> response = taskClient.exec("CACHE_TASK", "default", Collections.emptyMap()); ResponseAssertion.assertThat(response).isOk(); Json jsonNode = Json.read(join(response).getBody()); assertEquals("default", jsonNode.asString()); } }
4,749
38.583333
121
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/AbstractRestResourceTest.java
package org.infinispan.rest.resources; import static org.infinispan.client.rest.configuration.Protocol.HTTP_11; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE; import static org.infinispan.rest.RequestHeader.KEY_CONTENT_TYPE_HEADER; import static org.testng.AssertJUnit.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletionStage; import javax.security.auth.Subject; import org.apache.logging.log4j.core.util.StringBuilderWriter; 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.CacheConfigurationException; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.test.security.TestCertificates; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.counter.configuration.AbstractCounterConfiguration; import org.infinispan.counter.configuration.CounterConfigurationSerializer; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.remote.ProtobufMetadataManager; import org.infinispan.rest.RestTestSCI; import org.infinispan.rest.TestClass; import org.infinispan.rest.assertion.ResponseAssertion; import org.infinispan.rest.authentication.impl.BasicAuthenticator; import org.infinispan.rest.helper.RestServerHelper; import org.infinispan.rest.resources.security.SimpleSecurityDomain; import org.infinispan.scripting.ScriptingManager; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.Security; import org.infinispan.security.actions.SecurityActions; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.server.core.DummyServerStateManager; import org.infinispan.server.core.ServerStateManager; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; @Test(groups = "functional") public class AbstractRestResourceTest extends MultipleCacheManagersTest { public static final String REALM = "ApplicationRealm"; public static final Subject ADMIN = TestingUtil.makeSubject("ADMIN", ScriptingManager.SCRIPT_MANAGER_ROLE, ProtobufMetadataManager.SCHEMA_MANAGER_ROLE); public static final Subject USER = TestingUtil.makeSubject("USER", ScriptingManager.SCRIPT_MANAGER_ROLE, ProtobufMetadataManager.SCHEMA_MANAGER_ROLE); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); protected RestClient client; protected RestClient adminClient; protected static final int NUM_SERVERS = 2; private final List<RestServerHelper> restServers = new ArrayList<>(NUM_SERVERS); protected boolean security; protected Protocol protocol = HTTP_11; protected boolean ssl; protected boolean browser; protected ServerStateManager serverStateManager; @Override protected String parameters() { return "[security=" + security + ", protocol=" + protocol.toString() + ", ssl=" + ssl + ", browser=" + browser + "]"; } protected AbstractRestResourceTest withSecurity(boolean security) { this.security = security; return this; } protected AbstractRestResourceTest protocol(Protocol protocol) { this.protocol = protocol; return this; } protected AbstractRestResourceTest ssl(boolean ssl) { this.ssl = ssl; return this; } protected AbstractRestResourceTest browser(boolean browser) { this.browser = browser; return this; } public ConfigurationBuilder getDefaultCacheBuilder() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } protected boolean isSecurityEnabled() { return security; } protected GlobalConfigurationBuilder getGlobalConfigForNode(int id) { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder(); globalBuilder.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); TestCacheManagerFactory.configureJmx(globalBuilder, getClass().getSimpleName() + id, mBeanServerLookup); globalBuilder.cacheContainer().statistics(true); globalBuilder.serialization().addContextInitializer(RestTestSCI.INSTANCE); if (isSecurityEnabled()) addSecurity(globalBuilder); return globalBuilder.clusteredDefault().cacheManagerName("default"); } protected void addSecurity(GlobalConfigurationBuilder globalBuilder) { globalBuilder.security().authorization().enable().groupOnlyMapping(false).principalRoleMapper(new IdentityRoleMapper()) .role("ADMIN").permission(AuthorizationPermission.ALL) .role("USER").permission(AuthorizationPermission.WRITE, AuthorizationPermission.READ, AuthorizationPermission.EXEC, AuthorizationPermission.BULK_READ); } @Override protected void createCacheManagers() throws Exception { Security.doAs(ADMIN, () -> { for (int i = 0; i < NUM_SERVERS; i++) { GlobalConfigurationBuilder configForNode = getGlobalConfigForNode(i); addClusterEnabledCacheManager(new GlobalConfigurationBuilder().read(configForNode.build()), getDefaultCacheBuilder(), TransportFlags.minimalXsiteFlags()); } cacheManagers.forEach(this::defineCaches); cacheManagers.forEach(cm -> cm.defineConfiguration("invalid", getDefaultCacheBuilder().encoding().mediaType(APPLICATION_OBJECT_TYPE).indexing().enabled(true).addIndexedEntities("invalid").build())); serverStateManager = new DummyServerStateManager(); for (EmbeddedCacheManager cm : cacheManagers) { BasicComponentRegistry bcr = SecurityActions.getGlobalComponentRegistry(cm).getComponent(BasicComponentRegistry.class); bcr.registerComponent(ServerStateManager.class, serverStateManager, false); cm.getClassAllowList().addClasses(TestClass.class); waitForClusterToForm(cm.getCacheNames().stream().filter(name -> { try { cm.getCache(name); return true; } catch (CacheConfigurationException ignored) { return false; } }).toArray(String[]::new)); RestServerHelper restServerHelper = new RestServerHelper(cm); configureServer(restServerHelper); restServerHelper.start(TestResourceTracker.getCurrentTestShortName()); restServers.add(restServerHelper); } }); adminClient = RestClient.forConfiguration(getClientConfig("admin", "admin").build()); client = RestClient.forConfiguration(getClientConfig("user", "user").build()); } protected RestServerHelper configureServer(RestServerHelper helper) { if (isSecurityEnabled()) { BasicAuthenticator basicAuthenticator = new BasicAuthenticator(new SimpleSecurityDomain(ADMIN, USER), REALM); helper.withAuthenticator(basicAuthenticator); } if (ssl) { helper.withKeyStore(TestCertificates.certificate("server"), TestCertificates.KEY_PASSWORD, TestCertificates.KEYSTORE_TYPE) .withTrustStore(TestCertificates.certificate("trust"), TestCertificates.KEY_PASSWORD, TestCertificates.KEYSTORE_TYPE); } return helper; } protected RestServerHelper restServer() { return restServers.get(0); } protected void defineCaches(EmbeddedCacheManager cm) { } @AfterClass public void afterClass() { Security.doAs(ADMIN, () -> restServers.forEach(RestServerHelper::stop)); Util.close(client); Util.close(adminClient); } @AfterMethod public void afterMethod() { Security.doAs(ADMIN, () -> restServers.forEach(RestServerHelper::clear)); } private void putInCache(String cacheName, Object key, String keyContentType, String value, String contentType) { String url = String.format("/rest/v2/caches/%s/%s", cacheName, key); Map<String, String> headers = new HashMap<>(); if (keyContentType != null) headers.put(KEY_CONTENT_TYPE_HEADER.getValue(), contentType); CompletionStage<RestResponse> response = client.raw().putValue(url, headers, value, contentType); ResponseAssertion.assertThat(response).isOk(); } void putInCache(String cacheName, Object key, String value, String contentType) { putInCache(cacheName, key, null, value, contentType); } void putStringValueInCache(String cacheName, String key, String value) { putInCache(cacheName, key, value, "text/plain; charset=utf-8"); } void putTextEntryInCache(String cacheName, String key, String value) { putInCache(cacheName, key, TEXT_PLAIN_TYPE, value, TEXT_PLAIN_TYPE); } void putJsonValueInCache(String cacheName, String key, String value) { putInCache(cacheName, key, value, "application/json; charset=utf-8"); } void putBinaryValueInCache(String cacheName, String key, byte[] value, MediaType mediaType) { RestEntity restEntity = RestEntity.create(mediaType, value); CompletionStage<RestResponse> response = client.cache(cacheName).put(key, restEntity); ResponseAssertion.assertThat(response).isOk(); } private void removeFromCache(String cacheName, Object key, String keyContentType) { String url = String.format("/rest/v2/caches/%s/%s", cacheName, key); Map<String, String> headers = new HashMap<>(); if (keyContentType != null) headers.put(KEY_CONTENT_TYPE_HEADER.getValue(), keyContentType); CompletionStage<RestResponse> response = client.raw().delete(url, headers); ResponseAssertion.assertThat(response).isOk(); } void removeTextEntryFromCache(String cacheName, String key) { removeFromCache(cacheName, key, TEXT_PLAIN_TYPE); } protected RestClientConfigurationBuilder getClientConfig(String username, String password) { RestClientConfigurationBuilder clientConfigurationBuilder = new RestClientConfigurationBuilder(); if (protocol != null) { clientConfigurationBuilder.protocol(protocol); } if (ssl) { clientConfigurationBuilder.security().ssl().enable() .hostnameVerifier((hostname, session) -> true) .trustStoreFileName(TestCertificates.certificate("ca")).trustStorePassword(TestCertificates.KEY_PASSWORD).trustStoreType(TestCertificates.KEYSTORE_TYPE) .keyStoreFileName(TestCertificates.certificate("client")).keyStorePassword(TestCertificates.KEY_PASSWORD).keyStoreType(TestCertificates.KEYSTORE_TYPE); } if (isSecurityEnabled()) { clientConfigurationBuilder.security().authentication().enable().username(username).password(password); } if (browser) { clientConfigurationBuilder.header("User-Agent", "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/112.0"); } restServers.forEach(s -> clientConfigurationBuilder.addServer().host(s.getHost()).port(s.getPort())); return clientConfigurationBuilder; } public static String cacheConfigToJson(String name, Configuration configuration) { StringBuilderWriter sw = new StringBuilderWriter(); try (ConfigurationWriter w = ConfigurationWriter.to(sw).withType(APPLICATION_JSON).prettyPrint(false).build()) { new ParserRegistry().serialize(w, name, configuration); } return sw.toString(); } public static String counterConfigToJson(AbstractCounterConfiguration config) { org.infinispan.commons.io.StringBuilderWriter sw = new org.infinispan.commons.io.StringBuilderWriter(); try (ConfigurationWriter w = ConfigurationWriter.to(sw).withType(APPLICATION_JSON).build()) { new CounterConfigurationSerializer().serializeConfiguration(w, config); } return sw.toString(); } protected RestResponse join(CompletionStage<RestResponse> responseStage) { RestResponse response = CompletionStages.join(responseStage); checkBrowserHeaders(response); return response; } protected void checkBrowserHeaders(RestResponse response) { if (browser) { assertEquals("sameorigin", response.getHeader("X-Frame-Options")); assertEquals("1; mode=block", response.getHeader("X-XSS-Protection")); assertEquals("nosniff", response.getHeader("X-Content-Type-Options")); if (ssl) { assertEquals("max-age=31536000 ; includeSubDomains", response.getHeader("Strict-Transport-Security")); } } } }
13,795
45.295302
207
java
null
infinispan-main/server/rest/src/test/java/org/infinispan/rest/resources/security/SimpleSecurityDomain.java
package org.infinispan.rest.resources.security; import java.util.HashMap; import java.util.Map; import javax.security.auth.Subject; import org.infinispan.rest.authentication.SecurityDomain; /** * Security domain that supports a simple map of subjects */ public class SimpleSecurityDomain implements SecurityDomain { private final Map<String, Subject> subjects; public SimpleSecurityDomain(Subject... subjects) { this.subjects = new HashMap<>(subjects.length); for (Subject subject : subjects) { this.subjects.put(subject.getPrincipals().iterator().next().getName().toLowerCase(), subject); } } @Override public Subject authenticate(String username, String password) throws SecurityException { if (username.equals(password)) { return subjects.get(username); } return null; } }
857
25.8125
103
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/package-info.java
/** * REST Server bootstrap and Netty bridge classes. * * @api.public */ package org.infinispan.rest;
106
14.285714
50
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/JSONConstants.java
package org.infinispan.rest; /** * @since 9.2 */ public interface JSONConstants { String TYPE = "_type"; }
113
11.666667
32
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/RestServer.java
package org.infinispan.rest; import static org.infinispan.rest.RestChannelInitializer.MAX_HEADER_SIZE; import static org.infinispan.rest.RestChannelInitializer.MAX_INITIAL_LINE_SIZE; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.infinispan.commons.logging.LogFactory; import org.infinispan.counter.EmbeddedCounterManagerFactory; import org.infinispan.counter.impl.manager.EmbeddedCounterManager; import org.infinispan.rest.cachemanager.RestCacheManager; import org.infinispan.rest.configuration.RestAuthenticationConfiguration; import org.infinispan.rest.configuration.RestServerConfiguration; import org.infinispan.rest.framework.ResourceManager; import org.infinispan.rest.framework.RestDispatcher; import org.infinispan.rest.framework.impl.ResourceManagerImpl; import org.infinispan.rest.framework.impl.RestDispatcherImpl; import org.infinispan.rest.resources.CacheResourceV2; import org.infinispan.rest.resources.ClusterResource; import org.infinispan.rest.resources.ContainerResource; import org.infinispan.rest.resources.CounterResource; import org.infinispan.rest.resources.LoggingResource; import org.infinispan.rest.resources.MetricsResource; import org.infinispan.rest.resources.ProtobufResource; import org.infinispan.rest.resources.RedirectResource; import org.infinispan.rest.resources.SearchAdminResource; import org.infinispan.rest.resources.SecurityResource; import org.infinispan.rest.resources.ServerResource; import org.infinispan.rest.resources.StaticContentResource; import org.infinispan.rest.resources.TasksResource; import org.infinispan.rest.resources.XSiteResource; import org.infinispan.rest.tracing.RestTelemetryService; import org.infinispan.security.actions.SecurityActions; import org.infinispan.server.core.AbstractProtocolServer; import org.infinispan.server.core.logging.Log; import org.infinispan.server.core.telemetry.TelemetryService; import org.infinispan.server.core.transport.NettyInitializers; 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; import io.netty.handler.codec.http.cors.CorsConfig; /** * REST Protocol Server. * * @author Sebastian Łaskawiec */ public class RestServer extends AbstractProtocolServer<RestServerConfiguration> { private static final Log log = LogFactory.getLog(RestServer.class, Log.class); private static final int CROSS_ORIGIN_ALT_PORT = 9000; private RestDispatcher restDispatcher; private RestCacheManager<Object> restCacheManager; private InvocationHelper invocationHelper; private volatile List<CorsConfig> corsRules; private volatile int maxContentLength; public RestServer() { super("REST"); } @Override public ChannelOutboundHandler getEncoder() { return null; } @Override public ChannelInboundHandler getDecoder() { return null; } @Override public ChannelInitializer<Channel> getInitializer() { return new NettyInitializers(getRestChannelInitializer()); } @Override public ChannelMatcher getChannelMatcher() { return channel -> channel.pipeline().get(RestRequestHandler.class) != null; } /** * Returns Netty Channel Initializer for REST. * * @return Netty Channel Initializer for REST. */ public RestChannelInitializer getRestChannelInitializer() { return new RestChannelInitializer(this, transport); } RestDispatcher getRestDispatcher() { return restDispatcher; } public InvocationHelper getInvocationHelper() { return invocationHelper; } @Override public void stop() { if (log.isDebugEnabled()) log.debugf("Stopping server %s listening at %s:%d", getQualifiedName(), configuration.host(), configuration.port()); if (restCacheManager != null) { restCacheManager.stop(); } RestAuthenticationConfiguration auth = configuration.authentication(); if (auth.enabled()) { try { auth.authenticator().close(); } catch (IOException e) { log.trace(e); } } super.stop(); } @Override protected void startInternal() { TelemetryService telemetryService = SecurityActions.getGlobalComponentRegistry(cacheManager) .getComponent(TelemetryService.class); if (telemetryService == null) { telemetryService = new TelemetryService.NoTelemetry(); } RestTelemetryService restTelemetryService = new RestTelemetryService(telemetryService); this.maxContentLength = configuration.maxContentLength() + MAX_INITIAL_LINE_SIZE + MAX_HEADER_SIZE; RestAuthenticationConfiguration auth = configuration.authentication(); if (auth.enabled()) { auth.authenticator().init(this); } super.startInternal(); restCacheManager = new RestCacheManager<>(cacheManager, this::isCacheIgnored); invocationHelper = new InvocationHelper(this, restCacheManager, (EmbeddedCounterManager) EmbeddedCounterManagerFactory.asCounterManager(cacheManager), configuration, server, getExecutor()); String restContext = configuration.contextPath(); String rootContext = "/"; ResourceManager resourceManager = new ResourceManagerImpl(); resourceManager.registerResource(restContext, new CacheResourceV2(invocationHelper, restTelemetryService)); resourceManager.registerResource(restContext, new CounterResource(invocationHelper)); resourceManager.registerResource(restContext, new ContainerResource(invocationHelper)); resourceManager.registerResource(restContext, new XSiteResource(invocationHelper)); resourceManager.registerResource(restContext, new SearchAdminResource(invocationHelper)); resourceManager.registerResource(restContext, new TasksResource(invocationHelper)); resourceManager.registerResource(restContext, new ProtobufResource(invocationHelper, restTelemetryService)); resourceManager.registerResource(rootContext, new MetricsResource(auth.metricsAuth(), invocationHelper)); Path staticResources = configuration.staticResources(); if (staticResources != null) { Path console = configuration.staticResources().resolve("console"); resourceManager.registerResource(rootContext, new StaticContentResource(invocationHelper, staticResources, "static")); resourceManager.registerResource(rootContext, new StaticContentResource(invocationHelper, console, "console", (path, resource) -> { if (!path.contains(".")) return StaticContentResource.DEFAULT_RESOURCE; return path; })); // if the cache name contains '.' we need to retrieve the console and access to the cache detail. See ISPN-14376 resourceManager.registerResource(rootContext, new StaticContentResource(invocationHelper, console, "console/cache/", (path, resource) -> StaticContentResource.DEFAULT_RESOURCE)); resourceManager.registerResource(rootContext, new RedirectResource(invocationHelper, rootContext, rootContext + "console/welcome", true)); } if (adminEndpoint) { resourceManager.registerResource(restContext, new ServerResource(invocationHelper)); resourceManager.registerResource(restContext, new ClusterResource(invocationHelper)); resourceManager.registerResource(restContext, new SecurityResource(invocationHelper, rootContext + "console/", rootContext + "console/forbidden.html")); registerLoggingResource(resourceManager, restContext); } this.restDispatcher = new RestDispatcherImpl(resourceManager, restCacheManager.getAuthorizer()); } private void registerLoggingResource(ResourceManager resourceManager, String restContext) { String includeLoggingResource = System.getProperty("infinispan.server.resource.logging", "true"); if (Boolean.parseBoolean(includeLoggingResource)) { resourceManager.registerResource(restContext, new LoggingResource(invocationHelper)); } } public int maxContentLength() { return maxContentLength; } public List<CorsConfig> getCorsConfigs() { List<CorsConfig> rules = corsRules; if (rules == null) { synchronized (this) { rules = corsRules; if (rules == null) { rules = new ArrayList<>(); rules.addAll(CorsUtil.enableAllForSystemConfig()); rules.addAll(CorsUtil.enableAllForLocalHost(getPort(), CROSS_ORIGIN_ALT_PORT)); rules.addAll(getConfiguration().getCorsRules()); corsRules = rules; } } } return corsRules; } @Override public void installDetector(Channel ch) { // NO-OP } }
8,915
41.255924
187
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/StreamCorrelatorHandler.java
package org.infinispan.rest; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http2.HttpConversionUtil; import io.netty.util.AsciiString; /** * Handler to propagate HTTP/2 StreamId between requests and responses. * * @since 12.0 */ class StreamCorrelatorHandler extends ChannelDuplexHandler { public static final AsciiString STREAM_ID_HEADER = HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(); private Integer streamId; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; streamId = request.headers().getInt(STREAM_ID_HEADER); } ctx.fireChannelRead(msg); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (streamId != null) { response.headers().add(STREAM_ID_HEADER, streamId); } } ctx.write(msg, promise); } }
1,281
30.268293
111
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/LifecycleCallbacks.java
package org.infinispan.rest; import static org.infinispan.marshall.protostream.impl.SerializationContextRegistry.MarshallerType.PERSISTENCE; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.lifecycle.ModuleLifecycle; import org.infinispan.marshall.protostream.impl.SerializationContextRegistry; import org.infinispan.rest.distribution.DataDistributionContextInitializerImpl; /** * Lifecycle callbacks for the REST module. Register the externalizers to serialize the objects in package * {@link org.infinispan.rest.distribution} for querying data distribution. * * @since 14.0 */ @InfinispanModule(name = "server-rest") public class LifecycleCallbacks implements ModuleLifecycle { @Override public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) { SerializationContextRegistry ctxRegistry = gcr.getComponent(SerializationContextRegistry.class); ctxRegistry.addContextInitializer(PERSISTENCE, new DataDistributionContextInitializerImpl()); } }
1,176
42.592593
111
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/CorsHandler.java
/* * Copyright 2013 The Netty Project * * The Netty Project licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.infinispan.rest; import static io.netty.handler.codec.http.HttpMethod.OPTIONS; import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.util.ReferenceCountUtil.release; import static io.netty.util.internal.ObjectUtil.checkNonEmpty; import static io.netty.util.internal.ObjectUtil.checkNotNull; import java.util.Collections; import java.util.List; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.codec.http.cors.CorsConfig; import io.netty.handler.ssl.SslHandler; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; /** * Handles <a href="http://www.w3.org/TR/cors/">Cross Origin Resource Sharing</a> (CORS) requests. * <p> * This handler can be configured using one or more {@link CorsConfig}, please * refer to this class for details about the configuration options available. * * NOTE: This class should be removed after https://github.com/netty/netty/issues/10381 is solved. */ public class CorsHandler extends ChannelDuplexHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(CorsHandler.class); private static final String ANY_ORIGIN = "*"; private static final String NULL_ORIGIN = "null"; private CorsConfig config; private HttpRequest request; private final List<CorsConfig> configList; private boolean isShortCircuit; /** * Creates a new instance with a single {@link CorsConfig}. */ public CorsHandler(final CorsConfig config) { this(Collections.singletonList(checkNotNull(config, "config")), config.isShortCircuit()); } /** * Creates a new instance with the specified config list. If more than one * config matches a certain origin, the first in the List will be used. * * @param configList List of {@link CorsConfig} * @param isShortCircuit Same as {@link CorsConfig#shortCircuit} but applicable to all supplied configs. */ public CorsHandler(final List<CorsConfig> configList, boolean isShortCircuit) { checkNonEmpty(configList, "configList"); this.configList = configList; this.isShortCircuit = isShortCircuit; } @Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof HttpRequest) { request = (HttpRequest) msg; final String origin = request.headers().get(HttpHeaderNames.ORIGIN); config = getForOrigin(origin); if (isPreflightRequest(request)) { handlePreflight(ctx, request); return; } if (isShortCircuit && !allowRequest(ctx, origin)) { forbidden(ctx, request); return; } } ctx.fireChannelRead(msg); } private boolean allowRequest(ChannelHandlerContext ctx, String origin) { if (origin == null) { // Not a CORS Request, allow it to proceed. return true; } if (config != null) { // A rule was matched from the configs, so allow it. return true; } String scheme = "http"; if (ctx.channel().pipeline().get(SslHandler.class) != null || ctx.channel().parent().pipeline().get(SslHandler.class) != null) { scheme = "https"; } String host = scheme + "://" + request.headers().get(HttpHeaderNames.HOST); // If it's the same origin, allow it to proceed. return origin.equals(host); } private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest request) { final HttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), OK, true, true); if (setOrigin(response)) { setAllowMethods(response); setAllowHeaders(response); setAllowCredentials(response); setMaxAge(response); setPreflightHeaders(response); } if (!response.headers().contains(HttpHeaderNames.CONTENT_LENGTH)) { response.headers().set(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO); } release(request); respond(ctx, request, response); } /** * This is a non CORS specification feature which enables the setting of preflight * response headers that might be required by intermediaries. * * @param response the HttpResponse to which the preflight response headers should be added. */ private void setPreflightHeaders(final HttpResponse response) { response.headers().add(config.preflightResponseHeaders()); } private CorsConfig getForOrigin(String requestOrigin) { for (CorsConfig corsConfig : configList) { if (corsConfig.isAnyOriginSupported()) { return corsConfig; } if (corsConfig.origins().contains(requestOrigin)) { return corsConfig; } if (corsConfig.isNullOriginAllowed() || NULL_ORIGIN.equals(requestOrigin)) { return corsConfig; } } return null; } private boolean setOrigin(final HttpResponse response) { final String origin = request.headers().get(HttpHeaderNames.ORIGIN); if (origin != null && config != null) { if (NULL_ORIGIN.equals(origin) && config.isNullOriginAllowed()) { setNullOrigin(response); return true; } if (config.isAnyOriginSupported()) { if (config.isCredentialsAllowed()) { echoRequestOrigin(response); setVaryHeader(response); } else { setAnyOrigin(response); } return true; } if (config.origins().contains(origin)) { setOrigin(response, origin); setVaryHeader(response); return true; } logger.debug("Request origin [{}]] was not among the configured origins [{}]", origin, config.origins()); } return false; } private void echoRequestOrigin(final HttpResponse response) { setOrigin(response, request.headers().get(HttpHeaderNames.ORIGIN)); } private static void setVaryHeader(final HttpResponse response) { response.headers().set(HttpHeaderNames.VARY, HttpHeaderNames.ORIGIN); } private static void setAnyOrigin(final HttpResponse response) { setOrigin(response, ANY_ORIGIN); } private static void setNullOrigin(final HttpResponse response) { setOrigin(response, NULL_ORIGIN); } private static void setOrigin(final HttpResponse response, final String origin) { response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin); } private void setAllowCredentials(final HttpResponse response) { if (config.isCredentialsAllowed() && !response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN).equals(ANY_ORIGIN)) { response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } } private static boolean isPreflightRequest(final HttpRequest request) { final HttpHeaders headers = request.headers(); return OPTIONS.equals(request.method()) && headers.contains(HttpHeaderNames.ORIGIN) && headers.contains(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD); } private void setExposeHeaders(final HttpResponse response) { if (!config.exposedHeaders().isEmpty()) { response.headers().set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, config.exposedHeaders()); } } private void setAllowMethods(final HttpResponse response) { response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, config.allowedRequestMethods()); } private void setAllowHeaders(final HttpResponse response) { response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, config.allowedRequestHeaders()); } private void setMaxAge(final HttpResponse response) { response.headers().set(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE, config.maxAge()); } @Override public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception { if (config != null && config.isCorsSupportEnabled() && msg instanceof HttpResponse) { final HttpResponse response = (HttpResponse) msg; if (setOrigin(response)) { setAllowCredentials(response); setExposeHeaders(response); } } ctx.write(msg, promise); } private static void forbidden(final ChannelHandlerContext ctx, final HttpRequest request) { HttpResponse response = new DefaultFullHttpResponse( request.protocolVersion(), FORBIDDEN, ctx.alloc().buffer(0)); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO); release(request); respond(ctx, request, response); } private static void respond( final ChannelHandlerContext ctx, final HttpRequest request, final HttpResponse response) { final boolean keepAlive = HttpUtil.isKeepAlive(request); HttpUtil.setKeepAlive(response, keepAlive); final ChannelFuture future = ctx.writeAndFlush(response); if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE); } } }
10,542
36.78853
114
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/ByteBufContentSource.java
package org.infinispan.rest; import static java.nio.charset.StandardCharsets.UTF_8; import java.util.Arrays; import org.infinispan.rest.framework.ContentSource; import io.netty.buffer.ByteBuf; public class ByteBufContentSource implements ContentSource { private final ByteBuf byteBuf; ByteBufContentSource(ByteBuf byteBuf) { this.byteBuf = byteBuf; } @Override public String asString() { return byteBuf.toString(UTF_8); } @Override public byte[] rawContent() { if (byteBuf != null) { if (byteBuf.hasArray()) { int offset = byteBuf.arrayOffset(); int size = byteBuf.readableBytes(); byte[] underlyingBytes = byteBuf.array(); if (offset == 0 && underlyingBytes.length == size) { return underlyingBytes; } return Arrays.copyOfRange(underlyingBytes, offset, offset + size); } else { byte[] bufferCopy = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(bufferCopy); return bufferCopy; } } return null; } @Override public int size() { return byteBuf.readableBytes(); } }
1,201
23.530612
78
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/CorsUtil.java
package org.infinispan.rest; import static io.netty.handler.codec.http.HttpMethod.DELETE; import static io.netty.handler.codec.http.HttpMethod.GET; import static io.netty.handler.codec.http.HttpMethod.HEAD; import static io.netty.handler.codec.http.HttpMethod.OPTIONS; import static io.netty.handler.codec.http.HttpMethod.POST; import static io.netty.handler.codec.http.HttpMethod.PUT; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.infinispan.rest.logging.Log; import org.infinispan.util.logging.LogFactory; import io.netty.handler.codec.http.cors.CorsConfig; import io.netty.handler.codec.http.cors.CorsConfigBuilder; /** * @since 11.0 */ class CorsUtil { static final Log LOG = LogFactory.getLog(CorsUtil.class, Log.class); static final String[] SCHEMES = new String[]{"http", "https"}; static final String ENABLE_ALL_FOR_ORIGIN_PROPERTY = "infinispan.server.rest.cors-allow"; private static final List<CorsConfig> SYSTEM_CONFIG = new ArrayList<>(); static { String originProp = System.getProperty(ENABLE_ALL_FOR_ORIGIN_PROPERTY); if (originProp != null) { Arrays.stream(originProp.split(",")) .map(s -> s.replaceAll("\\s", "")) .filter(CorsUtil::isValidOrigin) .map(CorsUtil::enableAll) .forEach(SYSTEM_CONFIG::add); } } static List<CorsConfig> enableAllForSystemConfig() { return SYSTEM_CONFIG; } static List<CorsConfig> enableAllForLocalHost(int... ports) { List<CorsConfig> configs = new ArrayList<>(); for (int port : ports) { for (String scheme : SCHEMES) { String localIpv4 = scheme + "://" + "127.0.0.1" + ":" + port; String localDomain = scheme + "://" + "localhost" + ":" + port; String localIpv6 = scheme + "://" + "[::1]" + ":" + port; configs.add(enableAll(localIpv4)); configs.add(enableAll(localIpv6)); configs.add(enableAll(localDomain)); } } return Collections.unmodifiableList(configs); } private static boolean isValidOrigin(String prop) { try { new URL(prop).toURI(); } catch (URISyntaxException | MalformedURLException e) { LOG.invalidOrigin(prop, ENABLE_ALL_FOR_ORIGIN_PROPERTY); return false; } return true; } /** * @return a {@link CorsConfig} with all permissions for the provided origins. */ private static CorsConfig enableAll(String... origins) { return CorsConfigBuilder.forOrigins(origins) .allowCredentials() .allowedRequestMethods(GET, POST, PUT, DELETE, HEAD, OPTIONS) // Not all browsers support "*" (https://github.com/whatwg/fetch/issues/251) so we need to add each // header individually .allowedRequestHeaders(RequestHeader.toArray()) .exposeHeaders(ResponseHeader.toArray()) .build(); } }
3,112
33.977528
111
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/ServerRestBlockHoundIntegration.java
package org.infinispan.rest; import org.kohsuke.MetaInfServices; import reactor.blockhound.BlockHound; import reactor.blockhound.integration.BlockHoundIntegration; @MetaInfServices public class ServerRestBlockHoundIntegration implements BlockHoundIntegration { @Override public void applyTo(BlockHound.Builder builder) { // ChunkedFile read is blocking - This can be fixed in // https://issues.redhat.com/browse/ISPN-11834 builder.allowBlockingCallsInside(ResponseWriter.CHUNKED_FILE.getClass().getName(), "writeResponse"); } }
558
31.882353
106
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/NettyRestRequest.java
package org.infinispan.rest; import static org.infinispan.rest.RequestHeader.CREATED_HEADER; import static org.infinispan.rest.RequestHeader.FLAGS_HEADER; import static org.infinispan.rest.RequestHeader.KEY_CONTENT_TYPE_HEADER; import static org.infinispan.rest.RequestHeader.LAST_USED_HEADER; import static org.infinispan.rest.RequestHeader.MAX_TIME_IDLE_HEADER; import static org.infinispan.rest.RequestHeader.TTL_SECONDS_HEADER; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.security.auth.Subject; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.context.Flag; import org.infinispan.rest.framework.ContentSource; import org.infinispan.rest.framework.Method; import org.infinispan.rest.framework.RestRequest; import org.infinispan.rest.logging.Log; import org.infinispan.rest.operations.exceptions.InvalidFlagException; import org.infinispan.util.logging.LogFactory; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.QueryStringDecoder; /** * A {@link RestRequest} backed by Netty. * * @since 10.0 */ public class NettyRestRequest implements RestRequest { private final static Log logger = LogFactory.getLog(NettyRestRequest.class, Log.class); private static final MediaType DEFAULT_KEY_CONTENT_TYPE = MediaType.fromString("text/plain; charset=utf-8"); private final FullHttpRequest request; private final Map<String, List<String>> parameters; private final String path; private final ContentSource contentSource; private final String context; private final InetSocketAddress remoteAddress; private String action; private Subject subject; private Map<String, String> variables; private String getPath(String uri) { int lastSeparatorIdx = -1; int paramsSeparatorIdx = -1; for (int i = 0; i < uri.length(); i++) { char c = uri.charAt(i); if (c == '/') lastSeparatorIdx = i; if (c == '?') paramsSeparatorIdx = i; } String baseURI = lastSeparatorIdx == -1 ? uri : uri.substring(0, lastSeparatorIdx); String resourceName = uri.substring(lastSeparatorIdx + 1, paramsSeparatorIdx != -1 ? paramsSeparatorIdx : uri.length()); return baseURI + "/" + resourceName; } NettyRestRequest(FullHttpRequest request, InetSocketAddress remoteAddress) throws IllegalArgumentException { this.request = request; this.remoteAddress = remoteAddress; String uri = request.uri(); QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri); this.parameters = queryStringDecoder.parameters(); this.path = getPath(uri); this.context = getContext(this.path); List<String> action = queryStringDecoder.parameters().get("action"); if (action != null) { this.action = action.iterator().next(); } this.contentSource = new ByteBufContentSource(request.content()); } private String getContext(String path) { if (path == null || path.isEmpty() || !path.startsWith("/") || path.length() == 1) return ""; int endIndex = path.indexOf("/", 1); return path.substring(1, endIndex == -1 ? path.length() : endIndex); } public String getContext() { return context; } @Override public Method method() { return Method.valueOf(request.method().name()); } @Override public String path() { return path; } @Override public String uri() { return request.uri(); } @Override public String header(String name) { return request.headers().get(name); } @Override public List<String> headers(String name) { return request.headers().getAll(name); } @Override public Iterable<String> headersKeys() { return request.headers().entries().stream().map(headerEntry -> headerEntry.getKey()).collect(Collectors.toList()); } @Override public InetSocketAddress getRemoteAddress() { return remoteAddress; } @Override public ContentSource contents() { return contentSource; } @Override public Map<String, List<String>> parameters() { return parameters; } @Override public String getParameter(String name) { if (parameters == null || !parameters.containsKey(name)) return null; List<String> values = parameters.get(name); return values.get(values.size() - 1); } @Override public Map<String, String> variables() { return variables; } @Override public String getAction() { return action; } @Override public MediaType contentType() { String contentTypeHeader = getContentTypeHeader(); if (contentTypeHeader == null) return MediaType.MATCH_ALL; return MediaType.fromString(contentTypeHeader); } @Override public MediaType keyContentType() { String header = request.headers().get(KEY_CONTENT_TYPE_HEADER.getValue()); if (header == null) return DEFAULT_KEY_CONTENT_TYPE; return MediaType.fromString(header); } @Override public String getAcceptHeader() { String accept = request.headers().get(HttpHeaderNames.ACCEPT); return accept == null ? MediaType.MATCH_ALL_TYPE : accept; } @Override public String getAuthorizationHeader() { return request.headers().get(HttpHeaderNames.AUTHORIZATION); } @Override public String getCacheControlHeader() { String value = request.headers().get(HttpHeaderNames.CACHE_CONTROL); if (value == null) return ""; return value; } @Override public String getContentTypeHeader() { return request.headers().get(HttpHeaderNames.CONTENT_TYPE); } @Override public String getEtagIfMatchHeader() { return request.headers().get(HttpHeaderNames.IF_MATCH); } @Override public String getIfModifiedSinceHeader() { return request.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE); } @Override public String getEtagIfNoneMatchHeader() { return request.headers().get(HttpHeaderNames.IF_NONE_MATCH); } @Override public String getIfUnmodifiedSinceHeader() { return request.headers().get(HttpHeaderNames.IF_UNMODIFIED_SINCE); } @Override public Long getMaxIdleTimeSecondsHeader() { return getHeaderAsLong(MAX_TIME_IDLE_HEADER.getValue()); } @Override public Long getTimeToLiveSecondsHeader() { return getHeaderAsLong(TTL_SECONDS_HEADER.getValue()); } @Override public EnumSet<CacheContainerAdmin.AdminFlag> getAdminFlags() { String requestFlags = request.headers().get(FLAGS_HEADER.getValue()); if (requestFlags == null || requestFlags.isEmpty()) return null; try { return CacheContainerAdmin.AdminFlag.fromString(requestFlags); } catch (IllegalArgumentException e) { throw new InvalidFlagException(e); } } @Override public Flag[] getFlags() { try { String flags = request.headers().get(FLAGS_HEADER.getValue()); if (flags == null || flags.isEmpty()) { return null; } return Arrays.stream(flags.split(",")).filter(s -> !s.isEmpty()).map(Flag::valueOf).toArray(Flag[]::new); } catch (IllegalArgumentException e) { throw new InvalidFlagException(e); } } @Override public Long getCreatedHeader() { return getHeaderAsLong(CREATED_HEADER.getValue()); } @Override public Long getLastUsedHeader() { return getHeaderAsLong(LAST_USED_HEADER.getValue()); } public Subject getSubject() { return subject; } public void setSubject(Subject subject) { this.subject = subject; } @Override public void setVariables(Map<String, String> variables) { this.variables = variables; } @Override public void setAction(String action) { this.action = action; } private boolean getHeaderAsBoolean(String header) { String headerValue = request.headers().get(header); if (header == null) return false; return Boolean.parseBoolean(headerValue); } private Long getHeaderAsLong(String header) { String headerValue = request.headers().get(header); if (headerValue == null) return null; try { return Long.valueOf(headerValue); } catch (NumberFormatException e) { logger.warnInvalidNumber(header, headerValue); return null; } } public FullHttpRequest getFullHttpRequest() { return request; } @Override public String toString() { return "NettyRestRequest{" + request.method().name() + " " + request.uri() + ", remote=" + remoteAddress + ", subject=" + subject + '}'; } }
8,970
28.316993
126
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/RestRequestHandler.java
package org.infinispan.rest; import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE; import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; import static io.netty.handler.codec.http.HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import static org.infinispan.commons.util.Util.unwrapExceptionMessage; import java.lang.reflect.InvocationTargetException; import java.net.InetSocketAddress; import java.util.NoSuchElementException; import java.util.Objects; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import javax.security.auth.Subject; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.CacheListenerException; import org.infinispan.commons.dataconversion.EncodingException; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.remoting.RemoteException; import org.infinispan.rest.authentication.RestAuthenticator; import org.infinispan.rest.configuration.RestServerConfiguration; import org.infinispan.rest.framework.Invocation; import org.infinispan.rest.framework.LookupResult; import org.infinispan.rest.framework.Method; import org.infinispan.rest.logging.Log; import org.infinispan.rest.logging.RestAccessLoggingHandler; import org.infinispan.server.core.transport.ConnectionMetadata; import org.infinispan.topology.MissingMembersException; import org.infinispan.util.logging.LogFactory; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.unix.Errors; import io.netty.handler.codec.TooLongFrameException; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpUtil; /** * Netty handler for REST requests. * * @author Sebastian Łaskawiec */ public class RestRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> { protected final static Log logger = LogFactory.getLog(RestRequestHandler.class, Log.class); private final RestAccessLoggingHandler restAccessLoggingHandler = new RestAccessLoggingHandler(); protected final RestServer restServer; protected final RestServerConfiguration configuration; private Subject subject; private String authorization; private final RestAuthenticator authenticator; /** * Creates new {@link RestRequestHandler}. * * @param restServer Rest Server. */ RestRequestHandler(RestServer restServer) { super(false); this.restServer = restServer; this.configuration = restServer.getConfiguration(); this.authenticator = configuration.authentication().enabled() ? configuration.authentication().authenticator() : null; } void handleError(ChannelHandlerContext ctx, FullHttpRequest request, Throwable throwable) { Throwable cause = filterCause(throwable); NettyRestResponse.Builder errorResponse = restServer.getInvocationHelper().newResponse(request); if (cause instanceof RestResponseException) { RestResponseException responseException = (RestResponseException) throwable; if (getLogger().isTraceEnabled()) getLogger().tracef("Request failed: %s", responseException); errorResponse.status(responseException.getStatus()).entity(responseException.getText()); } else if (cause instanceof SecurityException) { if (getLogger().isTraceEnabled()) getLogger().tracef("Request failed: %s", cause); errorResponse.status(FORBIDDEN).entity(unwrapExceptionMessage(cause)); } else if (cause instanceof NoSuchElementException) { if (getLogger().isTraceEnabled()) getLogger().tracef("Request failed: %s", cause); errorResponse.status(NOT_FOUND).entity(unwrapExceptionMessage(cause)); } else if (cause instanceof CacheConfigurationException || cause instanceof IllegalArgumentException || cause instanceof EncodingException || cause instanceof Json.MalformedJsonException || cause instanceof MissingMembersException) { if (getLogger().isTraceEnabled()) getLogger().tracef("Request failed: %s", cause); errorResponse.status(BAD_REQUEST).entity(unwrapExceptionMessage(cause)); } else { getLogger().errorWhileResponding(throwable); errorResponse.status(INTERNAL_SERVER_ERROR).entity(unwrapExceptionMessage(cause)); } sendResponse(ctx, request, errorResponse.build()); } public static Throwable filterCause(Throwable re) { if (re == null) return null; Class<? extends Throwable> tClass = re.getClass(); Throwable cause = re.getCause(); if (cause != null && (tClass == ExecutionException.class || tClass == CompletionException.class || tClass == InvocationTargetException.class || tClass == RemoteException.class || tClass == RuntimeException.class || tClass == CacheListenerException.class)) return filterCause(cause); else return re; } void sendResponse(ChannelHandlerContext ctx, FullHttpRequest request, NettyRestResponse response) { ctx.executor().execute(() -> ResponseWriter.forContent(response.getEntity()).writeResponse(ctx, request, response)); } @Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) { if (logger.isTraceEnabled()) { logger.trace(HttpMessageUtil.dumpRequest(request)); } restAccessLoggingHandler.preLog(request); if (HttpUtil.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } if (!Method.contains(request.method().name())) { NettyRestResponse restResponse = new NettyRestResponse.Builder().status(FORBIDDEN).build(); sendResponse(ctx, request, restResponse); return; } ConnectionMetadata metadata = ConnectionMetadata.getInstance(ctx.channel()); metadata.protocolVersion(request.protocolVersion().text()); String userAgent = request.headers().get(HttpHeaderNames.USER_AGENT); if (userAgent != null) { metadata.clientLibraryName(userAgent); } NettyRestRequest restRequest; LookupResult invocationLookup; try { restRequest = new NettyRestRequest(request, (InetSocketAddress) ctx.channel().remoteAddress()); invocationLookup = restServer.getRestDispatcher().lookupInvocation(restRequest); Invocation invocation = invocationLookup.getInvocation(); if (invocation != null && invocation.deprecated()) { logger.warnDeprecatedCall(restRequest.toString()); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Error during REST dispatch", e); } NettyRestResponse restResponse = new NettyRestResponse.Builder().status(BAD_REQUEST).build(); sendResponse(ctx, request, restResponse); return; } if (authenticator == null || isAnon(invocationLookup)) { handleRestRequest(ctx, restRequest, invocationLookup); return; } if (subject != null) { // Ensure that the authorization header, if needed, has not changed String authz = request.headers().get(HttpHeaderNames.AUTHORIZATION); if (Objects.equals(authz, authorization)) { if (logger.isTraceEnabled()) { logger.tracef("Authorization header match, skipping authentication for %s", request); } restRequest.setSubject(subject); handleRestRequest(ctx, restRequest, invocationLookup); return; } else { // Invalidate and force re-authentication if (logger.isTraceEnabled()) { logger.tracef("Authorization header mismatch:\n%s\n%s", authz, authorization); } subject = null; authorization = null; } } authenticator.challenge(restRequest, ctx).whenComplete((authResponse, authThrowable) -> { boolean hasError = authThrowable != null; boolean authorized = !hasError && authResponse.getStatus() < BAD_REQUEST.code(); if (authorized) { authorization = restRequest.getAuthorizationHeader(); subject = restRequest.getSubject(); metadata.subject(subject); handleRestRequest(ctx, restRequest, invocationLookup); } else { try { if (hasError) { handleError(ctx, request, authThrowable); } else { sendResponse(ctx, request, ((NettyRestResponse) authResponse)); } } finally { request.release(); } } }); } private boolean isAnon(LookupResult lookupResult) { if (lookupResult == null || lookupResult.getInvocation() == null) return true; return lookupResult.getInvocation().anonymous(); } private void handleRestRequest(ChannelHandlerContext ctx, NettyRestRequest restRequest, LookupResult invocationLookup) { restServer.getRestDispatcher().dispatch(restRequest, invocationLookup).whenComplete((restResponse, throwable) -> { FullHttpRequest request = restRequest.getFullHttpRequest(); try { if (throwable == null) { NettyRestResponse nettyRestResponse = (NettyRestResponse) restResponse; sendResponse(ctx, request, nettyRestResponse); } else { handleError(ctx, request, throwable); } } finally { request.release(); } }); } protected Log getLogger() { return logger; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { // handle the case of to big requests. if (e.getCause() instanceof TooLongFrameException) { DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, REQUEST_ENTITY_TOO_LARGE); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else if (e instanceof Errors.NativeIoException) { // Native IO exceptions happen on HAProxy disconnect. It sends RST instead of FIN, which cases // a Netty IO Exception. The only solution is to ignore it, just like Tomcat does. logger.debugf(e, "Native IO Exception from %s", ctx.channel().remoteAddress()); ctx.close(); } else if (!ctx.channel().isActive() && e instanceof IllegalStateException && e.getMessage().equals("ssl is null")) { // Workaround for ISPN-12558 -- OpenSSLEngine shut itself down too soon // Ignore the exception, trying to close the context will cause a StackOverflowError } else { logger.uncaughtExceptionInThePipeline(e); ctx.close(); } } }
11,283
45.436214
261
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/ALPNHandler.java
package org.infinispan.rest; import static org.infinispan.rest.RestChannelInitializer.MAX_HEADER_SIZE; import static org.infinispan.rest.RestChannelInitializer.MAX_INITIAL_LINE_SIZE; import java.util.Collections; import java.util.Map; import org.infinispan.rest.configuration.RestServerConfiguration; import org.infinispan.server.core.ProtocolServer; import org.infinispan.server.core.transport.AccessControlFilter; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http.HttpContentCompressor; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpServerKeepAliveHandler; import io.netty.handler.codec.http.HttpServerUpgradeHandler; import io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodecFactory; import io.netty.handler.codec.http2.CleartextHttp2ServerUpgradeHandler; import io.netty.handler.codec.http2.Http2CodecUtil; import io.netty.handler.codec.http2.Http2MultiplexCodec; import io.netty.handler.codec.http2.Http2MultiplexCodecBuilder; import io.netty.handler.codec.http2.Http2ServerUpgradeCodec; import io.netty.handler.codec.http2.Http2Settings; import io.netty.handler.codec.http2.Http2StreamFrameToHttpObjectCodec; import io.netty.handler.ssl.ApplicationProtocolNames; import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.util.AsciiString; /** * Handler responsible for TLS/ALPN negotiation. * * @author Sebastian Łaskawiec */ public class ALPNHandler extends ApplicationProtocolNegotiationHandler { protected final RestServer restServer; public ALPNHandler(RestServer restServer) { super(ApplicationProtocolNames.HTTP_1_1); this.restServer = restServer; } @Override public void configurePipeline(ChannelHandlerContext ctx, String protocol) { configurePipeline(ctx.pipeline(), protocol, restServer, Collections.emptyMap()); } public static void configurePipeline(ChannelPipeline pipeline, String protocol, RestServer restServer, Map<String, ProtocolServer<?>> upgradeServers) { if (ApplicationProtocolNames.HTTP_2.equals(protocol) || ApplicationProtocolNames.HTTP_1_1.equals(protocol)) { configureHttpPipeline(pipeline, restServer); return; } ProtocolServer<?> protocolServer = upgradeServers.get(protocol); if (protocolServer != null) { pipeline.addLast(protocolServer.getInitializer()); return; } throw new IllegalStateException("unknown protocol: " + protocol); } /** * Configure the handlers that should be used for both HTTP 1.1 and HTTP 2.0 */ private static void addCommonHandlers(ChannelPipeline pipeline, RestServer restServer) { // Handles IP filtering for the HTTP connector RestServerConfiguration restServerConfiguration = restServer.getConfiguration(); pipeline.addLast(new AccessControlFilter<>(restServerConfiguration, false)); // Handles http content encoding (gzip) pipeline.addLast(new HttpContentCompressor(restServerConfiguration.getCompressionLevel())); // Handles chunked data pipeline.addLast(new HttpObjectAggregator(restServer.maxContentLength())); // Handles Http/2 headers propagation from request to response pipeline.addLast(new StreamCorrelatorHandler()); // Handles CORS pipeline.addLast(new CorsHandler(restServer.getCorsConfigs(), true)); // Handles Keep-alive pipeline.addLast(new HttpServerKeepAliveHandler()); // Handles the writing of ChunkedInputs pipeline.addLast(new ChunkedWriteHandler()); // Handles REST request pipeline.addLast(new RestRequestHandler(restServer)); } private static void configureHttpPipeline(ChannelPipeline pipeline, RestServer restServer) { //TODO [ISPN-12082]: Rework pipeline removing deprecated codecs Http2MultiplexCodec multiplexCodec = Http2MultiplexCodecBuilder.forServer(new ChannelInitializer<>() { @Override protected void initChannel(Channel channel) { // Creates the HTTP/2 pipeline, where each stream is handled by a sub-channel. ChannelPipeline p = channel.pipeline(); p.addLast(new Http2StreamFrameToHttpObjectCodec(true)); addCommonHandlers(p, restServer); } }).initialSettings(Http2Settings.defaultSettings()).build(); UpgradeCodecFactory upgradeCodecFactory = protocol -> { if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { return new Http2ServerUpgradeCodec(multiplexCodec); } else { return null; } }; // handler for clear-text upgrades HttpServerCodec httpCodec = new HttpServerCodec(MAX_INITIAL_LINE_SIZE, MAX_HEADER_SIZE, restServer.maxContentLength()); HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(httpCodec, upgradeCodecFactory, restServer.maxContentLength()); CleartextHttp2ServerUpgradeHandler cleartextHttp2ServerUpgradeHandler = new CleartextHttp2ServerUpgradeHandler(httpCodec, upgradeHandler, multiplexCodec); pipeline.addLast(cleartextHttp2ServerUpgradeHandler); addCommonHandlers(pipeline, restServer); } }
5,463
44.533333
160
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/ResponseWriter.java
package org.infinispan.rest; import static io.netty.handler.codec.http.HttpHeaderNames.CACHE_CONTROL; import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE; import static io.netty.handler.codec.http.HttpHeaderValues.NO_CACHE; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import org.infinispan.rest.logging.Log; import org.infinispan.rest.logging.RestAccessLoggingHandler; import org.infinispan.rest.stream.CacheChunkedStream; import org.infinispan.util.logging.LogFactory; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpChunkedInput; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.stream.ChunkedFile; /** * @since 10.0 */ public enum ResponseWriter { EMPTY { @Override void writeResponse(ChannelHandlerContext ctx, FullHttpRequest request, NettyRestResponse response) { HttpResponse res = response.getResponse(); HttpUtil.setContentLength(res, 0); log(ctx, request, res); ctx.writeAndFlush(response.getResponse()); } }, FULL { @Override void writeResponse(ChannelHandlerContext ctx, FullHttpRequest request, NettyRestResponse response) { HttpResponse res = response.getResponse(); ByteBuf responseContent = ((FullHttpResponse) res).content(); Object entity = response.getEntity(); if (entity instanceof byte[]) { responseContent.writeBytes((byte[]) entity); } else if (entity instanceof ByteArrayOutputStream) { responseContent.writeBytes(((ByteArrayOutputStream)entity).toByteArray()); } else { ByteBufUtil.writeUtf8(responseContent, entity.toString()); } HttpUtil.setContentLength(res, responseContent.readableBytes()); log(ctx, request, res); ctx.writeAndFlush(res); } }, CHUNKED_FILE { @Override void writeResponse(ChannelHandlerContext ctx, FullHttpRequest request, NettyRestResponse response) { try { // The file is closed by the ChunkedWriteHandler RandomAccessFile randomAccessFile = new RandomAccessFile((File) response.getEntity(), "r"); HttpResponse res = response.getResponse(); HttpUtil.setContentLength(res, randomAccessFile.length()); log(ctx, request, res); response.getResponse().headers().add(ResponseHeader.TRANSFER_ENCODING.getValue(), "chunked"); ctx.write(res); ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(randomAccessFile, 0, randomAccessFile.length(), 8192)), ctx.newProgressivePromise()); } catch (IOException e) { throw new RestResponseException(e); } } }, CHUNKED_STREAM { @Override void writeResponse(ChannelHandlerContext ctx, FullHttpRequest request, NettyRestResponse response) { HttpResponse res = response.getResponse(); res.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); res.headers().set(CONNECTION, KEEP_ALIVE); log(ctx, request, res); ctx.write(res); CacheChunkedStream<?> chunked = (CacheChunkedStream<?>) response.getEntity(); chunked.subscribe(ctx); } }, EVENT_STREAM { @Override void writeResponse(ChannelHandlerContext ctx, FullHttpRequest request, NettyRestResponse response) { HttpResponse res = response.getResponse(); res.headers().set(CACHE_CONTROL, NO_CACHE); res.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); res.headers().set(CONNECTION, KEEP_ALIVE); log(ctx, request, res); ctx.writeAndFlush(res).addListener(v -> { EventStream eventStream = (EventStream) response.getEntity(); eventStream.setChannelHandlerContext(ctx); }); } }; void log(ChannelHandlerContext ctx, FullHttpRequest req, HttpResponse rsp) { accessLog.log(ctx, req, rsp); if (logger.isTraceEnabled()) { logger.trace(HttpMessageUtil.dumpResponse(rsp)); } } final static Log logger = LogFactory.getLog(ResponseWriter.class, Log.class); final RestAccessLoggingHandler accessLog = new RestAccessLoggingHandler(); abstract void writeResponse(ChannelHandlerContext ctx, FullHttpRequest request, NettyRestResponse response); static ResponseWriter forContent(Object content) { if (content == null) return EMPTY; if (content instanceof File) return CHUNKED_FILE; if (content instanceof CacheChunkedStream) return CHUNKED_STREAM; if (content instanceof EventStream) return EVENT_STREAM; return FULL; } }
5,187
40.174603
152
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/EventStream.java
package org.infinispan.rest; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.function.Consumer; import org.infinispan.commons.util.concurrent.CompletableFutures; import io.netty.channel.ChannelHandlerContext; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 13.0 **/ public class EventStream implements Closeable { private final Consumer<EventStream> onOpen; private final Runnable onClose; private ChannelHandlerContext ctx; public EventStream(Consumer<EventStream> onOpen, Runnable onClose) { this.onOpen = onOpen; this.onClose = onClose; } public CompletionStage<Void> sendEvent(ServerSentEvent e) { if (ctx != null) { CompletableFuture<Void> cf = new CompletableFuture<>(); ctx.writeAndFlush(e).addListener(v -> cf.complete(null)); return cf; } else { return CompletableFutures.completedNull(); } } @Override public void close() throws IOException { if (onClose != null) { onClose.run(); } } public void setChannelHandlerContext(ChannelHandlerContext ctx) { this.ctx = ctx; ctx.channel().closeFuture().addListener(f -> this.close()); if (onOpen != null) { onOpen.accept(this); } } }
1,390
25.75
71
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/RestResponseException.java
package org.infinispan.rest; import org.infinispan.commons.util.Util; import io.netty.handler.codec.http.HttpResponseStatus; /** * An exception representing non-critical HTTP processing errors which will be translated * into {@link org.infinispan.rest.framework.RestResponse} and sent back to the client. * * <p> * {@link RestRequestHandler} and {@link RestRequestHandler} are responsible for catching subtypes of this * exception and translate them into proper Netty responses. * </p> */ public class RestResponseException extends RuntimeException { private final HttpResponseStatus status; private final String text; /** * Creates new {@link RestResponseException}. * * @param status Status code returned to the client. * @param text Text returned to the client. */ public RestResponseException(HttpResponseStatus status, String text) { this.status = status; this.text = text; } /** * Creates a new {@link RestResponseException}. * * @param status Status code returned to the client. * @param text Text returned to the client. * @param t Throwable instance. */ public RestResponseException(HttpResponseStatus status, String text, Throwable t) { super(t); this.status = status; this.text = text; } /** * Creates a new {@link RestResponseException} whose status is 500. * * @param t Throwable instance. */ public RestResponseException(Throwable t) { this(HttpResponseStatus.INTERNAL_SERVER_ERROR, Util.getRootCause(t)); } /** * Creates a new {@link RestResponseException}. * * @param status Status code returned to the client. * @param t Throwable instance. */ public RestResponseException(HttpResponseStatus status, Throwable t) { this(status, t.getMessage(), t); } public HttpResponseStatus getStatus() { return status; } public String getText() { return text; } }
1,979
26.5
109
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/DateUtils.java
package org.infinispan.rest; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.TemporalAccessor; import org.infinispan.rest.operations.exceptions.WrongDateFormatException; /** * @since 10.0 */ public final class DateUtils { private DateUtils() { } public static boolean ifUnmodifiedIsBeforeModificationDate(String ifUnmodifiedSince, Long lastMod) { if (ifUnmodifiedSince != null && lastMod != null) { try { Instant instant = Instant.ofEpochSecond(lastMod / 1000); ZonedDateTime clientTime = ZonedDateTime.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(ifUnmodifiedSince)); ZonedDateTime modificationTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()); return modificationTime.isAfter(clientTime); } catch (DateTimeParseException e) { throw new WrongDateFormatException("Could not parse date " + ifUnmodifiedSince); } } return false; } public static ZonedDateTime parseRFC1123(String str) { if (str == null) return null; try { TemporalAccessor temporalAccessor = DateTimeFormatter.RFC_1123_DATE_TIME.parse(str); return ZonedDateTime.from(temporalAccessor); } catch (DateTimeParseException ex) { return null; } } public static String toRFC1123(long epoch) { try { ZonedDateTime zonedDateTime = Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()); return DateTimeFormatter.RFC_1123_DATE_TIME.format(zonedDateTime); } catch (DateTimeParseException ex) { return null; } } public static boolean isNotModifiedSince(String rfc1123Since, Long lasModificationDate) throws WrongDateFormatException { if (rfc1123Since == null || lasModificationDate == null) return false; try { Instant instant = Instant.ofEpochSecond(lasModificationDate / 1000); ZonedDateTime lastMod = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()); ZonedDateTime since = ZonedDateTime.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(rfc1123Since)); return lastMod.isBefore(since) || lastMod.isEqual(since); } catch (DateTimeParseException e) { throw new WrongDateFormatException("Could not parse date " + lasModificationDate); } } }
2,481
37.184615
124
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/ResponseHeader.java
package org.infinispan.rest; import java.util.Arrays; /** * @since 11.0 */ public enum ResponseHeader { CACHE_CONTROL_HEADER("Cache-Control"), CLUSTER_PRIMARY_OWNER_HEADER("Cluster-Primary-Owner"), CLUSTER_BACKUP_OWNERS_HEADER("Cluster-Backup-Owners"), CLUSTER_NODE_NAME_HEADER("Cluster-Node-Name"), CLUSTER_SERVER_ADDRESS_HEADER("Cluster-Server-Address"), CONTENT_LENGTH_HEADER("Content-Length"), CONTENT_TYPE_HEADER("Content-Type"), CREATED_HEADER("created"), DATE_HEADER("Date"), ETAG_HEADER("Etag"), EXPIRES_HEADER("Expires"), KEY_CONTENT_TYPE_HEADER("key-content-type"), LAST_MODIFIED_HEADER("Last-Modified"), LAST_USED_HEADER("lastUsed"), LOCATION("location"), MAX_IDLE_TIME_HEADER("maxIdleTimeSeconds"), TIME_TO_LIVE_HEADER("timeToLiveSeconds"), TRANSFER_ENCODING("Transfer-Encoding"), VALUE_CONTENT_TYPE_HEADER("value-content-type"), WWW_AUTHENTICATE_HEADER("WWW-Authenticate"); private static final CharSequence[] ALL_VALUES = Arrays.stream(values()).map(ResponseHeader::getValue).toArray(String[]::new); private final String value; ResponseHeader(String value) { this.value = value; } public String getValue() { return value; } public static CharSequence[] toArray() { return ALL_VALUES; } }
1,313
27.565217
129
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/NettyRestResponse.java
package org.infinispan.rest; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import static org.infinispan.rest.ResponseHeader.CLUSTER_BACKUP_OWNERS_HEADER; import static org.infinispan.rest.ResponseHeader.CLUSTER_NODE_NAME_HEADER; import static org.infinispan.rest.ResponseHeader.CLUSTER_PRIMARY_OWNER_HEADER; import static org.infinispan.rest.ResponseHeader.CLUSTER_SERVER_ADDRESS_HEADER; import static org.infinispan.rest.ResponseHeader.CONTENT_LENGTH_HEADER; import static org.infinispan.rest.ResponseHeader.CONTENT_TYPE_HEADER; import static org.infinispan.rest.ResponseHeader.CREATED_HEADER; import static org.infinispan.rest.ResponseHeader.DATE_HEADER; import static org.infinispan.rest.ResponseHeader.ETAG_HEADER; import static org.infinispan.rest.ResponseHeader.EXPIRES_HEADER; import static org.infinispan.rest.ResponseHeader.LAST_MODIFIED_HEADER; import static org.infinispan.rest.ResponseHeader.LAST_USED_HEADER; import static org.infinispan.rest.ResponseHeader.LOCATION; import static org.infinispan.rest.ResponseHeader.MAX_IDLE_TIME_HEADER; import static org.infinispan.rest.ResponseHeader.TIME_TO_LIVE_HEADER; import static org.infinispan.rest.ResponseHeader.WWW_AUTHENTICATE_HEADER; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.rest.framework.RestResponse; import org.infinispan.rest.framework.impl.RestResponseBuilder; import org.infinispan.rest.stream.CacheChunkedStream; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.stream.ChunkedInput; /** * A {@link RestResponse} backed by Netty. * * @since 10.0 */ public class NettyRestResponse implements RestResponse { private final HttpResponse response; private final Object entity; private NettyRestResponse(HttpResponse response, Object entity) { this.response = response; this.entity = entity; } public HttpResponse getResponse() { return response; } @Override public int getStatus() { return response.status().code(); } @Override public Object getEntity() { return entity; } public static class Builder implements RestResponseBuilder<Builder> { private Map<String, List<String>> headers = new HashMap<>(); private Object entity; private HttpResponseStatus httpStatus = OK; public Builder() {} @Override public NettyRestResponse build() { HttpResponse response; if (entity instanceof File || entity instanceof ChunkedInput || entity instanceof EventStream || entity instanceof CacheChunkedStream) { response = new DefaultHttpResponse(HTTP_1_1, OK); } else { response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.buffer()); } response.setStatus(httpStatus); headers.forEach((name, values) -> response.headers().set(name, values)); return new NettyRestResponse(response, entity); } @Override public Builder header(String name, Object value) { setHeader(name, value); return this; } public Builder status(HttpResponseStatus httpStatus) { this.httpStatus = httpStatus; return this; } @Override public Builder status(int status) { this.httpStatus = HttpResponseStatus.valueOf(status); return this; } @Override public Builder entity(Object entity) { this.entity = entity; return this; } @Override public Builder eTag(String tag) { setHeader(ETAG_HEADER.getValue(), tag); return this; } @Override public int getStatus() { return httpStatus.code(); } @Override public Object getEntity() { return entity; } @Override public Builder contentType(MediaType mediaType) { if (mediaType != null) { contentType(mediaType.toString()); } return this; } @Override public Builder contentType(String mediaType) { setHeader(CONTENT_TYPE_HEADER.getValue(), mediaType); return this; } @Override public Builder contentLength(long length) { setLongHeader(CONTENT_LENGTH_HEADER.getValue(), length); return this; } @Override public Builder expires(Date expires) { if (expires != null) { setDateHeader(EXPIRES_HEADER.getValue(), expires.getTime()); } return this; } public Builder authenticate(String authentication) { if (authentication != null) { setHeader(WWW_AUTHENTICATE_HEADER.getValue(), authentication); } return this; } @Override public Builder lastModified(Long epoch) { setDateHeader(LAST_MODIFIED_HEADER.getValue(), epoch); return this; } @Override public Builder location(String location) { setHeader(LOCATION.getValue(), location); return this; } @Override public Builder addProcessedDate(Date d) { if (d != null) { setDateHeader(DATE_HEADER.getValue(), d.getTime()); } return this; } @Override public Builder cacheControl(CacheControl cacheControl) { if (cacheControl != null) { setHeader(ResponseHeader.CACHE_CONTROL_HEADER.getValue(), cacheControl.toString()); } return this; } @Override public Object getHeader(String header) { return headers.get(header); } public Builder timeToLive(long timeToLive) { if (timeToLive > -1) setLongHeader(TIME_TO_LIVE_HEADER.getValue(), TimeUnit.MILLISECONDS.toSeconds(timeToLive)); return this; } public Builder maxIdle(long maxIdle) { if (maxIdle > -1) setLongHeader(MAX_IDLE_TIME_HEADER.getValue(), TimeUnit.MILLISECONDS.toSeconds(maxIdle)); return this; } public Builder created(long created) { if (created > -1) setHeader(CREATED_HEADER.getValue(), String.valueOf(created)); return this; } public Builder lastUsed(long lastUsed) { if (lastUsed > -1) setHeader(LAST_USED_HEADER.getValue(), String.valueOf(lastUsed)); return this; } public Builder clusterPrimaryOwner(String primaryOwner) { setHeader(CLUSTER_PRIMARY_OWNER_HEADER.getValue(), primaryOwner); return this; } public Builder clusterBackupOwners(String primaryOwner) { setHeader(CLUSTER_BACKUP_OWNERS_HEADER.getValue(), primaryOwner); return this; } public Builder clusterNodeName(String nodeName) { setHeader(CLUSTER_NODE_NAME_HEADER.getValue(), nodeName); return this; } public Builder clusterServerAddress(String serverAddress) { setHeader(CLUSTER_SERVER_ADDRESS_HEADER.getValue(), serverAddress); return this; } public HttpResponseStatus getHttpStatus() { return httpStatus; } private void setHeader(String name, Object value) { if (value != null) { headers.computeIfAbsent(name, a -> new ArrayList<>()).add(value.toString()); } } private void setLongHeader(String name, long value) { headers.computeIfAbsent(name, a -> new ArrayList<>()).add(String.valueOf(value)); } private void setDateHeader(String name, Long epoch) { if (epoch != null) { String value = DateUtils.toRFC1123(epoch); setHeader(name, value); } } } }
8,148
30.103053
105
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/RequestHeader.java
package org.infinispan.rest; import java.util.Arrays; /** * @since 11.0 */ public enum RequestHeader { ACCEPT_HEADER("Accept"), AUTHORIZATION("Authorization"), CACHE_CONTROL_HEADER("Cache-Control"), CONTENT_ENCODING_HEADER("Content-encoding"), CONTENT_TYPE_HEADER("Content-Type"), CREATED_HEADER("created"), EXTENDED_HEADER("extended"), FLAGS_HEADER("flags"), IF_MODIFIED_SINCE("If-Modified-Since"), IF_NONE_MATCH("If-None-Match"), IF_UNMODIFIED_SINCE("If-UnModified-Since"), KEY_CONTENT_TYPE_HEADER("key-content-type"), LAST_USED_HEADER("lastUsed"), MAX_TIME_IDLE_HEADER("maxIdleTimeSeconds"), TTL_SECONDS_HEADER("timeToLiveSeconds"), USER_AGENT("User-Agent"); private static final CharSequence[] ALL_VALUES = Arrays.stream(values()).map(RequestHeader::getValue).toArray(String[]::new); private final String value; RequestHeader(String value) { this.value = value; } public String getValue() { return value; } public static CharSequence[] toArray() { return ALL_VALUES; } }
1,075
24.023256
128
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/CacheControl.java
package org.infinispan.rest; /** * A helper class for controlling Cache Control headers. * * @author Sebastian Łaskawiec */ public class CacheControl { private static final String NO_CACHE_HEADER_VALUE = "no-cache"; private static final String MAX_AGE_HEADER_VALUE = "max-age"; private static final CacheControl NO_CACHE = new CacheControl(NO_CACHE_HEADER_VALUE); private final String cacheControl; private CacheControl(String cacheControl) { this.cacheControl = cacheControl; } /** * Returns <code>no-cache</code> header value. * * @return <code>no-cache</code> header value. */ public static CacheControl noCache() { return NO_CACHE; } /** * Returns <code>max-age</code> header value. * * @param timeInSeconds Header value in seconds. * @return <code>max-age</code> header value. */ public static CacheControl maxAge(int timeInSeconds) { return new CacheControl(MAX_AGE_HEADER_VALUE + "=" + timeInSeconds); } @Override public String toString() { return cacheControl; } }
1,090
23.244444
88
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/ServerSentEvent.java
package org.infinispan.rest; import java.nio.charset.StandardCharsets; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.DecoderResult; import io.netty.handler.codec.http.HttpContent; public class ServerSentEvent implements HttpContent { private static final byte[] EVENT = "event: ".getBytes(); private static final byte[] NL = "\n".getBytes(); private static final byte[] DATA = "data: ".getBytes(); private final String event; private final String data; private DecoderResult decoderResult; public ServerSentEvent(String event, String data) { this.event = event; this.data = data; } @Override public String toString() { return "ServerSentEvent{" + ", event='" + event + '\'' + ", data='" + data + '\'' + '}'; } @Override public HttpContent copy() { return this; } @Override public HttpContent duplicate() { return this; } @Override public HttpContent retainedDuplicate() { return this; } @Override public HttpContent replace(ByteBuf content) { return this; } @Override public HttpContent retain() { return this; } @Override public HttpContent retain(int increment) { return this; } @Override public HttpContent touch() { return this; } @Override public HttpContent touch(Object hint) { return this; } @Override public ByteBuf content() { ByteBuf b = Unpooled.buffer(); if (event != null) { b.writeBytes(EVENT); b.writeBytes(event.getBytes(StandardCharsets.UTF_8)); b.writeBytes(NL); } for (String line : data.split("\n")) { b.writeBytes(DATA); b.writeBytes(line.getBytes(StandardCharsets.UTF_8)); b.writeBytes(NL); } b.writeBytes(NL); return b; } @Override public DecoderResult getDecoderResult() { return decoderResult(); } @Override public DecoderResult decoderResult() { return decoderResult; } @Override public void setDecoderResult(DecoderResult result) { this.decoderResult = result; } @Override public int refCnt() { return 1; } @Override public boolean release() { return false; } @Override public boolean release(int i) { return false; } }
2,420
19.344538
62
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/InvocationHelper.java
package org.infinispan.rest; import java.util.concurrent.Executor; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.counter.impl.manager.EmbeddedCounterManager; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.marshall.core.EncoderRegistry; import org.infinispan.metrics.impl.MetricsCollector; import org.infinispan.query.remote.ProtobufMetadataManager; import org.infinispan.rest.cachemanager.RestCacheManager; import org.infinispan.rest.configuration.RestServerConfiguration; import org.infinispan.rest.framework.RestRequest; import org.infinispan.rest.operations.exceptions.ServiceUnavailableException; import org.infinispan.server.core.ServerManagement; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; /** * @since 10.0 */ public class InvocationHelper { private final ParserRegistry parserRegistry = new ParserRegistry(); private final RestCacheManager<Object> restCacheManager; private final EmbeddedCounterManager counterManager; private final RestServerConfiguration configuration; private final ServerManagement server; private final Executor executor; private final RestServer protocolServer; private final EncoderRegistry encoderRegistry; private final MetricsCollector metricsCollector; private final ProtobufMetadataManager protobufMetadataManager; InvocationHelper(RestServer protocolServer, RestCacheManager<Object> restCacheManager, EmbeddedCounterManager counterManager, RestServerConfiguration configuration, ServerManagement server, Executor executor) { this.protocolServer = protocolServer; this.restCacheManager = restCacheManager; this.counterManager = counterManager; this.configuration = configuration; this.server = server; this.executor = executor; GlobalComponentRegistry globalComponentRegistry = restCacheManager.getInstance().getGlobalComponentRegistry(); this.encoderRegistry = globalComponentRegistry.getComponent(EncoderRegistry.class); this.metricsCollector = globalComponentRegistry.getComponent(MetricsCollector.class); this.protobufMetadataManager = globalComponentRegistry.getComponent(ProtobufMetadataManager.class); } public ParserRegistry getParserRegistry() { return parserRegistry; } public RestCacheManager<Object> getRestCacheManager() { checkServerStatus(); return restCacheManager; } public RestServerConfiguration getConfiguration() { return configuration; } public Executor getExecutor() { return executor; } public ServerManagement getServer() { return server; } public EmbeddedCounterManager getCounterManager() { checkServerStatus(); return counterManager; } public String getContext() { return configuration.contextPath(); } public RestServer getProtocolServer() { return protocolServer; } public EncoderRegistry getEncoderRegistry() { return encoderRegistry; } public MetricsCollector getMetricsCollector() { return metricsCollector; } public ProtobufMetadataManager protobufMetadataManager() { return protobufMetadataManager; } private void checkServerStatus() { ComponentStatus status = server.getStatus(); switch (status) { case STOPPING: case TERMINATED: throw new ServiceUnavailableException("Unable to process REST request when Server is " + status); } } public NettyRestResponse.Builder newResponse(FullHttpRequest request) { return newResponse(request.headers().get(RequestHeader.USER_AGENT.getValue()), request.uri()); } public NettyRestResponse.Builder newResponse(RestRequest request) { return newResponse(request.header(RequestHeader.USER_AGENT.getValue()), request.uri()); } private NettyRestResponse.Builder newResponse(String userAgent, String uri) { NettyRestResponse.Builder builder = new NettyRestResponse.Builder(); // All browser's user agents start with "Mozilla" if (userAgent != null && userAgent.startsWith("Mozilla")) { builder.header("X-Frame-Options", "sameorigin").header("X-XSS-Protection", "1; mode=block"). header("X-Content-Type-Options", "nosniff"). header("Content-Security-Policy", "script-src 'self'"); // Only if we are using HTTPS if (configuration.ssl().enabled() || uri.startsWith("https")) { builder.header("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains"); } } return builder; } public NettyRestResponse newResponse(RestRequest request, HttpResponseStatus status) { return newResponse(request, status, null); } public NettyRestResponse newResponse(RestRequest request, HttpResponseStatus status, Object entity) { return newResponse(request) .status(status) .entity(entity) .build(); } public NettyRestResponse noContentResponse(RestRequest request) { return newResponse(request, HttpResponseStatus.NO_CONTENT); } public NettyRestResponse notFoundResponse(RestRequest request) { return newResponse(request, HttpResponseStatus.NOT_FOUND); } }
5,392
34.953333
128
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/RestChannelInitializer.java
package org.infinispan.rest; import java.util.Collections; import org.infinispan.rest.configuration.RestServerConfiguration; import org.infinispan.server.core.transport.NettyChannelInitializer; import org.infinispan.server.core.transport.NettyTransport; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.handler.ssl.ApplicationProtocolConfig; import io.netty.handler.ssl.ApplicationProtocolNames; /** * Creates Netty Channels for this server. * * <p> * With ALPN support, this class acts only as a bridge between Server Core and ALPN Handler which bootstraps * pipeline handlers * </p> * * @author Sebastian Łaskawiec */ public class RestChannelInitializer extends NettyChannelInitializer<RestServerConfiguration> { static final int MAX_INITIAL_LINE_SIZE = 4096; static final int MAX_HEADER_SIZE = 8192; private final RestServer restServer; /** * Creates new {@link RestChannelInitializer}. * * @param restServer Rest Server this initializer belongs to. * @param transport Netty transport. */ public RestChannelInitializer(RestServer restServer, NettyTransport transport) { super(restServer, transport, null, null); this.restServer = restServer; } @Override public void initializeChannel(Channel ch) throws Exception { super.initializeChannel(ch); if (server.getConfiguration().ssl().enabled()) { ch.pipeline().addLast(new ALPNHandler(restServer)); } else { ALPNHandler.configurePipeline(ch.pipeline(), ApplicationProtocolNames.HTTP_1_1, restServer, Collections.emptyMap()); } } @Override protected ApplicationProtocolConfig getAlpnConfiguration() { if (restServer.getConfiguration().ssl().enabled()) { 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, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1); } return null; } public ChannelHandler getRestHandler() { return new RestRequestHandler(restServer); } }
2,469
33.788732
125
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/HttpMessageUtil.java
package org.infinispan.rest; import java.util.Map; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.util.internal.StringUtil; /** * @author Ryan Emerson * @since 14.0 */ final class HttpMessageUtil { static String dumpRequest(HttpRequest req) { StringBuilder sb = new StringBuilder(); sb.append(req.method()).append(' ').append(req.uri()).append(' ').append(req.protocolVersion()); appendHeaders(sb, req.headers()); return sb.toString(); } static String dumpResponse(HttpResponse res) { StringBuilder sb = new StringBuilder(); sb.append(res.protocolVersion()).append(' ').append(res.status()); appendHeaders(sb, res.headers()); return sb.toString(); } private static void appendHeaders(StringBuilder buf, HttpHeaders headers) { for (Map.Entry<String, String> header : headers) { buf.append(StringUtil.NEWLINE); buf.append(header.getKey()); buf.append(": "); buf.append(header.getValue()); } } private HttpMessageUtil() { } }
1,166
27.463415
102
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/configuration/package-info.java
/** * REST Server Configuration API * * @api.public */ package org.infinispan.rest.configuration;
102
13.714286
42
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/configuration/CorsRuleConfigurationBuilder.java
package org.infinispan.rest.configuration; import java.util.Arrays; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.cors.CorsConfig; import io.netty.handler.codec.http.cors.CorsConfigBuilder; /** * @since 10.0 */ public class CorsRuleConfigurationBuilder implements Builder<CorsRuleConfiguration> { private static final String[] ALLOW_ALL_ORIGINS = {"*"}; private final AttributeSet attributes; private final Attribute<String> name; private final Attribute<Long> maxAge; private final Attribute<Boolean> allowCredentials; private final Attribute<String[]> allowedHeaders; private final Attribute<String[]> allowedOrigins; private final Attribute<String[]> allowedMethods; private final Attribute<String[]> exposeHeaders; CorsRuleConfigurationBuilder() { this.attributes = CorsRuleConfiguration.attributeDefinitionSet(); name = attributes.attribute(CorsRuleConfiguration.NAME); maxAge = attributes.attribute(CorsRuleConfiguration.MAX_AGE); allowCredentials = attributes.attribute(CorsRuleConfiguration.ALLOW_CREDENTIALS); allowedHeaders = attributes.attribute(CorsRuleConfiguration.ALLOW_HEADERS); allowedOrigins = attributes.attribute(CorsRuleConfiguration.ALLOW_ORIGINS); allowedMethods = attributes.attribute(CorsRuleConfiguration.ALLOW_METHODS); exposeHeaders = attributes.attribute(CorsRuleConfiguration.EXPOSE_HEADERS); } @Override public AttributeSet attributes() { return attributes; } public CorsRuleConfigurationBuilder name(String value) { name.set(value); return this; } public CorsRuleConfigurationBuilder allowCredentials(boolean allow) { allowCredentials.set(allow); return this; } public CorsRuleConfigurationBuilder maxAge(long value) { maxAge.set(value); return this; } public CorsRuleConfigurationBuilder allowOrigins(String[] values) { allowedOrigins.set(values); return this; } public CorsRuleConfigurationBuilder allowMethods(String[] values) { allowedMethods.set(values); return this; } public CorsRuleConfigurationBuilder allowHeaders(String[] values) { allowedHeaders.set(values); return this; } public CorsRuleConfigurationBuilder exposeHeaders(String[] values) { exposeHeaders.set(values); return this; } @Override public CorsRuleConfiguration create() { CorsConfig corsConfig = createCors(); return new CorsRuleConfiguration(attributes.protect(), corsConfig); } private CorsConfig createCors() { boolean isAllowAll = Arrays.equals(allowedOrigins.get(), ALLOW_ALL_ORIGINS); CorsConfigBuilder builder = CorsConfigBuilder.forAnyOrigin(); if (allowedOrigins.isModified() && !isAllowAll) { builder = CorsConfigBuilder.forOrigins(allowedOrigins.get()); } if (allowCredentials.isModified() && allowCredentials.get() != null) { if (allowCredentials.get()) builder.allowCredentials(); } if (maxAge.isModified()) { builder.maxAge(maxAge.get()); } if (allowedHeaders.isModified()) { builder.allowedRequestHeaders(allowedHeaders.get()); } if (allowedMethods.isModified()) { HttpMethod[] methods = Arrays.stream(allowedMethods.get()).map(HttpMethod::valueOf).toArray(HttpMethod[]::new); builder.allowedRequestMethods(methods); } if (exposeHeaders.isModified()) { builder.exposeHeaders(exposeHeaders.get()); } return builder.build(); } @Override public CorsRuleConfigurationBuilder read(CorsRuleConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); return this; } }
4,041
31.596774
120
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/configuration/RestServerConfiguration.java
package org.infinispan.rest.configuration; import java.nio.file.Path; import java.util.List; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.ConfigurationFor; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.rest.RestServer; import org.infinispan.server.core.configuration.EncryptionConfiguration; import org.infinispan.server.core.configuration.IpFilterConfiguration; import org.infinispan.server.core.configuration.ProtocolServerConfiguration; import org.infinispan.server.core.configuration.SslConfiguration; import io.netty.handler.codec.http.cors.CorsConfig; @BuiltBy(RestServerConfigurationBuilder.class) @ConfigurationFor(RestServer.class) public class RestServerConfiguration extends ProtocolServerConfiguration<RestServerConfiguration, RestAuthenticationConfiguration> { public static final AttributeDefinition<ExtendedHeaders> EXTENDED_HEADERS = AttributeDefinition.builder("extended-headers", ExtendedHeaders.ON_DEMAND).immutable().build(); public static final AttributeDefinition<String> CONTEXT_PATH = AttributeDefinition.builder("context-path", "rest").immutable().build(); public static final AttributeDefinition<Integer> MAX_CONTENT_LENGTH = AttributeDefinition.builder("max-content-length", 10 * 1024 * 1024).immutable().build(); public static final AttributeDefinition<Integer> COMPRESSION_LEVEL = AttributeDefinition.builder("compression-level", 6).immutable().build(); private final Attribute<ExtendedHeaders> extendedHeaders; private final Attribute<String> contextPath; private final Attribute<Integer> maxContentLength; private final Attribute<Integer> compressionLevel; private final Path staticResources; public static AttributeSet attributeDefinitionSet() { return new AttributeSet(RestServerConfiguration.class, ProtocolServerConfiguration.attributeDefinitionSet(), EXTENDED_HEADERS, CONTEXT_PATH, MAX_CONTENT_LENGTH, COMPRESSION_LEVEL); } private final CorsConfiguration cors; private final EncryptionConfiguration encryption; RestServerConfiguration(AttributeSet attributes, SslConfiguration ssl, Path staticResources, RestAuthenticationConfiguration authentication, CorsConfiguration cors, EncryptionConfiguration encryption, IpFilterConfiguration ipRules) { super("rest-connector", attributes, authentication, ssl, ipRules); this.staticResources = staticResources; this.extendedHeaders = attributes.attribute(EXTENDED_HEADERS); this.contextPath = attributes.attribute(CONTEXT_PATH); this.maxContentLength = attributes.attribute(MAX_CONTENT_LENGTH); this.cors = cors; this.compressionLevel = attributes.attribute(COMPRESSION_LEVEL); this.encryption = encryption; } @Override public RestAuthenticationConfiguration authentication() { return authentication; } public EncryptionConfiguration encryption() { return encryption; } public ExtendedHeaders extendedHeaders() { return extendedHeaders.get(); } public Path staticResources() { return staticResources; } public String contextPath() { return contextPath.get(); } public int maxContentLength() { return maxContentLength.get(); } public List<CorsConfig> getCorsRules() { return cors.corsConfigs(); } public CorsConfiguration cors() { return cors; } public int getCompressionLevel() { return compressionLevel.get(); } @Override public String toString() { return "RestServerConfiguration{" + "authentication=" + authentication + ", cors=" + cors + ", encryption=" + encryption + '}'; } }
3,984
38.455446
174
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/configuration/RestServerConfigurationBuilder.java
package org.infinispan.rest.configuration; import static org.infinispan.rest.configuration.RestServerConfiguration.COMPRESSION_LEVEL; import static org.infinispan.rest.configuration.RestServerConfiguration.CONTEXT_PATH; import static org.infinispan.rest.configuration.RestServerConfiguration.EXTENDED_HEADERS; import static org.infinispan.rest.configuration.RestServerConfiguration.MAX_CONTENT_LENGTH; import static org.infinispan.server.core.configuration.ProtocolServerConfiguration.NAME; import java.nio.file.Path; import java.util.List; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.rest.logging.Log; import org.infinispan.server.core.configuration.EncryptionConfigurationBuilder; import org.infinispan.server.core.configuration.ProtocolServerConfigurationBuilder; import org.infinispan.util.logging.LogFactory; import io.netty.handler.codec.http.cors.CorsConfig; /** * RestServerConfigurationBuilder. * * @author Tristan Tarrant * @since 5.3 */ public class RestServerConfigurationBuilder extends ProtocolServerConfigurationBuilder<RestServerConfiguration, RestServerConfigurationBuilder, RestAuthenticationConfiguration> implements Builder<RestServerConfiguration> { final static Log logger = LogFactory.getLog(RestServerConfigurationBuilder.class, Log.class); private final RestAuthenticationConfigurationBuilder authentication; private final CorsConfigurationBuilder cors; private Path staticResources; private final EncryptionConfigurationBuilder encryption = new EncryptionConfigurationBuilder(ssl()); private static final int DEFAULT_PORT = 8080; private static final String DEFAULT_NAME = "rest"; public RestServerConfigurationBuilder() { super(DEFAULT_PORT, RestServerConfiguration.attributeDefinitionSet()); this.authentication = new RestAuthenticationConfigurationBuilder(this); this.cors = new CorsConfigurationBuilder(); } @Override public AttributeSet attributes() { return attributes; } public RestServerConfigurationBuilder extendedHeaders(ExtendedHeaders extendedHeaders) { attributes.attribute(EXTENDED_HEADERS).set(extendedHeaders); return this; } public RestServerConfigurationBuilder contextPath(String contextPath) { attributes.attribute(CONTEXT_PATH).set(contextPath); return this; } public RestServerConfigurationBuilder maxContentLength(int maxContentLength) { attributes.attribute(MAX_CONTENT_LENGTH).set(maxContentLength); return this; } public RestServerConfigurationBuilder compressionLevel(int compressLevel) { attributes.attribute(COMPRESSION_LEVEL).set(compressLevel); return this; } @Override public RestAuthenticationConfigurationBuilder authentication() { return authentication; } public EncryptionConfigurationBuilder encryption() { return encryption; } public RestServerConfigurationBuilder addAll(List<CorsConfig> corsConfig) { cors.add(corsConfig); return this; } public RestServerConfigurationBuilder staticResources(Path dir) { this.staticResources = dir; return this; } public CorsConfigurationBuilder cors() { return cors; } @Override public void validate() { super.validate(); authentication.validate(); int compressionLevel = attributes.attribute(COMPRESSION_LEVEL).get(); if (compressionLevel < 0 || compressionLevel > 9) { throw logger.illegalCompressionLevel(compressionLevel); } } @Override public RestServerConfiguration create() { if (!attributes.attribute(NAME).isModified()) { String socketBinding = socketBinding(); name(DEFAULT_NAME + (socketBinding == null ? "" : "-" + socketBinding)); } return new RestServerConfiguration(attributes.protect(), ssl.create(), staticResources, authentication.create(), cors.create(), encryption.create(), ipFilter.create()); } @Override public Builder<?> read(RestServerConfiguration template, Combine combine) { super.read(template, combine); this.attributes.read(template.attributes(), combine); this.authentication.read(template.authentication(), combine); this.cors.read(template.cors(), combine); this.encryption.read(template.encryption(), combine); return this; } public RestServerConfiguration build() { return build(true); } public RestServerConfiguration build(boolean validate) { if (validate) validate(); return create(); } @Override public RestServerConfigurationBuilder self() { return this; } @Override public RestServerConfigurationBuilder defaultCacheName(String defaultCacheName) { throw logger.unsupportedConfigurationOption(); } @Override public RestServerConfigurationBuilder idleTimeout(int idleTimeout) { throw logger.unsupportedConfigurationOption(); } @Override public RestServerConfigurationBuilder tcpNoDelay(boolean tcpNoDelay) { throw logger.unsupportedConfigurationOption(); } @Override public RestServerConfigurationBuilder tcpKeepAlive(boolean tcpKeepAlive) { throw logger.unsupportedConfigurationOption(); } @Override public RestServerConfigurationBuilder recvBufSize(int recvBufSize) { throw logger.unsupportedConfigurationOption(); } @Override public RestServerConfigurationBuilder sendBufSize(int sendBufSize) { throw logger.unsupportedConfigurationOption(); } }
5,674
32.579882
187
java
null
infinispan-main/server/rest/src/main/java/org/infinispan/rest/configuration/ExtendedHeaders.java
package org.infinispan.rest.configuration; public enum ExtendedHeaders { NEVER, ON_DEMAND }
99
13.285714
42
java