http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/http/ClientHttpRequestJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/http/ClientHttpRequestJUnitTest.java b/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/http/ClientHttpRequestJUnitTest.java deleted file mode 100644 index bbe961b..0000000 --- a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/http/ClientHttpRequestJUnitTest.java +++ /dev/null @@ -1,509 +0,0 @@ -/* - * 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/com/gemstone/gemfire/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java b/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java deleted file mode 100644 index 9ecf645..0000000 --- a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * 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]); - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/shell/RestHttpOperationInvokerJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/shell/RestHttpOperationInvokerJUnitTest.java b/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/shell/RestHttpOperationInvokerJUnitTest.java deleted file mode 100644 index b11125c..0000000 --- a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/shell/RestHttpOperationInvokerJUnitTest.java +++ /dev/null @@ -1,453 +0,0 @@ -/* - * 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.shell; - -import static org.junit.Assert.*; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.ResourceAccessException; - -import com.gemstone.gemfire.internal.lang.StringUtils; -import com.gemstone.gemfire.management.internal.cli.CommandRequest; -import com.gemstone.gemfire.management.internal.web.AbstractWebTestCase; -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.http.ClientHttpRequest; -import com.gemstone.gemfire.management.internal.web.http.HttpMethod; -import com.gemstone.gemfire.test.junit.categories.UnitTest; - -/** - * The RestHttpOperationInvokerJUnitTest class is a test suite of test cases testing the contract and functionality of the - * RestHttpOperationInvoker class. - * <p/> - * @see java.net.URI - * @see com.gemstone.gemfire.management.internal.cli.CommandRequest - * @see com.gemstone.gemfire.management.internal.web.http.HttpMethod - * @see com.gemstone.gemfire.management.internal.web.domain.Link - * @see com.gemstone.gemfire.management.internal.web.domain.LinkIndex - * @see com.gemstone.gemfire.management.internal.web.shell.RestHttpOperationInvoker - * @see org.junit.Assert - * @see org.junit.Test - * @since GemFire 8.0 - */ -@SuppressWarnings("unused") -@Category(UnitTest.class) -public class RestHttpOperationInvokerJUnitTest extends AbstractWebTestCase { - - private LinkIndex linkIndex; - - private RestHttpOperationInvoker operationInvoker; - - @Before - public void setUp() throws Exception { - final Link listLibraries = new Link("list-libraries", toUri("http://host.domain.com/service/v1/libraries")); - final Link getLibrary = new Link("get-library", toUri("http://host.domain.com/service/v1/libraries/{name}")); - final Link listBooks = new Link("list-books", toUri("http://host.domain.com/service/v1/libraries/{name}/books")); - final Link listBooksByAuthor = new Link("list-books", toUri("http://host.domain.com/service/v1/libraries/{name}/books/{author}")); - final Link listBooksByAuthorAndCategory = new Link("list-books", toUri("http://host.domain.com/service/v1/libraries/{name}/books/{author}/{category}")); - final Link listBooksByAuthorAndYear = new Link("list-books", toUri("http://host.domain.com/service/v1/libraries/{name}/books/{author}/{year}")); - final Link listBooksByAuthorCategoryAndYear = new Link("list-books", toUri("http://host.domain.com/service/v1/libraries/{name}/books/{author}/{category}/{year}")); - final Link addBook = new Link("add-book", toUri("http://host.domain.com/service/v1/libraries/{name}/books"), HttpMethod.POST); - final Link getBookByIsbn = new Link("get-book", toUri("http://host.domain.com/service/v1/libraries/{name}/books/{isbn}")); - final Link getBookByTitle = new Link("get-book", toUri("http://host.domain.com/service/v1/libraries/{name}/books/{title}")); - final Link removeBook = new Link("remove-book", toUri("http://host.domain.com/service/v1/libraries/{name}/books/{isbn}"), HttpMethod.DELETE); - - linkIndex = new LinkIndex(); - - linkIndex.addAll( - listLibraries, - getLibrary, - listBooks, - listBooksByAuthor, - listBooksByAuthorAndCategory, - listBooksByAuthorAndYear, - listBooksByAuthorCategoryAndYear, - addBook, - getBookByIsbn, - getBookByTitle, - removeBook - ); - - assertEquals(11, linkIndex.size()); - - operationInvoker = new RestHttpOperationInvoker(linkIndex); - - assertSame(linkIndex, operationInvoker.getLinkIndex()); - } - - @After - public void tearDown() { - operationInvoker.stop(); - operationInvoker = null; - } - - private CommandRequest createCommandRequest(final String command, final Map<String, String> options) { - return new TestCommandRequest(command, options, Collections.<String, String>emptyMap(), null); - } - - private CommandRequest createCommandRequest(final String command, final Map<String, String> options, final Map<String, String> environment) { - return new TestCommandRequest(command, options, environment, null); - } - - private CommandRequest createCommandRequest(final String command, final Map<String, String> options, final byte[][] fileData) { - return new TestCommandRequest(command, options, Collections.<String, String>emptyMap(), fileData); - } - - private CommandRequest createCommandRequest(final String command, final Map<String, String> options, final Map<String, String> environment, final byte[][] fileData) { - return new TestCommandRequest(command, options, environment, fileData); - } - - private LinkIndex getLinkIndex() { - assertTrue("The LinkIndex was not property initialized!", linkIndex != null); - return linkIndex; - } - - private RestHttpOperationInvoker getOperationInvoker() { - assertTrue("The RestHttpOperationInvoker was not properly initialized!", operationInvoker != null); - return operationInvoker; - } - - @Test - public void testCreateHttpRequest() { - final Map<String, String> commandOptions = new HashMap<String, String>(); - - commandOptions.put("author", "Adams"); - commandOptions.put("blankOption", " "); - commandOptions.put("category", "sci-fi"); - commandOptions.put("emptyOption", StringUtils.EMPTY_STRING); - commandOptions.put("isbn", "0-123456789"); - commandOptions.put("nullOption", null); - commandOptions.put("title", "Hitch Hiker's Guide to the Galaxy"); - commandOptions.put("year", "1983"); - - final CommandRequest command = createCommandRequest("add-book", commandOptions); - - final ClientHttpRequest request = getOperationInvoker().createHttpRequest(command); - - assertNotNull(request); - assertEquals("POST http://host.domain.com/service/v1/libraries/{name}/books", request.getLink().toHttpRequestLine()); - assertEquals("Adams", request.getParameterValue("author")); - assertEquals("sci-fi", request.getParameterValue("category")); - assertEquals("0-123456789", request.getParameterValue("isbn")); - assertEquals("Hitch Hiker's Guide to the Galaxy", request.getParameterValue("title")); - assertEquals("1983", request.getParameterValue("year")); - assertTrue(request.getParameters().containsKey("blankOption")); - assertTrue(request.getParameters().containsKey("emptyOption")); - assertFalse(request.getParameters().containsKey("nullOption")); - - for (String requestParameter : request.getParameters().keySet()) { - assertFalse(requestParameter.startsWith(RestHttpOperationInvoker.ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX)); - } - - assertNull(request.getParameterValue(RestHttpOperationInvoker.RESOURCES_REQUEST_PARAMETER)); - } - - @Test - public void testCreateHttpRequestWithEnvironmentVariables() { - final Map<String, String> commandOptions = new HashMap<String, String>(2); - - commandOptions.put("name", "ElLibreDeCongress"); - commandOptions.put("isbn", "${ISBN}"); - - final Map<String, String> environment = new HashMap<String, String>(2); - - environment.put("ISBN", "0-987654321"); - environment.put("VAR", "test"); - - final CommandRequest command = createCommandRequest("get-book", commandOptions, environment); - - final ClientHttpRequest request = getOperationInvoker().createHttpRequest(command); - - assertNotNull(request); - assertEquals("GET http://host.domain.com/service/v1/libraries/{name}/books/{isbn}", request.getLink() - .toHttpRequestLine()); - assertEquals("${ISBN}", request.getParameterValue("isbn")); - assertFalse(request.getParameters().containsKey("ISBN")); - assertEquals("0-987654321", request.getParameterValue( - RestHttpOperationInvoker.ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "ISBN")); - assertFalse(request.getParameters().containsKey("VAR")); - assertEquals("test", request.getParameterValue( - RestHttpOperationInvoker.ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "VAR")); - } - - @Test - public void testCreatHttpRequestWithFileData() { - final Map<String, String> commandOptions = Collections.singletonMap("isbn", "0-123456789"); - - final byte[][] fileData = { - "/path/to/book/content.txt".getBytes(), - "Once upon a time in a galaxy far, far away...".getBytes() - }; - - final CommandRequest command = createCommandRequest("add-book", commandOptions, fileData); - - final ClientHttpRequest request = getOperationInvoker().createHttpRequest(command); - - assertNotNull(request); - assertEquals("POST http://host.domain.com/service/v1/libraries/{name}/books", request.getLink().toHttpRequestLine()); - assertEquals("0-123456789", request.getParameterValue("isbn")); - assertTrue(request.getParameters().containsKey(RestHttpOperationInvoker.RESOURCES_REQUEST_PARAMETER)); - assertTrue(request.getParameterValue(RestHttpOperationInvoker.RESOURCES_REQUEST_PARAMETER) instanceof Resource); - - final List<Object> resources = request.getParameterValues(RestHttpOperationInvoker.RESOURCES_REQUEST_PARAMETER); - - assertNotNull(resources); - assertFalse(resources.isEmpty()); - assertEquals(1, resources.size()); - } - - @Test - public void testFindAndResolveLink() throws Exception { - final Map<String, String> commandOptions = new HashMap<String, String>(); - - commandOptions.put("name", "BarnesN'Noble"); - - Link link = getOperationInvoker().findLink(createCommandRequest("list-libraries", commandOptions)); - - assertNotNull(link); - assertEquals("http://host.domain.com/service/v1/libraries", toString(link.getHref())); - - link = getOperationInvoker().findLink(createCommandRequest("get-library", commandOptions)); - - assertNotNull(link); - assertEquals("http://host.domain.com/service/v1/libraries/{name}", toString(link.getHref())); - - commandOptions.put("author", "J.K.Rowlings"); - - link = getOperationInvoker().findLink(createCommandRequest("list-books", commandOptions)); - - assertNotNull(link); - assertEquals("http://host.domain.com/service/v1/libraries/{name}/books/{author}", toString(link.getHref())); - - commandOptions.put("category", "sci-fi"); - commandOptions.put("year", "1998"); - commandOptions.put("bogus", "data"); - - link = getOperationInvoker().findLink(createCommandRequest("list-books", commandOptions)); - - assertNotNull(link); - assertEquals("http://host.domain.com/service/v1/libraries/{name}/books/{author}/{category}/{year}", - toString(link.getHref())); - - commandOptions.remove("category"); - - link = getOperationInvoker().findLink(createCommandRequest("list-books", commandOptions)); - - assertNotNull(link); - assertEquals("http://host.domain.com/service/v1/libraries/{name}/books/{author}/{year}", - toString(link.getHref())); - - commandOptions.put("category", "fantasy"); - commandOptions.put("isbn", "0-123456789"); - commandOptions.put("title", "Harry Potter"); - - link = getOperationInvoker().findLink(createCommandRequest("add-book", commandOptions)); - - assertNotNull(link); - assertEquals("http://host.domain.com/service/v1/libraries/{name}/books", toString(link.getHref())); - - commandOptions.remove("isbn"); - - link = getOperationInvoker().findLink(createCommandRequest("get-book", commandOptions)); - - assertNotNull(link); - assertEquals("http://host.domain.com/service/v1/libraries/{name}/books/{title}", toString(link.getHref())); - - link = getOperationInvoker().findLink(createCommandRequest("remove-book", commandOptions)); - - assertNotNull(link); - assertEquals("http://host.domain.com/service/v1/libraries/{name}/books/{isbn}", toString(link.getHref())); - } - - @Test - public void testProcessCommand() { - final String expectedResult = "{\"libraries\":[{\"library-of\":\"Congress\"}]"; // JSON - - final RestHttpOperationInvoker operationInvoker = new RestHttpOperationInvoker(getLinkIndex()) { - @Override - public boolean isConnected() { - return true; - } - - @Override - @SuppressWarnings("unchecked") - protected <T> ResponseEntity<T> send(final ClientHttpRequest request, final Class<T> responseType, final Map<String, ?> uriVariables) { - return new ResponseEntity(expectedResult, HttpStatus.OK); - } - }; - - final String actualResult = operationInvoker.processCommand(createCommandRequest("list-libraries", - Collections.<String, String>emptyMap())); - - assertEquals(expectedResult, actualResult); - } - - @Test - public void testProcessCommandDelegatesToSimpleProcessCommand() { - final String expectedResult = "<resources>test</resources>"; - - final RestHttpOperationInvoker operationInvoker = new RestHttpOperationInvoker(getLinkIndex()) { - @Override - public boolean isConnected() { - return true; - } - - @Override - protected HttpOperationInvoker getHttpOperationInvoker() { - return new AbstractHttpOperationInvoker(AbstractHttpOperationInvoker.REST_API_URL) { - @Override public Object processCommand(final CommandRequest command) { - return expectedResult; - } - }; - } - - @Override - protected void printWarning(final String message, final Object... args) { - } - }; - - final String actualResult = operationInvoker.processCommand(createCommandRequest("get resource", - Collections.<String, String>emptyMap())); - - assertEquals(expectedResult, actualResult); - } - - @Test - public void testProcessCommandHandlesResourceAccessException() { - final RestHttpOperationInvoker operationInvoker = new RestHttpOperationInvoker(getLinkIndex()) { - private boolean connected = true; - - @Override - public boolean isConnected() { - return connected; - } - - @Override - protected void printWarning(final String message, final Object... args) { - } - - @Override - protected <T> ResponseEntity<T> send(final ClientHttpRequest request, final Class<T> responseType, final Map<String, ?> uriVariables) { - throw new ResourceAccessException("test"); - } - - @Override - public void stop() { - this.connected = false; - } - }; - - assertTrue(operationInvoker.isConnected()); - - final String expectedResult = String.format( - "The connection to the GemFire Manager's HTTP service @ %1$s failed with: %2$s. " - + "Please try reconnecting or see the GemFire Manager's log file for further details.", - operationInvoker.getBaseUrl(), "test"); - - final String actualResult = operationInvoker.processCommand(createCommandRequest("list-libraries", - Collections.<String, String>emptyMap())); - - assertFalse(operationInvoker.isConnected()); - assertEquals(expectedResult, actualResult); - } - - @Test(expected = RestApiCallForCommandNotFoundException.class) - public void testProcessCommandThrowsRestApiCallForCommandNotFoundException() { - final RestHttpOperationInvoker operationInvoker = new RestHttpOperationInvoker(getLinkIndex()) { - @Override - public boolean isConnected() { - return true; - } - - @Override - protected HttpOperationInvoker getHttpOperationInvoker() { - return null; - } - }; - - try { - operationInvoker.processCommand(createCommandRequest("get resource", Collections.<String, String>emptyMap())); - } - catch (RestApiCallForCommandNotFoundException e) { - assertEquals("No REST API call for command (get resource) was found!", e.getMessage()); - throw e; - } - } - - @Test(expected = IllegalStateException.class) - public void testProcessCommandWhenNotConnected() { - try { - getOperationInvoker().processCommand(createCommandRequest("get-book", Collections.<String, String>emptyMap())); - } - catch (IllegalStateException e) { - assertEquals("Gfsh must be connected to the GemFire Manager in order to process commands remotely!", - e.getMessage()); - throw e; - } - } - - private static final class TestCommandRequest extends CommandRequest { - - private final Map<String, String> commandParameters = new TreeMap<String, String>(); - - private final String command; - - protected TestCommandRequest(final String command, - final Map<String, String> commandParameters, - final Map<String, String> environment, - final byte[][] fileData) - { - super(environment, fileData); - - assert command != null : "The command cannot be null!"; - - this.command = command; - - if (commandParameters != null) { - this.commandParameters.putAll(commandParameters); - } - } - - @Override - public String getInput() { - return command; - } - - @Override - public String getName() { - return command; - } - - @Override - public Map<String, String> getParameters() { - return Collections.unmodifiableMap(commandParameters); - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/shell/SimpleHttpOperationInvokerJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/shell/SimpleHttpOperationInvokerJUnitTest.java b/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/shell/SimpleHttpOperationInvokerJUnitTest.java deleted file mode 100644 index 557cc20..0000000 --- a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/shell/SimpleHttpOperationInvokerJUnitTest.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * 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.shell; - -import static org.junit.Assert.*; - -import java.util.Collections; - -import com.gemstone.gemfire.management.internal.cli.CommandRequest; -import com.gemstone.gemfire.management.internal.web.AbstractWebTestCase; -import com.gemstone.gemfire.management.internal.web.domain.Link; -import com.gemstone.gemfire.management.internal.web.http.ClientHttpRequest; -import com.gemstone.gemfire.management.internal.web.http.HttpHeader; -import com.gemstone.gemfire.management.internal.web.http.HttpMethod; -import com.gemstone.gemfire.test.junit.categories.UnitTest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.ResourceAccessException; - -/** - * The SimpleHttpOperationInvokerJUnitTest class is a test suite of test cases testing the contract and functionality of the - * SimpleHttpOperationInvoker class. - * <p/> - * @see com.gemstone.gemfire.management.internal.web.AbstractWebTestCase - * @see com.gemstone.gemfire.management.internal.web.shell.SimpleHttpOperationInvoker - * @see org.junit.Assert - * @see org.junit.After - * @see org.junit.Before - * @see org.junit.Test - * @since GemFire 8.0 - */ -@Category(UnitTest.class) -public class SimpleHttpOperationInvokerJUnitTest extends AbstractWebTestCase { - - private SimpleHttpOperationInvoker operationInvoker; - - @Before - public void setUp() { - operationInvoker = new SimpleHttpOperationInvoker(); - } - - @After - public void tearDown() { - operationInvoker.stop(); - operationInvoker = null; - } - - private CommandRequest createCommandRequest(final String command) { - return new TestCommandRequest(command); - } - - private String getExpectedHttpRequestUrl(final CommandRequest command) { - return SimpleHttpOperationInvoker.REST_API_URL.concat(SimpleHttpOperationInvoker.REST_API_MANAGEMENT_COMMANDS_URI) - .concat("?").concat(SimpleHttpOperationInvoker.CMD_QUERY_PARAMETER).concat("=").concat(command.getInput()); - } - - private SimpleHttpOperationInvoker getOperationInvoker() { - return operationInvoker; - } - - @Test - public void testCreateHttpRequest() throws Exception { - final CommandRequest command = createCommandRequest("save resource --path=/path/to/file --size=1024KB"); - - final ClientHttpRequest request = getOperationInvoker().createHttpRequest(command); - - assertNotNull(request); - assertEquals(SimpleHttpOperationInvoker.USER_AGENT_HTTP_REQUEST_HEADER_VALUE, - request.getHeaderValue(HttpHeader.USER_AGENT.getName())); - - final Link requestLink = request.getLink(); - - assertNotNull(requestLink); - assertTrue(toString(requestLink).startsWith("POST")); - assertTrue(toString(requestLink).endsWith(command.getInput())); - } - - @Test - public void testCreateLink() throws Exception { - final CommandRequest command = createCommandRequest("delete resource --id=1"); - - final Link actualLink = getOperationInvoker().createLink(command); - - assertNotNull(actualLink); - assertEquals(SimpleHttpOperationInvoker.LINK_RELATION, actualLink.getRelation()); - assertEquals(HttpMethod.POST, actualLink.getMethod()); - assertTrue(toString(actualLink.getHref()).endsWith(command.getInput())); - } - - @Test - public void testGetHttpRequestUrl() throws Exception { - final CommandRequest command = createCommandRequest("get resource --option=value"); - - assertEquals(getExpectedHttpRequestUrl(command), toString(getOperationInvoker().getHttpRequestUrl(command))); - } - - @Test - public void testProcessCommand() { - final String expectedResult = "<resource>test</resource>"; // XML - - final SimpleHttpOperationInvoker operationInvoker = new SimpleHttpOperationInvoker() { - @Override - public boolean isConnected() { - return true; - } - - @Override - @SuppressWarnings("unchecked") - protected <T> ResponseEntity<T> send(final ClientHttpRequest request, final Class<T> responseType) { - return new ResponseEntity(expectedResult, HttpStatus.OK); - } - }; - - final String actualResult = operationInvoker.processCommand(createCommandRequest("get resource --id=1")); - - assertEquals(expectedResult, actualResult); - } - - @Test - public void testProcessCommandHandlesResourceAccessException() { - final SimpleHttpOperationInvoker operationInvoker = new SimpleHttpOperationInvoker() { - private boolean connected = true; - @Override - public boolean isConnected() { - return connected; - } - - @Override - protected <T> ResponseEntity<T> send(final ClientHttpRequest request, final Class<T> responseType) { - throw new ResourceAccessException("test"); - } - - @Override public void stop() { - this.connected = false; - } - }; - - assertTrue(operationInvoker.isConnected()); - - final String expectedResult = String.format( - "The connection to the GemFire Manager's HTTP service @ %1$s failed with: %2$s. " - + "Please try reconnecting or see the GemFire Manager's log file for further details.", - operationInvoker.getBaseUrl(), "test"); - - final String actualResult = operationInvoker.processCommand(createCommandRequest("get resource --id=1")); - - assertFalse(operationInvoker.isConnected()); - assertEquals(expectedResult, actualResult); - } - - @Test(expected = IllegalStateException.class) - public void testProcessCommandWhenNotConnected() { - try { - getOperationInvoker().processCommand(createCommandRequest("get resource")); - } - catch (IllegalStateException e) { - assertEquals("Gfsh must be connected to the GemFire Manager in order to process commands remotely!", - e.getMessage()); - throw e; - } - } - - private static final class TestCommandRequest extends CommandRequest { - - private final String command; - - protected TestCommandRequest(final String command) { - super(Collections.<String, String>emptyMap()); - assert command != null : "The command cannot be null!"; - this.command = command; - } - - @Override - public String getInput() { - return command; - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/util/ConvertUtilsJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/util/ConvertUtilsJUnitTest.java b/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/util/ConvertUtilsJUnitTest.java deleted file mode 100644 index d9eb8e5..0000000 --- a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/util/ConvertUtilsJUnitTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * 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.util; - -import static org.junit.Assert.*; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import com.gemstone.gemfire.internal.util.IOUtils; -import com.gemstone.gemfire.management.internal.web.io.MultipartFileAdapter; -import com.gemstone.gemfire.test.junit.categories.UnitTest; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.core.io.Resource; -import org.springframework.web.multipart.MultipartFile; - -/** - * The ConvertUtilsJUnitTest class is a test suite testing the contract and functionality of the ConvertUtilsJUnitTest class. - * <p/> - * @see com.gemstone.gemfire.management.internal.web.util.ConvertUtils - * @see org.junit.Assert - * @see org.junit.Test - * @since GemFire 8.0 - */ -@Category(UnitTest.class) -public class ConvertUtilsJUnitTest { - - private MultipartFile createMultipartFile(final String filename, final byte[] content) { - return new MultipartFileAdapter() { - @Override public byte[] getBytes() throws IOException { - return content; - } - @Override public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream(getBytes()); - } - @Override public String getName() { - return filename; - } - @Override public String getOriginalFilename() { - return filename; - } - @Override public long getSize() { - return content.length; - } - }; - } - - private Resource createResource(final String filename, final byte[] content) { - return new ByteArrayResource(content, String.format("Content of file (%1$s).", filename)) { - @Override public String getFilename() { - return filename; - } - }; - } - - @Test - public void testConvertFileData() throws IOException { - final String[] filenames = { "/path/to/file1.ext", "/path/to/another/file2.ext" }; - final String[] fileContent = { "This is the contents of file 1.", "This is the contents of file 2." }; - - final List<byte[]> fileData = new ArrayList<byte[]>(2); - - for (int index = 0; index < filenames.length; index++) { - fileData.add(filenames[index].getBytes()); - fileData.add(fileContent[index].getBytes()); - } - - final Resource[] resources = ConvertUtils.convert(fileData.toArray(new byte[fileData.size()][])); - - assertNotNull(resources); - assertEquals(filenames.length, resources.length); - - for (int index = 0; index < resources.length; index++) { - assertEquals(filenames[index], resources[index].getFilename()); - assertEquals(fileContent[index], new String(IOUtils.toByteArray(resources[index].getInputStream()))); - } - } - - @Test - public void testConvertFileDataWithNull() { - final Resource[] resources = ConvertUtils.convert((byte[][]) null); - - assertNotNull(resources); - assertEquals(0, resources.length); - } - - @Test - public void testConvertMultipartFile() throws IOException { - final MultipartFile[] files = { - createMultipartFile("/path/to/multi-part/file1.txt", "The contents of multi-part file1.".getBytes()), - createMultipartFile("/path/to/multi-part/file2.txt", "The contents of multi-part file2.".getBytes()) - }; - - final byte[][] fileData = ConvertUtils.convert(files); - - assertNotNull(fileData); - assertEquals(files.length * 2, fileData.length); - - for (int index = 0; index < fileData.length; index += 2) { - assertEquals(files[index / 2].getOriginalFilename(), new String(fileData[index])); - assertEquals(new String(files[index / 2].getBytes()), new String(fileData[index + 1])); - } - } - - @Test - public void testConvertResource() throws IOException { - final Resource[] resources = { - createResource("/path/to/file1.txt", "Contents of file1.".getBytes()), - createResource("/path/to/file2.txt", "Contents of file2.".getBytes()) - }; - - final byte[][] fileData = ConvertUtils.convert(resources); - - assertNotNull(fileData); - assertEquals(resources.length * 2, fileData.length); - - for (int index = 0; index < fileData.length; index += 2) { - assertEquals(resources[index / 2].getFilename(), new String(fileData[index])); - assertEquals(new String(IOUtils.toByteArray(resources[index / 2].getInputStream())), new String(fileData[index + 1])); - } - } - - @Test(expected = IllegalArgumentException.class) - public void testConvertResourceWithResourceHavingNoFilename() throws IOException { - try { - ConvertUtils.convert(createResource(null, "test".getBytes())); - } - catch (IllegalArgumentException expected) { - assertEquals("The filename of Resource (Byte array resource [Content of file (null).]) must be specified!", expected.getMessage()); - throw expected; - } - } - - @Test - public void testConvertResourceWithEmpty() throws IOException { - final byte[][] fileData = ConvertUtils.convert(new Resource[0]); - - assertNotNull(fileData); - assertEquals(0, fileData.length); - } - - @Test - public void testConvertResourceWithNull() throws IOException { - final byte[][] fileData = ConvertUtils.convert((Resource[]) null); - - assertNotNull(fileData); - assertEquals(0, fileData.length); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/util/UriUtilsJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/util/UriUtilsJUnitTest.java b/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/util/UriUtilsJUnitTest.java deleted file mode 100644 index 645133a..0000000 --- a/geode-web/src/test/java/com/gemstone/gemfire/management/internal/web/util/UriUtilsJUnitTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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.util; - -import static org.junit.Assert.*; - -import java.util.Map; - -import com.gemstone.gemfire.management.internal.web.AbstractWebTestCase; -import com.gemstone.gemfire.test.junit.categories.UnitTest; - -import org.junit.Test; -import org.junit.experimental.categories.Category; - -/** - * The UriUtilsJUnitTest class is a test suite of test cases testing the contract and functionality of the UriUtils class. - * <p/> - * @see com.gemstone.gemfire.management.internal.web.AbstractWebTestCase - * @see com.gemstone.gemfire.management.internal.web.util.UriUtils - * @see org.junit.Assert - * @see org.junit.Test - * @since GemFire 8.0 - */ -@Category(UnitTest.class) -public class UriUtilsJUnitTest extends AbstractWebTestCase { - - @Test - public void testDecodeNull() { - assertNull(UriUtils.decode((String) null)); - } - - @Test - public void testDecodeStringArray() throws Exception { - final String[] encodedValues = { - null, - "123", - "test", - encode("Path/Subpath"), - encode(encode(encode("/Customers/Accounts/Orders/Items"))) - }; - - final String[] decodedValues = UriUtils.decode(encodedValues); - - assertSame(encodedValues, decodedValues); - assertEquals(5, decodedValues.length); - assertNull(decodedValues[0]); - assertEquals("123", decodedValues[1]); - assertEquals("test", decodedValues[2]); - assertEquals("Path/Subpath", decodedValues[3]); - assertEquals("/Customers/Accounts/Orders/Items", decodedValues[4]); - } - - @Test - public void testDecodeMap() throws Exception { - final Map<String, Object> encodedForm = createMap(createArray("0", "1", "2", "3", "4"), - (Object[]) createArray(null, "123", "test", encode("Path/Subpath"), encode(encode(encode("/Customers/Accounts/Orders/Items"))))); - - final Map<String, Object> decodedForm = UriUtils.decode(encodedForm); - - assertSame(encodedForm, decodedForm); - assertEquals(5, decodedForm.size()); - assertNull(decodedForm.get("0")); - assertEquals("123", decodedForm.get("1")); - assertEquals("test", decodedForm.get("2")); - assertEquals("Path/Subpath", decodedForm.get("3")); - assertEquals("/Customers/Accounts/Orders/Items", decodedForm.get("4")); - } - - @Test - public void testEncodeNull() { - assertNull(UriUtils.encode((String) null)); - } - - @Test - public void testEncodeStringArray() throws Exception { - final String[] values = { null, "123", "test", "Path/Subpath", "/Customers/Accounts/Orders/Items" }; - final String[] encodedValues = UriUtils.encode(values); - - assertSame(values, encodedValues); - assertEquals(5, encodedValues.length); - assertNull(encodedValues[0]); - assertEquals("123", encodedValues[1]); - assertEquals("test", encodedValues[2]); - assertEquals(encode("Path/Subpath"), encodedValues[3]); - assertEquals(encode("/Customers/Accounts/Orders/Items"), encodedValues[4]); - } - - @Test - public void testEncodeMap() throws Exception { - final Map<String, Object> form = createMap(createArray("0", "1", "2", "3", "4"), - (Object[]) createArray(null, "123", "test", "Path/Subpath", "/Customers/Accounts/Orders/Items")); - - final Map<String, Object> encodedForm = UriUtils.encode(form); - - assertSame(form, encodedForm); - assertEquals(5, encodedForm.size()); - assertNull(encodedForm.get("0")); - assertEquals("123", encodedForm.get("1")); - assertEquals("test", encodedForm.get("2")); - assertEquals(encode("Path/Subpath"), encodedForm.get("3")); - assertEquals(encode("/Customers/Accounts/Orders/Items"), encodedForm.get("4")); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/CommandOverHttpDUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/CommandOverHttpDUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/CommandOverHttpDUnitTest.java new file mode 100644 index 0000000..2f5348f --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/CommandOverHttpDUnitTest.java @@ -0,0 +1,58 @@ +/* + * 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 org.junit.ClassRule; +import org.junit.contrib.java.lang.system.ProvideSystemProperty; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +import com.gemstone.gemfire.test.junit.categories.DistributedTest; +import com.gemstone.gemfire.test.junit.categories.SecurityTest; +import com.gemstone.gemfire.test.junit.runner.SuiteRunner; + +@Category({ DistributedTest.class, SecurityTest.class }) +@RunWith(SuiteRunner.class) +@Suite.SuiteClasses({ + ConfigCommandsDUnitTest.class, + DeployCommandsDUnitTest.class, + DiskStoreCommandsDUnitTest.class, + FunctionCommandsDUnitTest.class, + GemfireDataCommandsDUnitTest.class, + GetCommandOnRegionWithCacheLoaderDuringCacheMissDUnitTest.class, + IndexCommandsDUnitTest.class, + ListAndDescribeDiskStoreCommandsDUnitTest.class, + ListIndexCommandDUnitTest.class, + MemberCommandsDUnitTest.class, + MiscellaneousCommandsDUnitTest.class, + MiscellaneousCommandsExportLogsPart1DUnitTest.class, + MiscellaneousCommandsExportLogsPart2DUnitTest.class, + MiscellaneousCommandsExportLogsPart3DUnitTest.class, + MiscellaneousCommandsExportLogsPart4DUnitTest.class, + QueueCommandsDUnitTest.class, + SharedConfigurationCommandsDUnitTest.class, + ShellCommandsDUnitTest.class, + ShowDeadlockDUnitTest.class, + ShowMetricsDUnitTest.class, + ShowStackTraceDUnitTest.class, + UserCommandsDUnitTest.class +}) +public class CommandOverHttpDUnitTest { + @ClassRule + public static ProvideSystemProperty provideSystemProperty = new ProvideSystemProperty(CliCommandTestBase.USE_HTTP_SYSTEM_PROPERTY, "true"); +} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithHttpAndSSLDUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithHttpAndSSLDUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithHttpAndSSLDUnitTest.java new file mode 100644 index 0000000..dab762b --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ConnectCommandWithHttpAndSSLDUnitTest.java @@ -0,0 +1,319 @@ +/* + * 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.distributed.ConfigurationProperties.*; +import static com.gemstone.gemfire.management.internal.cli.i18n.CliStrings.*; +import static com.gemstone.gemfire.util.test.TestUtil.*; +import static org.junit.Assert.*; + +import java.io.File; +import java.util.Arrays; +import java.util.Collection; +import java.util.Properties; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSession; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import com.gemstone.gemfire.management.internal.cli.HeadlessGfsh; +import com.gemstone.gemfire.management.internal.cli.result.CommandResult; +import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder; +import com.gemstone.gemfire.test.junit.categories.DistributedTest; +import com.gemstone.gemfire.test.junit.categories.SecurityTest; +import com.gemstone.gemfire.test.junit.runners.CategoryWithParameterizedRunnerFactory; + +/** + * @since GemFire 8.1 + */ +@Category({ DistributedTest.class, SecurityTest.class }) +@RunWith(Parameterized.class) +@Parameterized.UseParametersRunnerFactory(CategoryWithParameterizedRunnerFactory.class) +public class ConnectCommandWithHttpAndSSLDUnitTest extends CliCommandTestBase { + + private static final ThreadLocal<Properties> sslInfoHolder = new ThreadLocal<>(); + + private File jks; + + @Parameterized.Parameter + public String urlContext; + + @Parameterized.Parameters + public static Collection<String> data() { + return Arrays.asList("/geode-mgmt", "/gemfire"); + } + + @Override + public final void postSetUpCliCommandTestBase() throws Exception { + this.jks = new File(getResourcePath(getClass(), "/ssl/trusted.keystore")); + } + + @Override + protected final void preTearDownCliCommandTestBase() throws Exception { + destroyDefaultSetup(); + } + + @Override + public final void postTearDownCacheTestCase() throws Exception { + sslInfoHolder.set(null); + } + + @Test + public void testMutualAuthentication() throws Exception { + Properties serverProps = new Properties(); + serverProps.setProperty(HTTP_SERVICE_SSL_ENABLED, "true"); + serverProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE, jks.getCanonicalPath()); + serverProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_PASSWORD, "password"); + serverProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_TYPE, "JKS"); + serverProps.setProperty(HTTP_SERVICE_SSL_PROTOCOLS, "SSL"); + serverProps.setProperty(HTTP_SERVICE_SSL_REQUIRE_AUTHENTICATION, "true"); + serverProps.setProperty(HTTP_SERVICE_SSL_TRUSTSTORE, jks.getCanonicalPath()); + serverProps.setProperty(HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD, "password"); + + Properties clientProps = new Properties(); + clientProps.setProperty(CONNECT__KEY_STORE, jks.getCanonicalPath()); + clientProps.setProperty(CONNECT__KEY_STORE_PASSWORD, "password"); + clientProps.setProperty(CONNECT__SSL_PROTOCOLS, "SSL"); + clientProps.setProperty(CONNECT__TRUST_STORE, jks.getCanonicalPath()); + clientProps.setProperty(CONNECT__TRUST_STORE_PASSWORD, "password"); + + sslInfoHolder.set(clientProps); + setUpJmxManagerOnVm0ThenConnect(serverProps); + } + + @Test + public void testSimpleSSL() throws Exception { + Properties serverProps = new Properties(); + serverProps.setProperty(HTTP_SERVICE_SSL_ENABLED, "true"); + serverProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE, jks.getCanonicalPath()); + serverProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_PASSWORD, "password"); + serverProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_TYPE, "JKS"); + + Properties clientProps = new Properties(); + clientProps.setProperty(CONNECT__TRUST_STORE, jks.getCanonicalPath()); + clientProps.setProperty(CONNECT__TRUST_STORE_PASSWORD, "password"); + + sslInfoHolder.set(clientProps); + setUpJmxManagerOnVm0ThenConnect(serverProps); + } + + @Test + public void testSSLWithoutKeyStoreType() throws Exception { + Properties localProps = new Properties(); + localProps.setProperty(HTTP_SERVICE_SSL_ENABLED, "true"); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE, jks.getCanonicalPath()); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_PASSWORD, "password"); + + Properties clientProps = new Properties(); + clientProps.setProperty(CONNECT__TRUST_STORE, jks.getCanonicalPath()); + clientProps.setProperty(CONNECT__TRUST_STORE_PASSWORD, "password"); + + sslInfoHolder.set(clientProps); + setUpJmxManagerOnVm0ThenConnect(localProps); + } + + @Test + public void testSSLWithSSLProtocol() throws Exception { + Properties localProps = new Properties(); + localProps.setProperty(HTTP_SERVICE_SSL_ENABLED, "true"); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE, jks.getCanonicalPath()); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_PASSWORD, "password"); + localProps.setProperty(HTTP_SERVICE_SSL_PROTOCOLS, "SSL"); + + Properties clientProps = new Properties(); + clientProps.setProperty(CONNECT__TRUST_STORE, jks.getCanonicalPath()); + clientProps.setProperty(CONNECT__TRUST_STORE_PASSWORD, "password"); + + sslInfoHolder.set(clientProps); + setUpJmxManagerOnVm0ThenConnect(localProps); + } + + @Test + public void testSSLWithTLSProtocol() throws Exception { + Properties localProps = new Properties(); + localProps.setProperty(HTTP_SERVICE_SSL_ENABLED, "true"); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE, jks.getCanonicalPath()); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_PASSWORD, "password"); + localProps.setProperty(HTTP_SERVICE_SSL_PROTOCOLS, "TLS"); + + Properties clientProps = new Properties(); + clientProps.setProperty(CONNECT__TRUST_STORE, jks.getCanonicalPath()); + clientProps.setProperty(CONNECT__TRUST_STORE_PASSWORD, "password"); + + sslInfoHolder.set(clientProps); + setUpJmxManagerOnVm0ThenConnect(localProps); + } + + @Test + public void testSSLWithTLSv11Protocol() throws Exception { + Properties localProps = new Properties(); + localProps.setProperty(HTTP_SERVICE_SSL_ENABLED, "true"); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE, jks.getCanonicalPath()); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_PASSWORD, "password"); + localProps.setProperty(HTTP_SERVICE_SSL_PROTOCOLS, "TLSv1.1"); + + Properties clientProps = new Properties(); + clientProps.setProperty(CONNECT__TRUST_STORE, jks.getCanonicalPath()); + clientProps.setProperty(CONNECT__TRUST_STORE_PASSWORD, "password"); + + sslInfoHolder.set(clientProps); + setUpJmxManagerOnVm0ThenConnect(localProps); + } + + @Test + public void testSSLWithTLSv12Protocol() throws Exception { + Properties localProps = new Properties(); + localProps.setProperty(HTTP_SERVICE_SSL_ENABLED, "true"); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE, jks.getCanonicalPath()); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_PASSWORD, "password"); + localProps.setProperty(HTTP_SERVICE_SSL_PROTOCOLS, "TLSv1.2"); + + Properties clientProps = new Properties(); + clientProps.setProperty(CONNECT__TRUST_STORE, jks.getCanonicalPath()); + clientProps.setProperty(CONNECT__TRUST_STORE_PASSWORD, "password"); + + sslInfoHolder.set(clientProps); + setUpJmxManagerOnVm0ThenConnect(localProps); + } + + @Test + public void testWithMultipleProtocol() throws Exception { + Properties localProps = new Properties(); + localProps.setProperty(HTTP_SERVICE_SSL_ENABLED, "true"); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE, jks.getCanonicalPath()); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_PASSWORD, "password"); + localProps.setProperty(HTTP_SERVICE_SSL_PROTOCOLS, "SSL,TLSv1.2"); + + Properties clientProps = new Properties(); + clientProps.setProperty(CONNECT__TRUST_STORE, jks.getCanonicalPath()); + clientProps.setProperty(CONNECT__TRUST_STORE_PASSWORD, "password"); + + sslInfoHolder.set(clientProps); + setUpJmxManagerOnVm0ThenConnect(localProps); + } + + @Ignore("TODO: disabled for unknown reason") + @Test + public void testSSLWithCipherSuite() throws Exception { + Properties localProps = new Properties(); + localProps.setProperty(HTTP_SERVICE_SSL_ENABLED, "true"); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE, jks.getCanonicalPath()); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_PASSWORD, "password"); + localProps.setProperty(HTTP_SERVICE_SSL_PROTOCOLS, "TLSv1.2"); + + //Its bad to hard code here. But using SocketFactory.getDefaultCiphers() somehow is not working with the option + //"https.cipherSuites" which is required to restrict cipher suite with HttpsURLConnection + //Keeping the below code for further investigation on different Java versions ( 7 & 8) @TODO + + /*SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + + sslContext.init(null, null, new java.security.SecureRandom()); + String[] cipherSuites = sslContext.getSocketFactory().getSupportedCipherSuites();*/ + + localProps.setProperty(HTTP_SERVICE_SSL_CIPHERS, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"); + + Properties clientProps = new Properties(); + clientProps.setProperty(CONNECT__TRUST_STORE, jks.getCanonicalPath()); + clientProps.setProperty(CONNECT__TRUST_STORE_PASSWORD, "password"); + clientProps.setProperty(CONNECT__SSL_CIPHERS, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"); + clientProps.setProperty(CONNECT__SSL_PROTOCOLS, "TLSv1.2"); + + sslInfoHolder.set(clientProps); + setUpJmxManagerOnVm0ThenConnect(localProps); + } + + @Ignore("TODO: disabled for unknown reason") + @Test + public void testSSLWithMultipleCipherSuite() throws Exception { + System.setProperty("javax.net.debug", "ssl,handshake,failure"); + + Properties localProps = new Properties(); + localProps.setProperty(HTTP_SERVICE_SSL_ENABLED, "true"); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE, jks.getCanonicalPath()); + localProps.setProperty(HTTP_SERVICE_SSL_KEYSTORE_PASSWORD, "password"); + localProps.setProperty(HTTP_SERVICE_SSL_PROTOCOLS, "TLSv1.2"); + localProps.setProperty(HTTP_SERVICE_SSL_CIPHERS, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_EMPTY_RENEGOTIATION_INFO_SCSV"); + + Properties clientProps = new Properties(); + clientProps.setProperty(CONNECT__TRUST_STORE, jks.getCanonicalPath()); + clientProps.setProperty(CONNECT__TRUST_STORE_PASSWORD, "password"); + clientProps.setProperty(CONNECT__SSL_PROTOCOLS, "TLSv1.2"); + + sslInfoHolder.set(clientProps); + setUpJmxManagerOnVm0ThenConnect(localProps); + } + + @Override + protected void connect(final String host, final int jmxPort, final int httpPort, final HeadlessGfsh shell) { + assertNotNull(host); + assertNotNull(shell); + + final CommandStringBuilder command = new CommandStringBuilder(CONNECT); + String endpoint; + + // This is for testing purpose only. If we remove this piece of code we will + // get a java.security.cert.CertificateException + // as matching hostname can not be obtained in all test environment. + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { + @Override + public boolean verify(String string, SSLSession ssls) { + return true; + } + }); + + endpoint = "https://" + host + ":" + httpPort + urlContext + "/v1"; + + command.addOption(CONNECT__USE_HTTP, Boolean.TRUE.toString()); + command.addOption(CONNECT__URL, endpoint); + command.addOption(CONNECT__USE_SSL,Boolean.TRUE.toString()); + + if(sslInfoHolder.get().getProperty(CONNECT__KEY_STORE) != null){ + command.addOption(CONNECT__KEY_STORE, sslInfoHolder.get().getProperty(CONNECT__KEY_STORE)); + } + if(sslInfoHolder.get().getProperty(CONNECT__KEY_STORE_PASSWORD) != null){ + command.addOption(CONNECT__KEY_STORE_PASSWORD, sslInfoHolder.get().getProperty(CONNECT__KEY_STORE_PASSWORD)); + } + if(sslInfoHolder.get().getProperty(CONNECT__TRUST_STORE) != null){ + command.addOption(CONNECT__TRUST_STORE, sslInfoHolder.get().getProperty(CONNECT__TRUST_STORE)); + } + if(sslInfoHolder.get().getProperty(CONNECT__TRUST_STORE_PASSWORD) != null){ + command.addOption(CONNECT__TRUST_STORE_PASSWORD, sslInfoHolder.get().getProperty(CONNECT__TRUST_STORE_PASSWORD)); + } + if(sslInfoHolder.get().getProperty(CONNECT__SSL_PROTOCOLS) != null){ + command.addOption(CONNECT__SSL_PROTOCOLS, sslInfoHolder.get().getProperty(CONNECT__SSL_PROTOCOLS)); + } + if(sslInfoHolder.get().getProperty(CONNECT__SSL_CIPHERS) != null){ + command.addOption(CONNECT__SSL_CIPHERS, sslInfoHolder.get().getProperty(CONNECT__SSL_CIPHERS)); + } + + CommandResult result = executeCommand(shell, command.toString()); + + if (!shell.isConnectedAndReady()) { + fail("Connect command failed to connect to manager " + endpoint + " result=" + commandResultToString(result)); + } + + info("Successfully connected to managing node using HTTPS"); + assertEquals(true, shell.isConnectedAndReady()); + } + +}