http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7c20e693/geode-web/src/test/java/org/apache/geode/management/internal/web/shell/RestHttpOperationInvokerJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/shell/RestHttpOperationInvokerJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/shell/RestHttpOperationInvokerJUnitTest.java new file mode 100644 index 0000000..b11125c --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/shell/RestHttpOperationInvokerJUnitTest.java @@ -0,0 +1,453 @@ +/* + * 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/org/apache/geode/management/internal/web/shell/SimpleHttpOperationInvokerJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/shell/SimpleHttpOperationInvokerJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/shell/SimpleHttpOperationInvokerJUnitTest.java new file mode 100644 index 0000000..557cc20 --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/shell/SimpleHttpOperationInvokerJUnitTest.java @@ -0,0 +1,198 @@ +/* + * 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/org/apache/geode/management/internal/web/util/ConvertUtilsJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/util/ConvertUtilsJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/util/ConvertUtilsJUnitTest.java new file mode 100644 index 0000000..d9eb8e5 --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/util/ConvertUtilsJUnitTest.java @@ -0,0 +1,170 @@ +/* + * 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/org/apache/geode/management/internal/web/util/UriUtilsJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/util/UriUtilsJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/util/UriUtilsJUnitTest.java new file mode 100644 index 0000000..645133a --- /dev/null +++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/util/UriUtilsJUnitTest.java @@ -0,0 +1,118 @@ +/* + * 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")); + } + +}
