http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/DataCommandsOverHttpDistributedTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/DataCommandsOverHttpDistributedTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/DataCommandsOverHttpDistributedTest.java new file mode 100644 index 0000000..11b8ab1 --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/DataCommandsOverHttpDistributedTest.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 com.gemstone.gemfire.management.internal.cli.commands; + +import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*; +import static com.gemstone.gemfire.test.dunit.Wait.*; +import static org.junit.Assert.*; + +import com.gemstone.gemfire.cache.Cache; +import com.gemstone.gemfire.cache.Region; +import com.gemstone.gemfire.cache.RegionFactory; +import com.gemstone.gemfire.cache.RegionShortcut; +import com.gemstone.gemfire.management.DistributedRegionMXBean; +import com.gemstone.gemfire.management.ManagementService; +import com.gemstone.gemfire.management.cli.Result; +import com.gemstone.gemfire.management.internal.cli.result.CommandResult; +import com.gemstone.gemfire.test.dunit.Host; +import com.gemstone.gemfire.test.dunit.SerializableRunnable; +import com.gemstone.gemfire.test.dunit.VM; +import com.gemstone.gemfire.test.dunit.WaitCriterion; +import com.gemstone.gemfire.test.junit.categories.DistributedTest; + +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.contrib.java.lang.system.ProvideSystemProperty; +import org.junit.experimental.categories.Category; + +@Category(DistributedTest.class) +@SuppressWarnings("deprecated") +public class DataCommandsOverHttpDistributedTest extends CliCommandTestBase { + + private static final String REBALANCE_REGION_NAME = DataCommandsOverHttpDistributedTest.class.getSimpleName() + "Region"; + + @ClassRule + public static ProvideSystemProperty provideSystemProperty = new ProvideSystemProperty(CliCommandTestBase.USE_HTTP_SYSTEM_PROPERTY, "true"); + + @Test + public void testSimulateForEntireDSWithTimeout() { + setupTestRebalanceForEntireDS(); + //check if DistributedRegionMXBean is available so that command will not fail + final VM manager = Host.getHost(0).getVM(0); + manager.invoke(checkRegionMBeans); + + getLogWriter().info("testSimulateForEntireDS verified MBean and executing command"); + + String command = "rebalance --simulate=true --time-out=-1"; + + CommandResult cmdResult = executeCommand(command); + + getLogWriter().info("testSimulateForEntireDS just after executing " + cmdResult); + + if (cmdResult != null) { + String stringResult = commandResultToString(cmdResult); + getLogWriter().info("testSimulateForEntireDS stringResult : " + stringResult); + assertEquals(Result.Status.OK, cmdResult.getStatus()); + } else { + fail("testRebalanceForIncludeRegionFunction failed as did not get CommandResult"); + } + } + + SerializableRunnable checkRegionMBeans = new SerializableRunnable() { + @Override + public void run() { + final WaitCriterion waitForMaangerMBean = new WaitCriterion() { + @Override + public boolean done() { + final ManagementService service = ManagementService.getManagementService(getCache()); + final DistributedRegionMXBean bean = service.getDistributedRegionMXBean( + Region.SEPARATOR + REBALANCE_REGION_NAME); + if (bean == null) { + getLogWriter().info("Still probing for checkRegionMBeans ManagerMBean"); + return false; + } else { + // verify that bean is proper before executing tests + if (bean.getMembers() != null && bean.getMembers().length > 1 && bean.getMemberCount() > 0 && service.getDistributedSystemMXBean().listRegions().length >= 2) { + return true; + } else { + return false; + } + } + } + + @Override + public String description() { + return "Probing for testRebalanceCommandForSimulateWithNoMember ManagerMBean"; + } + }; + waitForCriterion(waitForMaangerMBean, 2 * 60 * 1000, 2000, true); + DistributedRegionMXBean bean = ManagementService.getManagementService(getCache()).getDistributedRegionMXBean( + "/" + REBALANCE_REGION_NAME); + assertNotNull(bean); + } + }; + + void setupTestRebalanceForEntireDS() { + final VM vm1 = Host.getHost(0).getVM(1); + final VM vm2 = Host.getHost(0).getVM(2); + setUpJmxManagerOnVm0ThenConnect(null); + + vm1.invoke(new SerializableRunnable() { + public void run() { + + // no need to close cache as it will be closed as part of teardown2 + Cache cache = getCache(); + + RegionFactory<Integer, Integer> dataRegionFactory = cache.createRegionFactory(RegionShortcut.PARTITION); + Region region = dataRegionFactory.create(REBALANCE_REGION_NAME); + for (int i = 0; i < 10; i++) { + region.put("key" + (i + 200), "value" + (i + 200)); + } + region = dataRegionFactory.create(REBALANCE_REGION_NAME + "Another1"); + for (int i = 0; i < 100; i++) { + region.put("key" + (i + 200), "value" + (i + 200)); + } + } + }); + + vm2.invoke(new SerializableRunnable() { + public void run() { + + // no need to close cache as it will be closed as part of teardown2 + Cache cache = getCache(); + + RegionFactory<Integer, Integer> dataRegionFactory = cache.createRegionFactory(RegionShortcut.PARTITION); + Region region = dataRegionFactory.create(REBALANCE_REGION_NAME); + for (int i = 0; i < 100; i++) { + region.put("key" + (i + 400), "value" + (i + 400)); + } + region = dataRegionFactory.create(REBALANCE_REGION_NAME + "Another2"); + for (int i = 0; i < 10; i++) { + region.put("key" + (i + 200), "value" + (i + 200)); + } + } + }); + } + +}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/security/GfshCommandsOverHttpSecurityTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/security/GfshCommandsOverHttpSecurityTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/security/GfshCommandsOverHttpSecurityTest.java new file mode 100644 index 0000000..313f31a --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/security/GfshCommandsOverHttpSecurityTest.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 com.gemstone.gemfire.management.internal.security; + +import com.gemstone.gemfire.test.junit.categories.IntegrationTest; + +import com.gemstone.gemfire.test.junit.categories.SecurityTest; +import org.junit.experimental.categories.Category; + +@Category({ IntegrationTest.class, SecurityTest.class }) +public class GfshCommandsOverHttpSecurityTest extends GfshCommandsSecurityTest { + public GfshCommandsOverHttpSecurityTest(){ + gfshConnection = new GfshShellConnectionRule(jmxPort, httpPort, true); + } +} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/web/AbstractWebTestCase.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/AbstractWebTestCase.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/AbstractWebTestCase.java new file mode 100644 index 0000000..ae5c749 --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/AbstractWebTestCase.java @@ -0,0 +1,96 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 com.gemstone.gemfire.management.internal.web; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; + +import com.gemstone.gemfire.internal.lang.StringUtils; +import com.gemstone.gemfire.management.internal.web.domain.Link; + +/** + * The AbstractWebDomainTests class is abstract base class containing functionality common to a test suite classes + * in the com.gemstone.gemfire.management.internal.web.domain package. + * <p/> + * @see java.net.URI + * @see java.net.URLDecoder + * @see java.net.URLEncoder + * @see com.gemstone.gemfire.management.internal.web.domain.Link + * @since GemFire 8.0 + */ +@SuppressWarnings("unused") +public abstract class AbstractWebTestCase { + + protected <E> E[] createArray(final E... array) { + return array; + } + + protected <K, V> Map<K, V> createMap(final K[] keys, final V[] values) { + assert keys != null : "The Keys for the Map cannot be null!"; + assert values != null : "The Values for the Map cannot be null!"; + assert keys.length == values.length; + + final Map<K, V> map = new HashMap<K, V>(keys.length); + int index = 0; + + for (final K key : keys) { + map.put(key, values[index++]); + } + + return map; + } + + protected String decode(final String encodedValue) throws UnsupportedEncodingException { + return URLDecoder.decode(encodedValue, StringUtils.UTF_8); + } + + protected String encode(final String value) throws UnsupportedEncodingException { + return URLEncoder.encode(value, StringUtils.UTF_8); + } + + protected String toString(final Link... links) throws UnsupportedEncodingException { + final StringBuilder buffer = new StringBuilder("["); + int count = 0; + + for (final Link link : links) { + buffer.append(count++ > 0 ? ", " : StringUtils.EMPTY_STRING).append(toString(link)); + + } + + buffer.append("]"); + + return buffer.toString(); + } + + protected String toString(final Link link) throws UnsupportedEncodingException { + return link.toHttpRequestLine(); + } + + protected String toString(final URI uri) throws UnsupportedEncodingException { + return decode(uri.toString()); + } + + protected URI toUri(final String uriString) throws UnsupportedEncodingException, URISyntaxException { + return new URI(encode(uriString)); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/ShellCommandsControllerJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/ShellCommandsControllerJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/ShellCommandsControllerJUnitTest.java new file mode 100644 index 0000000..8fd3127 --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/ShellCommandsControllerJUnitTest.java @@ -0,0 +1,238 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 com.gemstone.gemfire.management.internal.web.controllers; + +import static org.junit.Assert.*; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.servlet.http.HttpServletRequest; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.shell.core.CommandMarker; +import org.springframework.shell.core.annotation.CliCommand; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import com.gemstone.gemfire.management.cli.CliMetaData; +import com.gemstone.gemfire.management.internal.cli.util.ClasspathScanLoadHelper; +import com.gemstone.gemfire.management.internal.web.domain.Link; +import com.gemstone.gemfire.management.internal.web.domain.LinkIndex; +import com.gemstone.gemfire.management.internal.web.util.UriUtils; +import com.gemstone.gemfire.test.junit.categories.UnitTest; + +/** + * The ShellCommandsControllerJUnitTest class is a test suite of test cases testing the contract and functionality of the + * ShellCommandsController class, and specifically ensuring that all GemFire Gfsh commands have a corresponding + * Management REST API call and web service endpoint in the GemFire Management REST Interface. + * <p/> + * @see org.junit.Test + * @see com.gemstone.gemfire.management.internal.web.controllers.ShellCommandsController + * @since GemFire 8.0 + */ +@Category(UnitTest.class) +public class ShellCommandsControllerJUnitTest { + + private static ShellCommandsController controller; + + @BeforeClass + public static void setupBeforeClass() { + controller = new ShellCommandsController(); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setContextPath("gemfire"); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + } + + @AfterClass + public static void tearDownAfterClass() { + controller = null; + } + + private List<String> getCliCommands() { + try { + Set<Class<?>> commandClasses = ClasspathScanLoadHelper.loadAndGet( + "com.gemstone.gemfire.management.internal.cli.commands", CommandMarker.class, true); + + List<String> commands = new ArrayList<>(commandClasses.size()); + + for (Class<?> commandClass : commandClasses) { + for (Method method : commandClass.getMethods()) { + if (method.isAnnotationPresent(CliCommand.class)) { + if (!(method.isAnnotationPresent(CliMetaData.class) + && method.getAnnotation(CliMetaData.class).shellOnly())) + { + CliCommand commandAnnotation = method.getAnnotation(CliCommand.class); + commands.addAll(Arrays.asList(commandAnnotation.value())); + } + } + } + } + + return commands; + } + catch (Exception e) { + throw new RuntimeException(e); + } + } + + private List<String> getControllerWebServiceEndpoints() { + RequestAttributes requestAttrs = RequestContextHolder.getRequestAttributes(); + HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttrs).getRequest(); + String scheme = servletRequest.getScheme(); + + try { + Set<Class<?>> controllerClasses = ClasspathScanLoadHelper.loadAndGet( + "com.gemstone.gemfire.management.internal.web.controllers", AbstractCommandsController.class, true); + + List<String> controllerWebServiceEndpoints = new ArrayList<>(controllerClasses.size()); + + for (Class<?> controllerClass : controllerClasses) { + if (!AbstractCommandsController.class.equals(controllerClass)) { + for (Method method : controllerClass.getMethods()) { + if (method.isAnnotationPresent(RequestMapping.class)) { + RequestMapping requestMappingAnnotation = method.getAnnotation(RequestMapping.class); + + String webServiceEndpoint = String.format("%1$s %2$s", requestMappingAnnotation.method()[0], + UriUtils.decode(controller.toUri(requestMappingAnnotation.value()[0], scheme).toString())); + + String[] requestParameters = requestMappingAnnotation.params(); + + if (requestParameters.length > 0) { + webServiceEndpoint += "?".concat( + com.gemstone.gemfire.internal.lang.StringUtils.concat(requestParameters, "&")); + } + + controllerWebServiceEndpoints.add(webServiceEndpoint); + } + } + } + } + + return controllerWebServiceEndpoints; + } + catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testUniqueIndex() { + LinkIndex linkIndex = controller.index("https"); + + List<String> conflicts = new ArrayList<>(); + Map<String, String> uriRelationMapping = new HashMap<>(linkIndex.size()); + + for (Link link : linkIndex) { + if (uriRelationMapping.containsKey(link.toHttpRequestLine())) { + conflicts.add(String.format("REST API endpoint (%1$s) for (%2$s) conflicts with the REST API endpoint for (%3$s)", + link.toHttpRequestLine(), link.getRelation(), uriRelationMapping.get(link.toHttpRequestLine()))); + } + else { + uriRelationMapping.put(link.toHttpRequestLine(), link.getRelation()); + } + } + + assertTrue(String.format("Conflicts: %1$s!", conflicts), conflicts.isEmpty()); + } + + @Test + public void testIndex() { + List<String> commands = getCliCommands(); + + assertNotNull(commands); + assertFalse(commands.isEmpty()); + + LinkIndex linkIndex = controller.index("https"); + + assertNotNull(linkIndex); + assertFalse(linkIndex.isEmpty()); + + List<String> linkCommands = new ArrayList<>(linkIndex.size()); + + for (Link link : linkIndex) { + linkCommands.add(link.getRelation()); + } + + assertEquals(linkIndex.size(), linkCommands.size()); + + List<String> missingLinkCommands = new ArrayList<>(commands); + + missingLinkCommands.removeAll(linkCommands); + + assertTrue(String.format( + "The GemFire Management REST API Link Index is missing Link(s) for the following command(s): %1$s", + missingLinkCommands), missingLinkCommands.isEmpty()); + } + + @Test + public void testCommandHasRestApiControllerWebServiceEndpoint() { + List<String> controllerWebServiceEndpoints = getControllerWebServiceEndpoints(); + + assertNotNull(controllerWebServiceEndpoints); + assertFalse(controllerWebServiceEndpoints.isEmpty()); + + LinkIndex linkIndex = controller.index("http"); + + assertNotNull(linkIndex); + assertFalse(linkIndex.isEmpty()); + + List<String> linkWebServiceEndpoints = new ArrayList<>(linkIndex.size()); + + for (Link link : linkIndex) { + linkWebServiceEndpoints.add(link.toHttpRequestLine()); + } + + assertEquals(linkIndex.size(), linkWebServiceEndpoints.size()); + + List<String> missingControllerWebServiceEndpoints = new ArrayList<>(linkWebServiceEndpoints); + + missingControllerWebServiceEndpoints.removeAll(controllerWebServiceEndpoints); + + assertTrue(String.format( + "The Management REST API Web Service Controllers in (%1$s) are missing the following REST API Web Service Endpoint(s): %2$s!", + getClass().getPackage().getName(), missingControllerWebServiceEndpoints), missingControllerWebServiceEndpoints.isEmpty()); + } + + @Test + public void testIndexUrisHaveCorrectScheme() { + String versionCmd = "version"; + List<String> controllerWebServiceEndpoints = getControllerWebServiceEndpoints(); + + assertNotNull(controllerWebServiceEndpoints); + assertFalse(controllerWebServiceEndpoints.isEmpty()); + + String testScheme = "xyz"; + LinkIndex linkIndex = controller.index(testScheme); + + assertNotNull(linkIndex); + assertFalse(linkIndex.isEmpty()); + + assertTrue(String.format("Link does not have correct scheme %1$s", linkIndex.find(versionCmd)), + testScheme.equals(linkIndex.find(versionCmd).getHref().getScheme())); + } +} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/support/LoginHandlerInterceptorJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/support/LoginHandlerInterceptorJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/support/LoginHandlerInterceptorJUnitTest.java new file mode 100644 index 0000000..0037a48 --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/support/LoginHandlerInterceptorJUnitTest.java @@ -0,0 +1,273 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 com.gemstone.gemfire.management.internal.web.controllers.support; + +import static org.junit.Assert.*; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; + +import edu.umd.cs.mtc.MultithreadedTestCase; +import edu.umd.cs.mtc.TestFramework; +import org.jmock.Expectations; +import org.jmock.Mockery; +import org.jmock.lib.concurrent.Synchroniser; +import org.jmock.lib.legacy.ClassImposteriser; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import com.gemstone.gemfire.test.junit.categories.UnitTest; + +/** + * The LoginHandlerInterceptorJUnitTest class is a test suite of test cases to test the contract + * and functionality of the Spring HandlerInterceptor, LoginHandlerInterceptor class. + * + * @see org.jmock.Mockery + * @see org.junit.Assert + * @see org.junit.Test + * @since GemFire 8.0 + */ +@Category(UnitTest.class) +public class LoginHandlerInterceptorJUnitTest { + + private Mockery mockContext; + + @Before + public void setUp() { + mockContext = new Mockery(); + mockContext.setImposteriser(ClassImposteriser.INSTANCE); + mockContext.setThreadingPolicy(new Synchroniser()); + } + + @After + public void tearDown() { + mockContext.assertIsSatisfied(); + mockContext = null; + } + + private String createEnvironmentVariable(final String name) { + return (LoginHandlerInterceptor.ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + name); + } + + private <T> Enumeration<T> enumeration(final Iterator<T> iterator) { + return new Enumeration<T>() { + public boolean hasMoreElements() { + return iterator.hasNext(); + } + public T nextElement() { + return iterator.next(); + } + }; + } + + @Test + public void testPreHandleAfterCompletion() throws Exception { + final Map<String, String> requestParameters = new HashMap<>(2); + final Map<String, String> requestHeaders = new HashMap<>(); + + requestParameters.put("parameter", "one"); + requestParameters.put(createEnvironmentVariable("variable"), "two"); + + final HttpServletRequest mockHttpRequest = mockContext.mock(HttpServletRequest.class, "testPreHandleAfterCompletion.HttpServletRequest"); + + mockContext.checking(new Expectations() {{ + oneOf(mockHttpRequest).getParameterNames(); + will(returnValue(enumeration(requestParameters.keySet().iterator()))); + oneOf(mockHttpRequest).getHeaderNames(); + will(returnValue(enumeration(requestHeaders.keySet().iterator()))); + oneOf(mockHttpRequest).getParameter(with(equal(createEnvironmentVariable("variable")))); + will(returnValue(requestParameters.get(createEnvironmentVariable("variable")))); + }}); + + LoginHandlerInterceptor handlerInterceptor = new LoginHandlerInterceptor(); + + Map<String, String> envBefore = LoginHandlerInterceptor.getEnvironment(); + + assertNotNull(envBefore); + assertTrue(envBefore.isEmpty()); + assertTrue(handlerInterceptor.preHandle(mockHttpRequest, null, null)); + + Map<String, String> envSet = LoginHandlerInterceptor.getEnvironment(); + + assertNotNull(envSet); + assertNotSame(envBefore, envSet); + assertEquals(1, envSet.size()); + assertTrue(envSet.containsKey("variable")); + assertEquals("two", envSet.get("variable")); + + handlerInterceptor.afterCompletion(mockHttpRequest, null, null, null); + + Map<String, String> envAfter = LoginHandlerInterceptor.getEnvironment(); + + assertNotNull(envAfter); + assertTrue(envAfter.isEmpty()); + } + + @Test + public void testHandlerInterceptorThreadSafety() throws Throwable { + TestFramework.runOnce(new HandlerInterceptorThreadSafetyMultiThreadedTestCase()); + } + + private final class HandlerInterceptorThreadSafetyMultiThreadedTestCase extends MultithreadedTestCase { + + private LoginHandlerInterceptor handlerInterceptor; + + private HttpServletRequest mockHttpRequestOne; + private HttpServletRequest mockHttpRequestTwo; + + @Override + public void initialize() { + super.initialize(); + + final Map<String, String> requestParametersOne = new HashMap<>(3); + final Map<String, String> requestHeaders = new HashMap<>(); + + requestParametersOne.put("param", "one"); + requestParametersOne.put(createEnvironmentVariable("STAGE"), "test"); + requestParametersOne.put(createEnvironmentVariable("GEMFIRE"), "/path/to/gemfire/700"); + + mockHttpRequestOne = mockContext.mock(HttpServletRequest.class, "testHandlerInterceptorThreadSafety.HttpServletRequest.1"); + + mockContext.checking(new Expectations() {{ + oneOf(mockHttpRequestOne).getParameterNames(); + will(returnValue(enumeration(requestParametersOne.keySet().iterator()))); + oneOf(mockHttpRequestOne).getHeaderNames(); + will(returnValue(enumeration(requestHeaders.keySet().iterator()))); + oneOf(mockHttpRequestOne).getParameter(with(equal(createEnvironmentVariable("STAGE")))); + will(returnValue(requestParametersOne.get(createEnvironmentVariable("STAGE")))); + oneOf(mockHttpRequestOne).getParameter(with(equal(createEnvironmentVariable("GEMFIRE")))); + will(returnValue(requestParametersOne.get(createEnvironmentVariable("GEMFIRE")))); + }}); + + mockHttpRequestTwo = mockContext.mock(HttpServletRequest.class, "testHandlerInterceptorThreadSafety.HttpServletRequest.2"); + + final Map<String, String> requestParametersTwo = new HashMap<>(3); + + requestParametersTwo.put("parameter", "two"); + requestParametersTwo.put(createEnvironmentVariable("HOST"), "localhost"); + requestParametersTwo.put(createEnvironmentVariable("GEMFIRE"), "/path/to/gemfire/75"); + + mockContext.checking(new Expectations() {{ + oneOf(mockHttpRequestTwo).getParameterNames(); + will(returnValue(enumeration(requestParametersTwo.keySet().iterator()))); + oneOf(mockHttpRequestTwo).getHeaderNames(); + will(returnValue(enumeration(requestHeaders.keySet().iterator()))); + oneOf(mockHttpRequestTwo).getParameter(with(equal(createEnvironmentVariable("HOST")))); + will(returnValue(requestParametersTwo.get(createEnvironmentVariable("HOST")))); + oneOf(mockHttpRequestTwo).getParameter(with(equal(createEnvironmentVariable("GEMFIRE")))); + will(returnValue(requestParametersTwo.get(createEnvironmentVariable("GEMFIRE")))); + }}); + + handlerInterceptor = new LoginHandlerInterceptor(); + } + + public void thread1() throws Exception { + assertTick(0); + Thread.currentThread().setName("HTTP Request Processing Thread 1"); + + Map<String, String> env = LoginHandlerInterceptor.getEnvironment(); + + assertNotNull(env); + assertTrue(env.isEmpty()); + assertTrue(handlerInterceptor.preHandle(mockHttpRequestOne, null, null)); + + env = LoginHandlerInterceptor.getEnvironment(); + + assertNotNull(env); + assertEquals(2, env.size()); + assertFalse(env.containsKey("param")); + assertFalse(env.containsKey("parameter")); + assertFalse(env.containsKey("HOST")); + assertEquals("test", env.get("STAGE")); + assertEquals("/path/to/gemfire/700", env.get("GEMFIRE")); + + waitForTick(2); + + env = LoginHandlerInterceptor.getEnvironment(); + + assertNotNull(env); + assertEquals(2, env.size()); + assertFalse(env.containsKey("param")); + assertFalse(env.containsKey("parameter")); + assertFalse(env.containsKey("HOST")); + assertEquals("test", env.get("STAGE")); + assertEquals("/path/to/gemfire/700", env.get("GEMFIRE")); + + waitForTick(4); + + env = LoginHandlerInterceptor.getEnvironment(); + + assertNotNull(env); + assertEquals(2, env.size()); + assertFalse(env.containsKey("param")); + assertFalse(env.containsKey("parameter")); + assertFalse(env.containsKey("HOST")); + assertEquals("test", env.get("STAGE")); + assertEquals("/path/to/gemfire/700", env.get("GEMFIRE")); + + handlerInterceptor.afterCompletion(mockHttpRequestOne, null, null, null); + + env = LoginHandlerInterceptor.getEnvironment(); + + assertNotNull(env); + assertTrue(env.isEmpty()); + } + + public void thread2() throws Exception { + assertTick(0); + Thread.currentThread().setName("HTTP Request Processing Thread 2"); + waitForTick(1); + + Map<String, String> env = LoginHandlerInterceptor.getEnvironment(); + + assertNotNull(env); + assertTrue(env.isEmpty()); + assertTrue(handlerInterceptor.preHandle(mockHttpRequestTwo, null, null)); + + env = LoginHandlerInterceptor.getEnvironment(); + + assertNotNull(env); + assertEquals(2, env.size()); + assertFalse(env.containsKey("parameter")); + assertFalse(env.containsKey("param")); + assertFalse(env.containsKey("STAGE")); + assertEquals("localhost", env.get("HOST")); + assertEquals("/path/to/gemfire/75", env.get("GEMFIRE")); + + waitForTick(3); + + handlerInterceptor.afterCompletion(mockHttpRequestTwo, null, null, null); + + env = LoginHandlerInterceptor.getEnvironment(); + + assertNotNull(env); + assertTrue(env.isEmpty()); + } + + @Override + public void finish() { + super.finish(); + handlerInterceptor = null; + } + } + +} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/LinkIndexJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/LinkIndexJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/LinkIndexJUnitTest.java new file mode 100644 index 0000000..61a9736 --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/LinkIndexJUnitTest.java @@ -0,0 +1,236 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 com.gemstone.gemfire.management.internal.web.domain; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +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 com.gemstone.gemfire.internal.util.CollectionUtils; +import com.gemstone.gemfire.management.internal.web.AbstractWebTestCase; +import com.gemstone.gemfire.management.internal.web.http.HttpMethod; +import com.gemstone.gemfire.test.junit.categories.UnitTest; + +import org.junit.Test; +import org.junit.experimental.categories.Category; + +/** + * The LinkIndexJUnitTest class is a test suite of test cases testing the contract and functionality of the LinkIndex class. + * <p/> + * @see java.net.URI + * @see com.gemstone.gemfire.management.internal.web.AbstractWebTestCase + * @see com.gemstone.gemfire.management.internal.web.domain.LinkIndex + * @see org.junit.Assert + * @see org.junit.Test + * @since GemFire 8.0 + */ +@Category(UnitTest.class) +public class LinkIndexJUnitTest extends AbstractWebTestCase { + + @Test + public void testAdd() throws Exception { + final Link link = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}")); + + final LinkIndex linkIndex = new LinkIndex(); + + assertTrue(linkIndex.isEmpty()); + assertEquals(0, linkIndex.size()); + assertEquals(linkIndex, linkIndex.add(link)); + assertFalse(linkIndex.isEmpty()); + assertEquals(1, linkIndex.size()); + assertEquals(linkIndex, linkIndex.add(link)); // test duplicate addition + assertFalse(linkIndex.isEmpty()); + assertEquals(1, linkIndex.size()); + } + + @Test(expected = AssertionError.class) + public void testAddNullLink() { + final LinkIndex linkIndex = new LinkIndex(); + + assertTrue(linkIndex.isEmpty()); + + try { + linkIndex.add(null); + } + finally { + assertTrue(linkIndex.isEmpty()); + } + } + + @Test + public void testAddAll() throws Exception { + final Link create = new Link("create-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.POST); + final Link retrieve = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}")); + final Link update = new Link("update-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.PUT); + final Link delete = new Link("delete-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}"), HttpMethod.DELETE); + + final LinkIndex linkIndex = new LinkIndex(); + + assertTrue(linkIndex.isEmpty()); + assertEquals(linkIndex, linkIndex.addAll(create, retrieve, update, delete)); + assertFalse(linkIndex.isEmpty()); + assertEquals(4, linkIndex.size()); + } + + @Test(expected = AssertionError.class) + public void testAddAllWithNullLinks() { + final LinkIndex linkIndex = new LinkIndex(); + + assertTrue(linkIndex.isEmpty()); + + try { + linkIndex.addAll((Iterable<Link>) null); + } + finally { + assertTrue(linkIndex.isEmpty()); + } + } + + @Test + public void testFind() throws Exception { + final Link list = new Link("get-resources", toUri("http://host.domain.com:port/service/v1/resources")); + final Link create = new Link("create-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.POST); + final Link retrieve = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}")); + final Link update = new Link("update-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.PUT); + final Link delete = new Link("delete-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}"), HttpMethod.DELETE); + + final LinkIndex linkIndex = new LinkIndex(); + + assertTrue(linkIndex.isEmpty()); + assertEquals(linkIndex, linkIndex.addAll(list, create, retrieve, update, delete)); + assertFalse(linkIndex.isEmpty()); + assertEquals(5, linkIndex.size()); + assertEquals(list, linkIndex.find("get-resources")); + assertEquals(retrieve, linkIndex.find("get-resource")); + assertEquals(update, linkIndex.find("UPDATE-RESOURCE")); + assertEquals(delete, linkIndex.find("Delete-Resource")); + assertNull(linkIndex.find("destroy-resource")); + assertNull(linkIndex.find("save-resource")); + } + + @Test + public void testFindAll() throws Exception { + final Link list = new Link("get-resources", toUri("http://host.domain.com:port/service/v1/resources")); + final Link create = new Link("create-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.POST); + final Link retrieveById = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}")); + final Link retrieveByName = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{name}")); + final Link update = new Link("update-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.PUT); + final Link delete = new Link("delete-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}"), HttpMethod.DELETE); + + final LinkIndex linkIndex = new LinkIndex(); + + assertTrue(linkIndex.isEmpty()); + assertEquals(linkIndex, linkIndex.addAll(list, create, retrieveById, retrieveByName, update, delete)); + assertFalse(linkIndex.isEmpty()); + assertEquals(6, linkIndex.size()); + + final Link[] retrieveLinks = linkIndex.findAll("get-resource"); + + assertNotNull(retrieveLinks); + assertEquals(2, retrieveLinks.length); + assertTrue(Arrays.asList(retrieveLinks).containsAll(Arrays.asList(retrieveById, retrieveByName))); + + final Link[] saveLinks = linkIndex.findAll("save-resource"); + + assertNotNull(saveLinks); + assertEquals(0, saveLinks.length); + } + + @Test + public void testIterator() throws Exception { + final Link list = new Link("get-resources", toUri("http://host.domain.com:port/service/v1/resources")); + final Link create = new Link("create-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.POST); + final Link retrieveById = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}")); + final Link retrieveByName = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{name}")); + final Link update = new Link("update-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.PUT); + final Link delete = new Link("delete-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}"), HttpMethod.DELETE); + + final LinkIndex linkIndex = new LinkIndex(); + + assertTrue(linkIndex.isEmpty()); + assertEquals(linkIndex, linkIndex.addAll(list, create, retrieveById, retrieveByName, update, delete)); + assertFalse(linkIndex.isEmpty()); + assertEquals(6, linkIndex.size()); + + final Collection<Link> expectedLinks = Arrays.asList(list, create, retrieveById, retrieveByName, update, delete); + + final Collection<Link> actualLinks = new ArrayList<Link>(linkIndex.size()); + + for (final Link link : linkIndex) { + actualLinks.add(link); + } + + assertTrue(actualLinks.containsAll(expectedLinks)); + } + + @Test + public void testToList() throws Exception { + final Link list = new Link("get-resources", toUri("http://host.domain.com:port/service/v1/resources")); + final Link create = new Link("create-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.POST); + final Link retrieveById = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}")); + final Link retrieveByName = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{name}")); + final Link update = new Link("update-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.PUT); + final Link delete = new Link("delete-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}"), HttpMethod.DELETE); + + final LinkIndex linkIndex = new LinkIndex(); + + assertTrue(linkIndex.isEmpty()); + assertEquals(linkIndex, linkIndex.addAll(list, create, retrieveById, retrieveByName, update, delete)); + assertFalse(linkIndex.isEmpty()); + assertEquals(6, linkIndex.size()); + + final List<Link> expectedList = CollectionUtils.asList(list, create, retrieveById, retrieveByName, update, delete); + + Collections.sort(expectedList); + + assertEquals(expectedList, linkIndex.toList()); + } + + @Test + public void testToMap() throws Exception { + final Link list = new Link("get-resources", toUri("http://host.domain.com:port/service/v1/resources")); + final Link create = new Link("create-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.POST); + final Link retrieveById = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}")); + final Link retrieveByName = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{name}")); + final Link update = new Link("update-resource", toUri("http://host.domain.com:port/service/v1/resources"), HttpMethod.PUT); + final Link delete = new Link("delete-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}"), HttpMethod.DELETE); + + final LinkIndex linkIndex = new LinkIndex(); + + assertTrue(linkIndex.isEmpty()); + assertEquals(linkIndex, linkIndex.addAll(list, create, retrieveById, retrieveByName, update, delete)); + assertFalse(linkIndex.isEmpty()); + assertEquals(6, linkIndex.size()); + + final Map<String, List<Link>> expectedMap = new HashMap<String, List<Link>>(5); + + expectedMap.put("get-resources", Arrays.asList(list)); + expectedMap.put("create-resource", Arrays.asList(create)); + expectedMap.put("get-resource", Arrays.asList(retrieveById, retrieveByName)); + expectedMap.put("update-resource", Arrays.asList(update)); + expectedMap.put("delete-resource", Arrays.asList(delete)); + + assertEquals(expectedMap, linkIndex.toMap()); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/LinkJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/LinkJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/LinkJUnitTest.java new file mode 100644 index 0000000..c0b1620 --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/LinkJUnitTest.java @@ -0,0 +1,123 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 com.gemstone.gemfire.management.internal.web.domain; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import com.gemstone.gemfire.internal.util.CollectionUtils; +import com.gemstone.gemfire.management.internal.web.AbstractWebTestCase; +import com.gemstone.gemfire.management.internal.web.http.HttpMethod; +import com.gemstone.gemfire.test.junit.categories.UnitTest; + +import org.junit.Test; +import org.junit.experimental.categories.Category; + +/** + * The LinkJUnitTest class is a test suite of test cases testing the contract and functionality of the Link class. + * <p/> + * @see java.net.URI + * @see com.gemstone.gemfire.management.internal.web.AbstractWebTestCase + * @see com.gemstone.gemfire.management.internal.web.domain.Link + * @see org.junit.Assert + * @see org.junit.Test + * @since GemFire 8.0 + */ +@Category(UnitTest.class) +public class LinkJUnitTest extends AbstractWebTestCase { + + @Test + public void testConstructDefaultLink() { + final Link link = new Link(); + + assertNotNull(link); + assertNull(link.getHref()); + assertNull(link.getMethod()); + assertNull(link.getRelation()); + } + + @Test + public void testConstructLinkWithRelationAndHref() throws Exception { + final Link link = new Link("get-resource", toUri("http://host:port/service/v1/resources/{id}")); + + assertNotNull(link); + assertEquals("http://host:port/service/v1/resources/{id}", toString(link.getHref())); + assertEquals(HttpMethod.GET, link.getMethod()); + assertEquals("get-resource", link.getRelation()); + } + + @Test + public void testConstructLinkWithRelationHrefAndMethod() throws Exception { + final Link link = new Link("create-resource", toUri("http://host:port/service/v1/resources"), HttpMethod.POST); + + assertNotNull(link); + assertEquals("http://host:port/service/v1/resources", toString(link.getHref())); + assertEquals(HttpMethod.POST, link.getMethod()); + assertEquals("create-resource", link.getRelation()); + } + + @Test + public void testSetAndGetMethod() { + final Link link = new Link(); + + assertNotNull(link); + assertNull(link.getMethod()); + + link.setMethod(HttpMethod.POST); + + assertEquals(HttpMethod.POST, link.getMethod()); + + link.setMethod(null); + + assertEquals(HttpMethod.GET, link.getMethod()); + } + + @Test + public void testCompareTo() throws Exception { + final Link link0 = new Link("resources", toUri("http://host:port/service/v1/resources")); + final Link link1 = new Link("resource", toUri("http://host:port/service/v1/resources"), HttpMethod.POST); + final Link link2 = new Link("resource", toUri("http://host:port/service/v1/resources/{id}")); + final Link link3 = new Link("resource", toUri("http://host:port/service/v1/resources/{name}")); + final Link link4 = new Link("resource", toUri("http://host:port/service/v1/resources/{id}"), HttpMethod.DELETE); + + final List<Link> expectedList = new ArrayList<Link>(Arrays.asList(link1, link4, link2, link3, link0)); + + final List<Link> actualList = CollectionUtils.asList(link0, link1, link2, link3, link4); + + Collections.sort(actualList); + + System.out.println(toString(expectedList.toArray(new Link[expectedList.size()]))); + System.out.println(toString(actualList.toArray(new Link[actualList.size()]))); + + assertEquals(expectedList, actualList); + } + + @Test + public void testToHttpRequestLine() throws Exception { + final Link link = new Link("get-resource", toUri("http://host.domain.com:port/service/v1/resources/{id}")); + + assertNotNull(link); + assertEquals(HttpMethod.GET, link.getMethod()); + assertEquals("http://host.domain.com:port/service/v1/resources/{id}", toString(link.getHref())); + assertEquals("GET ".concat("http://host.domain.com:port/service/v1/resources/{id}"), link.toHttpRequestLine()); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/QueryParameterSourceJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/QueryParameterSourceJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/QueryParameterSourceJUnitTest.java new file mode 100644 index 0000000..ae2f87b --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/domain/QueryParameterSourceJUnitTest.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 com.gemstone.gemfire.management.internal.web.domain; + +import static org.junit.Assert.*; + +import java.io.IOException; + +import javax.management.MalformedObjectNameException; +import javax.management.ObjectName; +import javax.management.Query; +import javax.management.QueryExp; + +import com.gemstone.gemfire.internal.util.IOUtils; +import com.gemstone.gemfire.test.junit.categories.UnitTest; + +import org.junit.Test; +import org.junit.experimental.categories.Category; + +/** + * The QueryParameterSourceJUnitTest class is a test suite of test cases testing the contract and functionality of the + * QueryParameterSource class. + * <p/> + * @see com.gemstone.gemfire.management.internal.web.domain.QueryParameterSource + * @see org.junit.Assert + * @see org.junit.Test + * @since GemFire 8.0 + */ +@Category(UnitTest.class) +public class QueryParameterSourceJUnitTest { + + @Test + public void testCreateQueryParameterSource() throws MalformedObjectNameException { + final ObjectName expectedObjectName = ObjectName.getInstance("GemFire:type=Member,*"); + + final QueryExp expectedQueryExpression = Query.eq(Query.attr("id"), Query.value("12345")); + + final QueryParameterSource query = new QueryParameterSource(expectedObjectName, expectedQueryExpression); + + assertNotNull(query); + assertSame(expectedObjectName, query.getObjectName()); + assertSame(expectedQueryExpression, query.getQueryExpression()); + } + + @Test + public void testSerialization() throws ClassNotFoundException, IOException, MalformedObjectNameException { + final ObjectName expectedObjectName = ObjectName.getInstance("GemFire:type=Member,*"); + + final QueryExp expectedQueryExpression = Query.or( + Query.eq(Query.attr("name"), Query.value("myName")), + Query.eq(Query.attr("id"), Query.value("myId")) + ); + + final QueryParameterSource expectedQuery = new QueryParameterSource(expectedObjectName, expectedQueryExpression); + + assertNotNull(expectedQuery); + assertSame(expectedObjectName, expectedQuery.getObjectName()); + assertSame(expectedQueryExpression, expectedQuery.getQueryExpression()); + + final byte[] queryBytes = IOUtils.serializeObject(expectedQuery); + + assertNotNull(queryBytes); + assertTrue(queryBytes.length != 0); + + final Object queryObj = IOUtils.deserializeObject(queryBytes); + + assertTrue(queryObj instanceof QueryParameterSource); + + final QueryParameterSource actualQuery = (QueryParameterSource) queryObj; + + assertNotSame(expectedQuery, actualQuery); + assertNotNull(actualQuery.getObjectName()); + assertEquals(expectedQuery.getObjectName().toString(), actualQuery.getObjectName().toString()); + assertNotNull(actualQuery.getQueryExpression()); + assertEquals(expectedQuery.getQueryExpression().toString(), actualQuery.getQueryExpression().toString()); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/web/http/ClientHttpRequestJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/http/ClientHttpRequestJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/http/ClientHttpRequestJUnitTest.java new file mode 100644 index 0000000..bbe961b --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/http/ClientHttpRequestJUnitTest.java @@ -0,0 +1,509 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 com.gemstone.gemfire.management.internal.web.http; + +import static org.junit.Assert.*; + +import java.net.URI; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jmock.Mockery; +import org.jmock.lib.legacy.ClassImposteriser; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.springframework.http.HttpEntity; +import org.springframework.http.MediaType; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import com.gemstone.gemfire.management.internal.web.AbstractWebTestCase; +import com.gemstone.gemfire.management.internal.web.domain.Link; +import com.gemstone.gemfire.test.junit.categories.UnitTest; + +/** + * The ClientHttpRequestJUnitTest class is a test suite of test cases testing the contract and functionality of the + * ClientHttpRequest class. + * <p/> + * @see com.gemstone.gemfire.management.internal.web.AbstractWebTestCase + * @see com.gemstone.gemfire.management.internal.web.http.ClientHttpRequest + * @see org.jmock.Mockery + * @see org.junit.Assert + * @see org.junit.Test + * @since GemFire 8.0 + */ +@Category(UnitTest.class) +public class ClientHttpRequestJUnitTest extends AbstractWebTestCase { + + private Mockery mockContext; + + @Before + public void setUp() { + mockContext = new Mockery(); + mockContext.setImposteriser(ClassImposteriser.INSTANCE); + } + + @After + public void tearDown() { + mockContext.assertIsSatisfied(); + mockContext = null; + } + + @Test + public void testCreateClientHttpRequest() throws Exception { + final Link expectedLink = new Link("test", toUri("http://host.domain.com:8080/app/service")); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertNotNull(request); + assertEquals(expectedLink, request.getLink()); + } + + @Test(expected = AssertionError.class) + public void testCreateClientHttpRequestWithNullLink() { + new ClientHttpRequest(null); + } + + @Test + public void testGetMethod() throws Exception { + Link link = new Link("get-resource", toUri("http://host.domain.com:8080/app/resources/{id}")); + ClientHttpRequest request = new ClientHttpRequest(link); + + assertEquals(link, request.getLink()); + assertEquals(org.springframework.http.HttpMethod.GET, request.getMethod()); + + link = new Link("delete-resource", toUri("http://host.domain.com:8080/app/resources/{id}"), HttpMethod.DELETE); + request = new ClientHttpRequest(link); + + assertEquals(link, request.getLink()); + assertEquals(org.springframework.http.HttpMethod.DELETE, request.getMethod()); + + link = new Link("delete-resource", toUri("http://host.domain.com:8080/app/service"), HttpMethod.HEAD); + request = new ClientHttpRequest(link); + + assertEquals(link, request.getLink()); + assertEquals(org.springframework.http.HttpMethod.HEAD, request.getMethod()); + + link = new Link("delete-resource", toUri("http://host.domain.com:8080/app/service"), HttpMethod.OPTIONS); + request = new ClientHttpRequest(link); + + assertEquals(link, request.getLink()); + assertEquals(org.springframework.http.HttpMethod.OPTIONS, request.getMethod()); + + link = new Link("delete-resource", toUri("http://host.domain.com:8080/app/resources"), HttpMethod.POST); + request = new ClientHttpRequest(link); + + assertEquals(link, request.getLink()); + assertEquals(org.springframework.http.HttpMethod.POST, request.getMethod()); + + link = new Link("delete-resource", toUri("http://host.domain.com:8080/app/resources"), HttpMethod.PUT); + request = new ClientHttpRequest(link); + + assertEquals(link, request.getLink()); + assertEquals(org.springframework.http.HttpMethod.PUT, request.getMethod()); + + link = new Link("delete-resource", toUri("http://host.domain.com:8080/app"), HttpMethod.TRACE); + request = new ClientHttpRequest(link); + + assertEquals(link, request.getLink()); + assertEquals(org.springframework.http.HttpMethod.TRACE, request.getMethod()); + } + + @Test + public void testIsDelete() throws Exception { + final Link expectedLink = new Link("delete", toUri("http://host.domain.com:8080/app/resources/{id}"), HttpMethod.DELETE); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + assertTrue(request.isDelete()); + assertFalse(request.isGet()); + assertFalse(request.isPost()); + assertFalse(request.isPut()); + } + + @Test + public void testIsGet() throws Exception { + final Link expectedLink = new Link("get", toUri("http://host.domain.com:8080/app/resources/{id}"), HttpMethod.GET); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + assertFalse(request.isDelete()); + assertTrue(request.isGet()); + assertFalse(request.isPost()); + assertFalse(request.isPut()); + } + + @Test + public void testIsPost() throws Exception { + final Link expectedLink = new Link("post", toUri("http://host.domain.com:8080/app/resources"), HttpMethod.POST); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + assertFalse(request.isDelete()); + assertFalse(request.isGet()); + assertTrue(request.isPost()); + assertFalse(request.isPut()); + } + + @Test + public void testIsPut() throws Exception { + final Link expectedLink = new Link("put", toUri("http://host.domain.com:8080/app/resources/{id}"), HttpMethod.PUT); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + assertFalse(request.isDelete()); + assertFalse(request.isGet()); + assertFalse(request.isPost()); + assertTrue(request.isPut()); + } + + @Test + public void testGetPathVariables() throws Exception { + final Link expectedLink = new Link("test", toUri("http://host.domain.com:8080/app/libraries/{name}/books/{author}/{title}")); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + assertEquals(Arrays.asList("name", "author", "title"), request.getPathVariables()); + } + + @Test + public void testGetPathVariablesWithUriHavingNoPathVariables() throws Exception { + final Link expectedLink = new Link("test", toUri("http://host.domain.com:8080/app/service")); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + + final List<String> actualPathVariables = request.getPathVariables(); + + assertNotNull(actualPathVariables); + assertTrue(actualPathVariables.isEmpty()); + } + + @Test + public void testGetURI() throws Exception { + final URI expectedURI = toUri("http://host.domain.com:8080/app/service"); + final Link expectedLink = new Link("test", expectedURI); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + assertEquals(expectedURI, request.getURI()); + } + + @Test + public void testGetURLForGet() throws Exception { + final Link expectedLink = new Link("find", toUri("http://host.domain.com:8080/app/libraries/{name}/books"), HttpMethod.GET); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + request.addParameterValues("author", "Rowling"); + request.addParameterValues("category", "science-fiction"); + + assertEquals(expectedLink, request.getLink()); + assertEquals("http://host.domain.com:8080/app/libraries/amazon/books?author=Rowling&category=science-fiction", + toString(request.getURL(Collections.singletonMap("name", "amazon")))); + } + + @Test + public void testGetURLForGetEncoded() throws Exception { + final Link expectedLink = new Link("readValue4Key", toUri("http://host.domain.com:8080/app/regions/{region}/keys/{key}"), HttpMethod.GET); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + final Map<String, Object> uriVariables = new HashMap<String, Object>(4); + + uriVariables.put("region", "Customers/Accounts/Orders"); + uriVariables.put("key", "123"); + uriVariables.put("item", "456"); + + assertEquals(expectedLink, request.getLink()); + assertEquals("http://host.domain.com:8080/app/regions/Customers%2FAccounts%2FOrders/keys/123", + toString(request.getURL(uriVariables))); + } + + @Test + public void testGetURLForGetWithQueryParametersNoBody() throws Exception { + final Link expectedLink = new Link("find", toUri("http://host.domain.com:8080/app/libraries/{name}/books/{author}"), HttpMethod.GET); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + request.addParameterValues("author", "Rowling"); + request.addParameterValues("category", "science-fiction"); + request.addParameterValues("name", "Boston"); + request.addParameterValues("year", "2007"); + + final Map<String, Object> uriVariables = new HashMap<String, Object>(4); + + uriVariables.put("author", "Rowling"); + uriVariables.put("category", "mystery"); + uriVariables.put("isbn", "0-123456789"); + uriVariables.put("name", "Amazon"); + + assertEquals(expectedLink, request.getLink()); + assertEquals("http://host.domain.com:8080/app/libraries/Amazon/books/Rowling?category=science-fiction&year=2007", + toString(request.getURL(uriVariables))); + } + + @Test + public void testGetURLForDelete() throws Exception { + final Link expectedLink = new Link("delete-all", toUri("http://host.domain.com:8080/app/libraries/{name}/books"), HttpMethod.DELETE); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + request.addParameterValues("category", "romance"); + + assertEquals(expectedLink, request.getLink()); + assertEquals("http://host.domain.com:8080/app/libraries/congress/books?category=romance", + toString(request.getURL(Collections.singletonMap("name", "congress")))); + } + + @Test + public void testGetURLForPost() throws Exception { + final Link expectedLink = new Link("post", toUri("http://host.domain.com:8080/app/libraries/{name}/books"), HttpMethod.POST); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + request.addParameterValues("author", "Douglas Adams"); + request.addParameterValues("title", "The Hitchhiker's Guide to the Galaxy"); + request.addParameterValues("year", "1979"); + request.addParameterValues("isbn", "0345453743"); + + assertEquals(expectedLink, request.getLink()); + assertEquals("http://host.domain.com:8080/app/libraries/royal/books", + toString(request.getURL(Collections.singletonMap("name", "royal")))); + } + + @Test + public void testGetURLForPut() throws Exception { + final Link expectedLink = new Link("put", toUri("http://host.domain.com:8080/app/libraries/{name}/books/{isbn}"), HttpMethod.PUT); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + request.addParameterValues("year", "1983"); + + final Map<String, String> uriVariables = new HashMap<String, String>(2); + + uriVariables.put("name", "royal"); + uriVariables.put("isbn", "0345453743"); + + assertEquals(expectedLink, request.getLink()); + assertEquals("http://host.domain.com:8080/app/libraries/royal/books/0345453743", + toString(request.getURL(uriVariables))); + } + + @Test + public void testCreateRequestEntityForGet() throws Exception { + final Link expectedLink = new Link("find", toUri("http://host.domain.com:8080/app/libraries/{name}/books"), HttpMethod.GET); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + + request.addHeaderValues(HttpHeader.CONTENT_TYPE.getName(), MediaType.TEXT_PLAIN_VALUE); + request.addParameterValues("author", "Rowling"); + request.addParameterValues("category", "science-fiction"); + + final HttpEntity<?> requestEntity = request.createRequestEntity(); + + assertNotNull(requestEntity); + assertNotNull(requestEntity.getHeaders()); + assertEquals(MediaType.TEXT_PLAIN, requestEntity.getHeaders().getContentType()); + assertNull(requestEntity.getBody()); + } + + @Test + public void testCreateRequestEntityForDelete() throws Exception { + final Link expectedLink = new Link("delete-all", toUri("http://host.domain.com:8080/app/libraries/{name}/books"), HttpMethod.DELETE); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + + request.addHeaderValues(HttpHeader.ACCEPT.getName(), MediaType.APPLICATION_JSON_VALUE); + request.addParameterValues("category", "romance"); + + final HttpEntity<?> requestEntity = request.createRequestEntity(); + + assertNotNull(requestEntity); + assertNotNull(requestEntity.getHeaders()); + assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), requestEntity.getHeaders().getAccept()); + assertNull(requestEntity.getBody()); + } + + @Test + @SuppressWarnings("unchecked") + public void testCreateRequestEntityForPost() throws Exception { + final Link expectedLink = new Link("post", toUri("http://host.domain.com:8080/app/libraries/{name}/books"), HttpMethod.POST); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + + final MultiValueMap<String, Object> expectedRequestParameters = new LinkedMultiValueMap<String, Object>(4); + + expectedRequestParameters.add("author", "Douglas Adams"); + expectedRequestParameters.add("title", "The Hitchhiker's Guide to the Galaxy"); + expectedRequestParameters.add("year", "1979"); + expectedRequestParameters.add("isbn", "0345453743"); + + request.addHeaderValues(HttpHeader.CONTENT_TYPE.getName(), MediaType.APPLICATION_FORM_URLENCODED_VALUE); + request.addParameterValues("author", expectedRequestParameters.getFirst("author")); + request.addParameterValues("title", expectedRequestParameters.getFirst("title")); + request.addParameterValues("year", expectedRequestParameters.getFirst("year")); + request.addParameterValues("isbn", expectedRequestParameters.getFirst("isbn")); + + final HttpEntity<MultiValueMap<String, Object>> requestEntity = (HttpEntity<MultiValueMap<String, Object>>) + request.createRequestEntity(); + + assertNotNull(requestEntity); + assertNotNull(requestEntity.getHeaders()); + assertEquals(MediaType.APPLICATION_FORM_URLENCODED, requestEntity.getHeaders().getContentType()); + assertEquals(expectedRequestParameters, requestEntity.getBody()); + } + + @Test + @SuppressWarnings("unchecked") + public void testCreateRequestEntityForPut() throws Exception { + final Link expectedLink = new Link("put", toUri("http://host.domain.com:8080/app/libraries/{name}/books/{isbn}"), HttpMethod.PUT); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + + final MultiValueMap<String, Object> expectedRequestParameters = new LinkedMultiValueMap<String, Object>(4); + + expectedRequestParameters.add("year", "1979"); + + request.addHeaderValues(HttpHeader.ACCEPT.getName(), MediaType.TEXT_XML_VALUE); + request.addHeaderValues(HttpHeader.CONTENT_TYPE.getName(), MediaType.APPLICATION_FORM_URLENCODED_VALUE); + request.addParameterValues("year", expectedRequestParameters.getFirst("year")); + + final HttpEntity<MultiValueMap<String, Object>> requestEntity = (HttpEntity<MultiValueMap<String, Object>>) + request.createRequestEntity(); + + assertNotNull(requestEntity); + assertNotNull(requestEntity.getHeaders()); + assertEquals(Collections.singletonList(MediaType.TEXT_XML), requestEntity.getHeaders().getAccept()); + assertEquals(MediaType.APPLICATION_FORM_URLENCODED, requestEntity.getHeaders().getContentType()); + assertEquals(expectedRequestParameters, requestEntity.getBody()); + } + + @Test + public void testCreateRequestEntityOnPost() throws Exception { + final Library mockLibrary = mockContext.mock(Library.class, "testCreateRequestEntityOnPost.Library"); + final Link expectedLink = new Link("post", toUri("http://host.domain.com:8080/app/libraries"), HttpMethod.POST); + + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + assertTrue(request.isPost()); + assertNull(request.getContent()); + + request.setContent(mockLibrary); + + assertSame(mockLibrary, request.getContent()); + + final HttpEntity<?> requestEntity = request.createRequestEntity(); + + assertNotNull(requestEntity); + assertTrue(requestEntity.getBody() instanceof Library); + } + + @Test + public void testCreateRequestEntityOnPut() throws Exception { + final Book mockBook = mockContext.mock(Book.class, "testCreateRequestEntityOnPut.Book"); + final Link expectedLink = new Link("put", toUri("http://host.domain.com:8080/app/libraries/{name}/books/{id}"), HttpMethod.PUT); + + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + assertTrue(request.isPut()); + assertNull(request.getContent()); + + request.setContent(mockBook); + request.addParameterValues("isbn", "0-123456789"); + request.addParameterValues("category", "science-fiction", "sci-fi", "fiction"); + + assertSame(mockBook, request.getContent()); + assertEquals("0-123456789", request.getParameterValue("isbn")); + assertTrue(request.getParameterValues("category").containsAll(Arrays.asList("science-fiction", "sci-fi", "fiction"))); + + final HttpEntity<?> requestEntity = request.createRequestEntity(); + + assertNotNull(requestEntity); + assertTrue(requestEntity.getBody() instanceof MultiValueMap); + assertEquals(MediaType.APPLICATION_FORM_URLENCODED, requestEntity.getHeaders().getContentType()); + } + + @Test + public void testSetAndGetHeaderValues() throws Exception { + final Link expectedLink = new Link("put", toUri("http://host.domain.com:8080/app/libraries"), HttpMethod.PUT); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + assertTrue(request.getHeaders().isEmpty()); + + request.addHeaderValues(HttpHeader.CONTENT_TYPE.getName(), MediaType.APPLICATION_JSON_VALUE); + request.addHeaderValues(HttpHeader.ACCEPT.getName(), MediaType.APPLICATION_JSON_VALUE, + MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_PLAIN_VALUE); + + assertEquals(MediaType.APPLICATION_JSON_VALUE, request.getHeaderValue(HttpHeader.CONTENT_TYPE.getName())); + assertEquals(1, request.getHeaderValues(HttpHeader.CONTENT_TYPE.getName()).size()); + assertEquals(MediaType.APPLICATION_JSON_VALUE, request.getHeaderValue(HttpHeader.ACCEPT.getName())); + assertEquals(3, request.getHeaderValues(HttpHeader.ACCEPT.getName()).size()); + assertTrue(request.getHeaderValues(HttpHeader.ACCEPT.getName()).containsAll(Arrays.asList( + MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_PLAIN_VALUE))); + + request.setHeader(HttpHeader.ACCEPT.getName(), MediaType.APPLICATION_OCTET_STREAM_VALUE); + + assertEquals(MediaType.APPLICATION_OCTET_STREAM_VALUE, request.getHeaderValue(HttpHeader.ACCEPT.getName())); + assertEquals(1, request.getHeaderValues(HttpHeader.ACCEPT.getName()).size()); + assertTrue(request.getHeaderValues(HttpHeader.ACCEPT.getName()).containsAll(Arrays.asList( + MediaType.APPLICATION_OCTET_STREAM_VALUE))); + } + + @Test + public void testSetAndGetParameterValues() throws Exception { + final Link expectedLink = new Link("put", toUri("http://host.domain.com:8080/app/libraries"), HttpMethod.PUT); + final ClientHttpRequest request = new ClientHttpRequest(expectedLink); + + assertEquals(expectedLink, request.getLink()); + assertTrue(request.getParameters().isEmpty()); + + request.addParameterValues("parameterOne", "value"); + request.addParameterValues("parameterTwo", "test", "testing", "tested"); + + assertEquals("value", request.getParameterValue("parameterOne")); + assertEquals(1, request.getParameterValues("parameterOne").size()); + assertEquals("test", request.getParameterValue("parameterTwo")); + assertEquals(3, request.getParameterValues("parameterTwo").size()); + assertTrue(request.getParameterValues("parameterTwo").containsAll(Arrays.asList("test", "testing", "tested"))); + + request.setParameter("parameterTwo", "development"); + + assertEquals("development", request.getParameterValue("parameterTwo")); + assertEquals(1, request.getParameterValues("parameterTwo").size()); + assertTrue(request.getParameterValues("parameterTwo").containsAll(Arrays.asList("development"))); + } + + @SuppressWarnings("unused") + private static interface Library { + public String getName(); + } + + @SuppressWarnings("unused") + private static interface Book { + public String getAuthor(); + public String getIsbn(); + public String getTitle(); + public Integer getYear(); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java new file mode 100644 index 0000000..9ecf645 --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java @@ -0,0 +1,165 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF 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 com.gemstone.gemfire.management.internal.web.http.converter; + +import static org.junit.Assert.*; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.Serializable; +import java.util.Calendar; + +import org.jmock.Expectations; +import org.jmock.Mockery; +import org.jmock.lib.legacy.ClassImposteriser; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.MediaType; + +import com.gemstone.gemfire.internal.util.IOUtils; +import com.gemstone.gemfire.test.junit.categories.UnitTest; + +/** + * The SerializableObjectHttpMessageConverterJUnitTest class is a test suite of test cases testing the contract + * and functionality of the SerializableObjectHttpMessageConverter class. + * <p/> + * @see com.gemstone.gemfire.management.internal.web.http.converter.SerializableObjectHttpMessageConverter + * @see org.jmock.Mockery + * @see org.junit.Assert + * @see org.junit.Test + * @since GemFire 8.0 + */ +@Category(UnitTest.class) +public class SerializableObjectHttpMessageConverterJUnitTest { + + private Mockery mockContext; + + @Before + public void setUp() { + mockContext = new Mockery(); + mockContext.setImposteriser(ClassImposteriser.INSTANCE); + } + + @After + public void tearDown() { + mockContext.assertIsSatisfied(); + mockContext = null; + } + + @Test + public void testCreateSerializableObjectHttpMessageConverter() { + final SerializableObjectHttpMessageConverter converter = new SerializableObjectHttpMessageConverter(); + + assertNotNull(converter); + assertTrue(converter.getSupportedMediaTypes().contains(MediaType.APPLICATION_OCTET_STREAM)); + assertTrue(converter.getSupportedMediaTypes().contains(MediaType.ALL)); + } + + @Test + public void testSupport() { + final SerializableObjectHttpMessageConverter converter = new SerializableObjectHttpMessageConverter(); + + assertTrue(converter.supports(Boolean.class)); + assertTrue(converter.supports(Calendar.class)); + assertTrue(converter.supports(Character.class)); + assertTrue(converter.supports(Integer.class)); + assertTrue(converter.supports(Double.class)); + assertTrue(converter.supports(String.class)); + assertTrue(converter.supports(Serializable.class)); + assertFalse(converter.supports(Object.class)); + assertFalse(converter.supports(null)); + } + + @Test + public void testReadInternal() throws IOException { + final String expectedInputMessageBody = "Expected content of the HTTP input message body!"; + + final HttpInputMessage mockInputMessage = mockContext.mock(HttpInputMessage.class, "HttpInputMessage"); + + mockContext.checking(new Expectations() {{ + oneOf(mockInputMessage).getBody(); + will(returnValue(new ByteArrayInputStream(IOUtils.serializeObject(expectedInputMessageBody)))); + }}); + + final SerializableObjectHttpMessageConverter converter = new SerializableObjectHttpMessageConverter(); + + final Serializable obj = converter.readInternal(String.class, mockInputMessage); + + assertTrue(obj instanceof String); + assertEquals(expectedInputMessageBody, obj); + } + + @Test + public void testSetContentLength() { + final byte[] bytes = { (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE }; + + final HttpHeaders headers = new HttpHeaders(); + + final HttpOutputMessage mockOutputMessage = mockContext.mock(HttpOutputMessage.class, "HttpOutputMessage"); + + mockContext.checking(new Expectations() {{ + oneOf(mockOutputMessage).getHeaders(); + will(returnValue(headers)); + }}); + + final SerializableObjectHttpMessageConverter converter = new SerializableObjectHttpMessageConverter(); + + converter.setContentLength(mockOutputMessage, bytes); + + assertEquals(bytes.length, headers.getContentLength()); + } + + @Test + public void testWriteInternal() throws IOException { + final String expectedOutputMessageBody = "Expected media of the HTTP output message body!"; + + final byte[] expectedOutputMessageBodyBytes = IOUtils.serializeObject(expectedOutputMessageBody); + + final ByteArrayOutputStream out = new ByteArrayOutputStream(expectedOutputMessageBodyBytes.length); + + final HttpHeaders headers = new HttpHeaders(); + + final HttpOutputMessage mockOutputMessage = mockContext.mock(HttpOutputMessage.class, "HttpOutputMessage"); + + mockContext.checking(new Expectations() {{ + oneOf(mockOutputMessage).getHeaders(); + will(returnValue(headers)); + oneOf(mockOutputMessage).getBody(); + will(returnValue(out)); + }}); + + final SerializableObjectHttpMessageConverter converter = new SerializableObjectHttpMessageConverter(); + + converter.writeInternal(expectedOutputMessageBody, mockOutputMessage); + + final byte[] actualOutputMessageBodyBytes = out.toByteArray(); + + assertEquals(expectedOutputMessageBodyBytes.length, headers.getContentLength()); + assertEquals(expectedOutputMessageBodyBytes.length, actualOutputMessageBodyBytes.length); + + for (int index = 0; index < actualOutputMessageBodyBytes.length; index++) { + assertEquals(expectedOutputMessageBodyBytes[index], actualOutputMessageBodyBytes[index]); + } + } + +}
