http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/1b0e45a2/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/TestTask1.java ---------------------------------------------------------------------- diff --git a/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/TestTask1.java b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/TestTask1.java new file mode 100644 index 0000000..afb5cd2 --- /dev/null +++ b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/TestTask1.java @@ -0,0 +1,52 @@ +/* + * 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 org.apache.ignite.internal.processors.rest; + +import org.apache.ignite.*; +import org.apache.ignite.compute.*; +import org.apache.ignite.internal.util.typedef.*; +import org.jetbrains.annotations.*; + +import java.util.*; + +/** + * + */ +class TestTask1 extends ComputeTaskSplitAdapter<String, String> { + /** {@inheritDoc} */ + @Override protected Collection<? extends ComputeJob> split(int gridSize, String arg) throws IgniteCheckedException { + Collection<ComputeJob> jobs = new ArrayList<>(gridSize); + + for (int i = 0; i < gridSize; i++) + jobs.add(new ComputeJobAdapter() { + @Nullable + @Override public Object execute() { + X.println("Test task1."); + + return null; + } + }); + + return jobs; + } + + /** {@inheritDoc} */ + @Override public String reduce(List<ComputeJobResult> results) throws IgniteCheckedException { + return null; + } +}
http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/1b0e45a2/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/TestTask2.java ---------------------------------------------------------------------- diff --git a/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/TestTask2.java b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/TestTask2.java new file mode 100644 index 0000000..15628b1 --- /dev/null +++ b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/TestTask2.java @@ -0,0 +1,54 @@ +/* + * 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 org.apache.ignite.internal.processors.rest; + +import org.apache.ignite.*; +import org.apache.ignite.compute.*; +import org.apache.ignite.internal.util.typedef.*; +import org.jetbrains.annotations.*; + +import java.util.*; + +/** + * + */ +class TestTask2 extends ComputeTaskSplitAdapter<String, String> { + static final String RES = "Task 2 result."; + + /** {@inheritDoc} */ + @Override protected Collection<? extends ComputeJob> split(int gridSize, String arg) throws IgniteCheckedException { + Collection<ComputeJob> jobs = new ArrayList<>(gridSize); + + for (int i = 0; i < gridSize; i++) + jobs.add(new ComputeJobAdapter() { + @Nullable + @Override public Object execute() { + X.println("Test task2."); + + return null; + } + }); + + return jobs; + } + + /** {@inheritDoc} */ + @Override public String reduce(List<ComputeJobResult> results) throws IgniteCheckedException { + return RES; + } +} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/1b0e45a2/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridMockNioSession.java ---------------------------------------------------------------------- diff --git a/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridMockNioSession.java b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridMockNioSession.java new file mode 100644 index 0000000..6ced925 --- /dev/null +++ b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridMockNioSession.java @@ -0,0 +1,155 @@ +/* + * 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 org.apache.ignite.internal.processors.rest.protocols.tcp; + +import org.apache.ignite.internal.util.lang.*; +import org.apache.ignite.internal.util.nio.*; +import org.jetbrains.annotations.*; + +import java.net.*; + +/** + * Mock nio session with disabled functionality for testing parser. + */ +public class GridMockNioSession extends GridMetadataAwareAdapter implements GridNioSession { + /** Local address */ + private InetSocketAddress locAddr = new InetSocketAddress(0); + + /** Remote address. */ + private InetSocketAddress rmtAddr = new InetSocketAddress(0); + + /** + * Creates empty mock session. + */ + public GridMockNioSession() { + // No-op. + } + + /** + * Creates new mock session with given addresses. + * + * @param locAddr Local address. + * @param rmtAddr Remote address. + */ + public GridMockNioSession(InetSocketAddress locAddr, InetSocketAddress rmtAddr) { + this(); + + this.locAddr = locAddr; + this.rmtAddr = rmtAddr; + } + + /** {@inheritDoc} */ + @Override public InetSocketAddress localAddress() { + return locAddr; + } + + /** {@inheritDoc} */ + @Override public InetSocketAddress remoteAddress() { + return rmtAddr; + } + + /** {@inheritDoc} */ + @Override public long bytesSent() { + return 0; + } + + /** {@inheritDoc} */ + @Override public long bytesReceived() { + return 0; + } + + /** {@inheritDoc} */ + @Override public long createTime() { + return 0; + } + + /** {@inheritDoc} */ + @Override public long closeTime() { + return 0; + } + + /** {@inheritDoc} */ + @Override public long lastReceiveTime() { + return 0; + } + + /** {@inheritDoc} */ + @Override public long lastSendTime() { + return 0; + } + + /** {@inheritDoc} */ + @Override public long lastSendScheduleTime() { + return 0; + } + + /** {@inheritDoc} */ + @Override public GridNioFuture<Boolean> close() { + return new GridNioFinishedFuture<>(true); + } + + /** {@inheritDoc} */ + @Override public GridNioFuture<?> send(Object msg) { + return new GridNioFinishedFuture<>(true); + } + + /** {@inheritDoc} */ + @Override public <T> T meta(int key) { + return meta(String.valueOf(key)); + } + + /** {@inheritDoc} */ + @Override public <T> T addMeta(int key, T val) { + return addMeta(String.valueOf(key), val); + } + + /** {@inheritDoc} */ + @Override public <T> T removeMeta(int key) { + return removeMeta(String.valueOf(key)); + } + + /** {@inheritDoc} */ + @Override public GridNioFuture<Object> resumeReads() { + return null; + } + + /** {@inheritDoc} */ + @Override public GridNioFuture<Object> pauseReads() { + return null; + } + + /** {@inheritDoc} */ + @Override public boolean accepted() { + return false; + } + + /** {@inheritDoc} */ + @Override public boolean readsPaused() { + return false; + } + + /** {@inheritDoc} */ + @Override public void recoveryDescriptor(GridNioRecoveryDescriptor recoveryDesc) { + // No-op. + } + + /** {@inheritDoc} */ + @Nullable @Override public GridNioRecoveryDescriptor recoveryDescriptor() { + return null; + } +} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/1b0e45a2/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParserSelfTest.java ---------------------------------------------------------------------- diff --git a/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParserSelfTest.java b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParserSelfTest.java new file mode 100644 index 0000000..d296cf9 --- /dev/null +++ b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParserSelfTest.java @@ -0,0 +1,451 @@ +/* + * 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 org.apache.ignite.internal.processors.rest.protocols.tcp; + +import org.apache.ignite.client.marshaller.*; +import org.apache.ignite.client.marshaller.optimized.*; +import org.apache.ignite.internal.processors.rest.client.message.*; +import org.apache.ignite.internal.util.nio.*; +import org.apache.ignite.internal.util.typedef.*; +import org.apache.ignite.internal.util.typedef.internal.*; +import org.gridgain.testframework.*; +import org.gridgain.testframework.junits.common.*; +import org.jetbrains.annotations.*; + +import java.io.*; +import java.nio.*; +import java.util.*; +import java.util.concurrent.*; + +import static org.apache.ignite.internal.processors.rest.client.message.GridClientCacheRequest.GridCacheOperation.*; +import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.*; +import static org.apache.ignite.internal.util.nio.GridNioSessionMetaKey.*; + +/** + * This class tests that parser confirms memcache extended specification. + */ +@SuppressWarnings("TypeMayBeWeakened") +public class GridTcpRestParserSelfTest extends GridCommonAbstractTest { + /** Marshaller. */ + private GridClientMarshaller marshaller = new GridClientOptimizedMarshaller(); + + /** Extras value. */ + public static final byte[] EXTRAS = new byte[]{ + (byte)0xDE, 0x00, (byte)0xBE, 0x00, //Flags, string encoding. + 0x00, 0x00, 0x00, 0x00 // Expiration value. + }; + + /** + * @throws Exception If failed. + */ + public void testSimplePacketParsing() throws Exception { + GridNioSession ses = new GridMockNioSession(); + + GridTcpRestParser parser = new GridTcpRestParser(); + + byte hdr = MEMCACHE_REQ_FLAG; + + byte[] opCodes = {0x01, 0x02, 0x03}; + + byte[] opaque = new byte[] {0x01, 0x02, 0x03, (byte)0xFF}; + + String key = "key"; + + String val = "value"; + + for (byte opCode : opCodes) { + ByteBuffer raw = rawPacket(hdr, opCode, opaque, key.getBytes(), val.getBytes(), EXTRAS); + + GridClientMessage msg = parser.decode(ses, raw); + + assertTrue(msg instanceof GridMemcachedMessage); + + GridMemcachedMessage packet = (GridMemcachedMessage)msg; + + assertEquals("Parser leaved unparsed bytes", 0, raw.remaining()); + + assertEquals("Invalid opcode", opCode, packet.operationCode()); + assertEquals("Invalid key", key, packet.key()); + assertEquals("Invalid value", val, packet.value()); + } + } + + /** + * @throws Exception If failed. + */ + public void testIncorrectPackets() throws Exception { + final GridNioSession ses = new GridMockNioSession(); + + final GridTcpRestParser parser = new GridTcpRestParser(); + + final byte[] opaque = new byte[] {0x01, 0x02, 0x03, (byte)0xFF}; + + final String key = "key"; + + final String val = "value"; + + GridTestUtils.assertThrows(log(), new Callable<Object>() { + @Nullable @Override public Object call() throws Exception { + parser.decode(ses, rawPacket((byte)0x01, (byte)0x01, opaque, key.getBytes(), val.getBytes(), EXTRAS)); + + return null; + } + }, IOException.class, null); + + + GridTestUtils.assertThrows(log(), new Callable<Object>() { + @Nullable @Override public Object call() throws Exception { + parser.decode(ses, rawPacket(MEMCACHE_REQ_FLAG, (byte)0x01, opaque, key.getBytes(), val.getBytes(), null)); + + return null; + } + }, IOException.class, null); + + GridTestUtils.assertThrows(log(), new Callable<Object>() { + @Nullable @Override public Object call() throws Exception { + ByteBuffer fake = ByteBuffer.allocate(21); + + fake.put(GRIDGAIN_REQ_FLAG); + fake.put(U.intToBytes(-5)); + fake.put(U.longToBytes(0)); + fake.put(U.longToBytes(0)); + + fake.flip(); + + parser.decode(ses, fake); + + return null; + } + }, IOException.class, null); + } + + /** + * @throws Exception If failed. + */ + public void testCustomMessages() throws Exception { + GridClientCacheRequest req = new GridClientCacheRequest(CAS); + + req.key("key"); + req.value(1); + req.value2(2); + req.clientId(UUID.randomUUID()); + + ByteBuffer raw = clientRequestPacket(req); + + GridNioSession ses = new GridMockNioSession(); + + ses.addMeta(MARSHALLER.ordinal(), new GridClientOptimizedMarshaller()); + + GridTcpRestParser parser = new GridTcpRestParser(); + + GridClientMessage msg = parser.decode(ses, raw); + + assertNotNull(msg); + + assertEquals("Parser leaved unparsed bytes", 0, raw.remaining()); + + assertTrue(msg instanceof GridClientCacheRequest); + + GridClientCacheRequest res = (GridClientCacheRequest) msg; + + assertEquals("Invalid operation", req.operation(), res.operation()); + assertEquals("Invalid clientId", req.clientId(), res.clientId()); + assertEquals("Invalid key", req.key(), res.key()); + assertEquals("Invalid value 1", req.value(), res.value()); + assertEquals("Invalid value 2", req.value2(), res.value2()); + } + + /** + * @throws Exception If failed. + */ + public void testMixedParsing() throws Exception { + GridNioSession ses1 = new GridMockNioSession(); + GridNioSession ses2 = new GridMockNioSession(); + + ses1.addMeta(MARSHALLER.ordinal(), new GridClientOptimizedMarshaller()); + ses2.addMeta(MARSHALLER.ordinal(), new GridClientOptimizedMarshaller()); + + GridTcpRestParser parser = new GridTcpRestParser(); + + GridClientCacheRequest req = new GridClientCacheRequest(CAS); + + req.key("key"); + + String val = "value"; + + req.value(val); + req.value2(val); + req.clientId(UUID.randomUUID()); + + byte[] opaque = new byte[]{0x01, 0x02, 0x03, (byte)0xFF}; + + String key = "key"; + + ByteBuffer raw1 = rawPacket(MEMCACHE_REQ_FLAG, (byte)0x01, opaque, key.getBytes(), val.getBytes(), EXTRAS); + + ByteBuffer raw2 = clientRequestPacket(req); + + raw1.mark(); + + raw2.mark(); + + int splits = Math.min(raw1.remaining(), raw2.remaining()); + + for (int i = 1; i < splits; i++) { + ByteBuffer[] packet1 = split(raw1, i); + + ByteBuffer[] packet2 = split(raw2, i); + + GridClientMessage msg = parser.decode(ses1, packet1[0]); + + assertNull(msg); + + msg = parser.decode(ses2, packet2[0]); + + assertNull(msg); + + msg = parser.decode(ses1, packet1[1]); + + assertTrue(msg instanceof GridMemcachedMessage); + + assertEquals(key, ((GridMemcachedMessage)msg).key()); + assertEquals(val, ((GridMemcachedMessage)msg).value()); + + msg = parser.decode(ses2, packet2[1]); + + assertTrue(msg instanceof GridClientCacheRequest); + + assertEquals(val, ((GridClientCacheRequest)msg).value()); + assertEquals(val, ((GridClientCacheRequest)msg).value2()); + + raw1.reset(); + + raw2.reset(); + } + } + + /** + * @throws Exception If failed. + */ + public void testParseContinuousSplit() throws Exception { + ByteBuffer tmp = ByteBuffer.allocate(10 * 1024); + + GridClientCacheRequest req = new GridClientCacheRequest(CAS); + + req.key("key"); + req.value(1); + req.value2(2); + req.clientId(UUID.randomUUID()); + + for (int i = 0; i < 5; i++) + tmp.put(clientRequestPacket(req)); + + tmp.flip(); + + for (int splitPos = 0; splitPos < tmp.remaining(); splitPos++) { + ByteBuffer[] split = split(tmp, splitPos); + + tmp.flip(); + + GridNioSession ses = new GridMockNioSession(); + + ses.addMeta(MARSHALLER.ordinal(), new GridClientOptimizedMarshaller()); + + GridTcpRestParser parser = new GridTcpRestParser(); + + Collection<GridClientCacheRequest> lst = new ArrayList<>(5); + + for (ByteBuffer buf : split) { + GridClientCacheRequest r; + + while (buf.hasRemaining() && (r = (GridClientCacheRequest)parser.decode(ses, buf)) != null) + lst.add(r); + + assertTrue("Parser has left unparsed bytes.", buf.remaining() == 0); + } + + assertEquals(5, lst.size()); + + for (GridClientCacheRequest res : lst) { + assertEquals("Invalid operation", req.operation(), res.operation()); + assertEquals("Invalid clientId", req.clientId(), res.clientId()); + assertEquals("Invalid key", req.key(), res.key()); + assertEquals("Invalid value 1", req.value(), res.value()); + assertEquals("Invalid value 2", req.value2(), res.value2()); + } + } + } + + /** + * Tests correct parsing of client handshake packets. + * + * @throws Exception If failed. + */ + public void testParseClientHandshake() throws Exception { + for (int splitPos = 1; splitPos < 5; splitPos++) { + log.info("Checking split position: " + splitPos); + + ByteBuffer tmp = clientHandshakePacket(); + + ByteBuffer[] split = split(tmp, splitPos); + + GridNioSession ses = new GridMockNioSession(); + + ses.addMeta(MARSHALLER.ordinal(), new GridClientOptimizedMarshaller()); + + GridTcpRestParser parser = new GridTcpRestParser(); + + Collection<GridClientMessage> lst = new ArrayList<>(1); + + for (ByteBuffer buf : split) { + GridClientMessage r; + + while (buf.hasRemaining() && (r = parser.decode(ses, buf)) != null) + lst.add(r); + + assertTrue("Parser has left unparsed bytes.", buf.remaining() == 0); + } + + assertEquals(1, lst.size()); + + GridClientHandshakeRequest req = (GridClientHandshakeRequest)F.first(lst); + + assertNotNull(req); + assertEquals(U.bytesToShort(new byte[] {5, 0}, 0), req.version()); + } + } + + /** + * Splits given byte buffer into two byte buffers. + * + * @param original Original byte buffer. + * @param pos Position at which buffer should be split. + * @return Array of byte buffers. + */ + private ByteBuffer[] split(ByteBuffer original, int pos) { + + byte[] data = new byte[pos]; + + original.get(data); + + ByteBuffer[] res = new ByteBuffer[2]; + + res[0] = ByteBuffer.wrap(data); + + data = new byte[original.remaining()]; + + original.get(data); + + res[1] = ByteBuffer.wrap(data); + + return res; + } + + /** + * Assembles GridGain client packet. + * + * @param msg Message to serialize. + * @return Raw message bytes. + * @throws IOException If serialization failed. + */ + private ByteBuffer clientRequestPacket(GridClientMessage msg) throws IOException { + ByteBuffer res = marshaller.marshal(msg, 45); + + ByteBuffer slice = res.slice(); + + slice.put(GRIDGAIN_REQ_FLAG); + slice.putInt(res.remaining() - 5); + slice.putLong(msg.requestId()); + slice.put(U.uuidToBytes(msg.clientId())); + slice.put(U.uuidToBytes(msg.destinationId())); + + return res; + } + + /** + * Assembles GridGain client handshake packet. + * + * @return Raw message bytes. + */ + private ByteBuffer clientHandshakePacket() { + ByteBuffer res = ByteBuffer.allocate(6); + + res.put(new byte[] { + GRIDGAIN_HANDSHAKE_FLAG, 5, 0, 0, 0, 0 + }); + + res.flip(); + + return res; + } + + /** + * Assembles raw packet without any logical checks. + * + * @param magic Header for packet. + * @param opCode Operation code. + * @param opaque Opaque value. + * @param key Key data. + * @param val Value data. + * @param extras Extras data. + * @return Byte buffer containing assembled packet. + */ + private ByteBuffer rawPacket(byte magic, byte opCode, byte[] opaque, @Nullable byte[] key, @Nullable byte[] val, + @Nullable byte[] extras) { + // 1k should be enough. + ByteBuffer res = ByteBuffer.allocate(1024); + + res.put(magic); + res.put(opCode); + + int keyLen = key == null ? 0 : key.length; + int extrasLen = extras == null ? 0 : extras.length; + int valLen = val == null ? 0 : val.length; + + res.putShort((short)keyLen); + res.put((byte)extrasLen); + + // Data type is always 0. + res.put((byte)0); + + // Reserved. + res.putShort((short)0); + + // Total body. + res.putInt(keyLen + extrasLen + valLen); + + // Opaque. + res.put(opaque); + + // CAS + res.putLong(0); + + if (extrasLen > 0) + res.put(extras); + + if (keyLen > 0) + res.put(key); + + if (valLen > 0) + res.put(val); + + res.flip(); + + return res; + } +} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/1b0e45a2/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridAbstractRestProcessorSelfTest.java ---------------------------------------------------------------------- diff --git a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridAbstractRestProcessorSelfTest.java b/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridAbstractRestProcessorSelfTest.java deleted file mode 100644 index 5d15b2f..0000000 --- a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridAbstractRestProcessorSelfTest.java +++ /dev/null @@ -1,96 +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 org.gridgain.grid.kernal.processors.rest; - -import org.apache.ignite.cache.*; -import org.apache.ignite.cache.*; -import org.apache.ignite.configuration.*; -import org.apache.ignite.spi.discovery.tcp.*; -import org.apache.ignite.spi.discovery.tcp.ipfinder.*; -import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*; -import org.gridgain.testframework.junits.common.*; - -/** - * Abstract class for REST protocols tests. - */ -abstract class GridAbstractRestProcessorSelfTest extends GridCommonAbstractTest { - /** IP finder. */ - private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); - - /** Local host. */ - protected static final String LOC_HOST = "127.0.0.1"; - - /** - * @return Grid count. - */ - protected abstract int gridCount(); - - /** {@inheritDoc} */ - @Override protected void beforeTestsStarted() throws Exception { - startGrids(gridCount()); - } - - /** {@inheritDoc} */ - @Override protected void afterTestsStopped() throws Exception { - stopAllGrids(); - } - - /** {@inheritDoc} */ - @Override protected void beforeTest() throws Exception { - assert grid(0).nodes().size() == gridCount(); - } - - /** {@inheritDoc} */ - @Override protected void afterTest() throws Exception { - cache().clearAll(); - - assertTrue(cache().isEmpty()); - } - - /** {@inheritDoc} */ - @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { - IgniteConfiguration cfg = super.getConfiguration(gridName); - - cfg.setLocalHost(LOC_HOST); - - assert cfg.getClientConnectionConfiguration() == null; - - ClientConnectionConfiguration clientCfg = new ClientConnectionConfiguration(); - - cfg.setClientConnectionConfiguration(clientCfg); - - TcpDiscoverySpi disco = new TcpDiscoverySpi(); - - disco.setIpFinder(IP_FINDER); - - cfg.setDiscoverySpi(disco); - - CacheConfiguration ccfg = defaultCacheConfiguration(); - - cfg.setCacheConfiguration(ccfg); - - return cfg; - } - - /** - * @return Cache. - */ - @Override protected <K, V> GridCache<K, V> cache() { - return grid(0).cache(null); - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/1b0e45a2/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridClientMemcachedProtocolSelfTest.java ---------------------------------------------------------------------- diff --git a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridClientMemcachedProtocolSelfTest.java b/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridClientMemcachedProtocolSelfTest.java deleted file mode 100644 index 4a27dbf..0000000 --- a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridClientMemcachedProtocolSelfTest.java +++ /dev/null @@ -1,443 +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 org.gridgain.grid.kernal.processors.rest; - -import net.spy.memcached.*; -import org.apache.ignite.*; -import org.apache.ignite.configuration.*; -import org.apache.ignite.internal.util.typedef.*; -import org.junit.*; - -import java.io.*; -import java.net.*; -import java.util.*; - -import static org.junit.Assert.*; - -/** - * Tests for TCP binary protocol. - */ -public class GridClientMemcachedProtocolSelfTest extends GridAbstractRestProcessorSelfTest { - /** Grid count. */ - private static final int GRID_CNT = 1; - - /** Custom port. */ - private Integer customPort; - - /** Memcache client. */ - private MemcachedClientIF client; - - /** {@inheritDoc} */ - @Override protected int gridCount() { - return GRID_CNT; - } - - /** - * @return Memcache client. - * @throws Exception If start failed. - */ - private MemcachedClientIF startClient() throws Exception { - int port = customPort != null ? customPort : IgniteConfiguration.DFLT_TCP_PORT; - - return new MemcachedClient(new BinaryConnectionFactory(), - F.asList(new InetSocketAddress(LOC_HOST, port))); - } - - /** {@inheritDoc} */ - @Override protected void beforeTest() throws Exception { - super.beforeTest(); - - client = startClient(); - } - - /** {@inheritDoc} */ - @Override protected void afterTest() throws Exception { - super.afterTest(); - - client.shutdown(); - - customPort = null; - } - - /** {@inheritDoc} */ - @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { - IgniteConfiguration cfg = super.getConfiguration(gridName); - - assert cfg.getClientConnectionConfiguration() != null; - - if (customPort != null) - cfg.getClientConnectionConfiguration().setRestTcpPort(customPort); - - return cfg; - } - - /** - * @throws Exception If failed. - */ - public void testGet() throws Exception { - Assert.assertTrue(cache().putx("getKey1", "getVal1")); - Assert.assertTrue(cache().putx("getKey2", "getVal2")); - - Assert.assertEquals("getVal1", client.get("getKey1")); - Assert.assertEquals("getVal2", client.get("getKey2")); - Assert.assertNull(client.get("wrongKey")); - } - - /** - * @throws Exception If failed. - */ - public void testGetBulk() throws Exception { - Assert.assertTrue(cache().putx("getKey1", "getVal1")); - Assert.assertTrue(cache().putx("getKey2", "getVal2")); - Assert.assertTrue(cache().putx("getKey3", "getVal3")); - - Map<String, Object> map = client.getBulk("getKey1", "getKey2"); - - Assert.assertEquals(2, map.size()); - - Assert.assertEquals("getVal1", map.get("getKey1")); - Assert.assertEquals("getVal2", map.get("getKey2")); - } - - /** - * @throws Exception If failed. - */ - public void testSet() throws Exception { - Assert.assertTrue(client.set("setKey", 0, "setVal").get()); - - assertEquals("setVal", cache().get("setKey")); - } - - /** - * @throws Exception If failed. - */ - public void testSetWithExpiration() throws Exception { - Assert.assertTrue(client.set("setKey", 2000, "setVal").get()); - - assertEquals("setVal", cache().get("setKey")); - - Thread.sleep(2100); - - Assert.assertNull(cache().get("setKey")); - } - - /** - * @throws Exception If failed. - */ - public void testAdd() throws Exception { - Assert.assertTrue(cache().putx("addKey1", "addVal1")); - - Assert.assertFalse(client.add("addKey1", 0, "addVal1New").get()); - Assert.assertTrue(client.add("addKey2", 0, "addVal2").get()); - - assertEquals("addVal1", cache().get("addKey1")); - assertEquals("addVal2", cache().get("addKey2")); - } - - /** - * @throws Exception If failed. - */ - public void testAddWithExpiration() throws Exception { - Assert.assertTrue(client.add("addKey", 2000, "addVal").get()); - - assertEquals("addVal", cache().get("addKey")); - - Thread.sleep(2100); - - Assert.assertNull(cache().get("addKey")); - } - - /** - * @throws Exception If failed. - */ - public void testReplace() throws Exception { - Assert.assertFalse(client.replace("replaceKey", 0, "replaceVal").get()); - - Assert.assertNull(cache().get("replaceKey")); - Assert.assertTrue(cache().putx("replaceKey", "replaceVal")); - - Assert.assertTrue(client.replace("replaceKey", 0, "replaceValNew").get()); - - assertEquals("replaceValNew", cache().get("replaceKey")); - } - - /** - * @throws Exception If failed. - */ - public void testReplaceWithExpiration() throws Exception { - Assert.assertTrue(cache().putx("replaceKey", "replaceVal")); - - Assert.assertTrue(client.set("replaceKey", 2000, "replaceValNew").get()); - - assertEquals("replaceValNew", cache().get("replaceKey")); - - Thread.sleep(2100); - - Assert.assertNull(cache().get("replaceKey")); - } - - /** - * @throws Exception If failed. - */ - public void testDelete() throws Exception { - Assert.assertFalse(client.delete("deleteKey").get()); - - Assert.assertTrue(cache().putx("deleteKey", "deleteVal")); - - Assert.assertTrue(client.delete("deleteKey").get()); - - Assert.assertNull(cache().get("deleteKey")); - } - - /** - * @throws Exception If failed. - */ - public void testIncrement() throws Exception { - Assert.assertEquals(5, client.incr("incrKey", 3, 2)); - - assertEquals(5, cache().dataStructures().atomicLong("incrKey", 0, true).get()); - - Assert.assertEquals(15, client.incr("incrKey", 10, 0)); - - assertEquals(15, cache().dataStructures().atomicLong("incrKey", 0, true).get()); - } - - /** - * @throws Exception If failed. - */ - public void testDecrement() throws Exception { - Assert.assertEquals(5, client.decr("decrKey", 10, 15)); - - assertEquals(5, cache().dataStructures().atomicLong("decrKey", 0, true).get()); - - Assert.assertEquals(2, client.decr("decrKey", 3, 0)); - - assertEquals(2, cache().dataStructures().atomicLong("decrKey", 0, true).get()); - } - - /** - * @throws Exception If failed. - */ - public void testFlush() throws Exception { - Assert.assertTrue(cache().putx("flushKey1", "flushVal1")); - Assert.assertTrue(cache().putx("flushKey2", "flushVal2")); - - Assert.assertTrue(client.flush().get()); - - Assert.assertNull(cache().get("flushKey1")); - Assert.assertNull(cache().get("flushKey2")); - Assert.assertTrue(cache().isEmpty()); - } - - /** - * @throws Exception If failed. - */ - public void testStat() throws Exception { - Assert.assertTrue(cache().putx("statKey1", "statVal1")); - assertEquals("statVal1", cache().get("statKey1")); - - Map<SocketAddress, Map<String, String>> map = client.getStats(); - - Assert.assertEquals(1, map.size()); - - Map<String, String> stats = F.first(map.values()); - - Assert.assertEquals(7, stats.size()); - Assert.assertTrue(Integer.valueOf(stats.get("writes")) >= 1); - Assert.assertTrue(Integer.valueOf(stats.get("reads")) >= 1); - - Assert.assertTrue(cache().putx("statKey2", "statVal2")); - assertEquals("statVal2", cache().get("statKey2")); - - map = client.getStats(); - - Assert.assertEquals(1, map.size()); - - stats = F.first(map.values()); - - Assert.assertEquals(7, stats.size()); - Assert.assertTrue(Integer.valueOf(stats.get("writes")) >= 2); - Assert.assertTrue(Integer.valueOf(stats.get("reads")) >= 2); - } - - /** - * @throws Exception If failed. - */ - public void testAppend() throws Exception { - Assert.assertFalse(client.append(0, "appendKey", "_suffix").get()); - - Assert.assertTrue(cache().putx("appendKey", "appendVal")); - - Assert.assertTrue(client.append(0, "appendKey", "_suffix").get()); - - Assert.assertEquals("appendVal_suffix", client.get("appendKey")); - - assertEquals("appendVal_suffix", cache().get("appendKey")); - } - - /** - * @throws Exception If failed. - */ - public void testPrepend() throws Exception { - Assert.assertFalse(client.append(0, "prependKey", "_suffix").get()); - - Assert.assertTrue(cache().putx("prependKey", "prependVal")); - - Assert.assertTrue(client.append(0, "prependKey", "_suffix").get()); - - Assert.assertEquals("prependVal_suffix", client.get("prependKey")); - - assertEquals("prependVal_suffix", cache().get("prependKey")); - } - - /** - * @throws Exception If failed. - */ - public void testSpecialTypes() throws Exception { - Assert.assertTrue(client.set("boolKey", 0, true).get()); - - Assert.assertEquals(true, client.get("boolKey")); - - Assert.assertTrue(client.set("intKey", 0, 10).get()); - - Assert.assertEquals(10, client.get("intKey")); - - Assert.assertTrue(client.set("longKey", 0, 100L).get()); - - Assert.assertEquals(100L, client.get("longKey")); - - Date now = new Date(); - - Assert.assertTrue(client.set("dateKey", 0, now).get()); - - Assert.assertEquals(now, client.get("dateKey")); - - Assert.assertTrue(client.set("byteKey", 0, (byte) 1).get()); - - Assert.assertEquals((byte) 1, client.get("byteKey")); - - Assert.assertTrue(client.set("floatKey", 0, 1.1).get()); - - Assert.assertEquals(1.1, client.get("floatKey")); - - Assert.assertTrue(client.set("doubleKey", 0, 100.001d).get()); - - Assert.assertEquals(100.001d, client.get("doubleKey")); - - byte[] arr = new byte[5]; - - for (byte i = 0; i < arr.length; i++) - arr[i] = i; - - Assert.assertTrue(client.set("arrKey", 0, arr).get()); - - assertArrayEquals(arr, (byte[])client.get("arrKey")); - - Assert.assertTrue(client.set("shortKey", 0, (short) 1).get()); - - Assert.assertEquals((short) 1, client.get("shortKey")); - } - - /** - * @throws Exception If failed. - */ - public void testComplexObject() throws Exception { - Assert.assertTrue(client.set("objKey", 0, new ValueObject(10, "String")).get()); - - Assert.assertEquals(new ValueObject(10, "String"), client.get("objKey")); - } - - /** - * @throws Exception If failed. - */ - public void testCustomPort() throws Exception { - customPort = 11212; - - Ignite g = startGrid(); - - assert g != null; - assert g.cluster().nodes().size() == gridCount() + 1; - - MemcachedClientIF c = startClient(); - - Assert.assertTrue(c.set("key", 0, 1).get()); - - Assert.assertEquals(1, c.get("key")); - - c.shutdown(); - - stopGrid(); - } - - /** - * @throws Exception If failed. - */ - public void testVersion() throws Exception { - Map<SocketAddress, String> map = client.getVersions(); - - Assert.assertEquals(1, map.size()); - - String ver = F.first(map.values()); - - Assert.assertFalse(F.isEmpty(ver)); - } - - /** - * Complex object. - */ - private static class ValueObject implements Serializable { - /** */ - private int intVal; - - /** */ - private String strVal; - - /** - * @param intVal Integer value. - * @param strVal String value. - */ - private ValueObject(int intVal, String strVal) { - this.intVal = intVal; - this.strVal = strVal; - } - - /** {@inheritDoc} */ - @Override public boolean equals(Object o) { - if (this == o) - return true; - - if (o == null || getClass() != o.getClass()) - return false; - - ValueObject obj = (ValueObject)o; - - return intVal == obj.intVal && - !(strVal != null ? !strVal.equals(obj.strVal) : obj.strVal != null); - - } - - /** {@inheritDoc} */ - @Override public int hashCode() { - int res = intVal; - - res = 31 * res + (strVal != null ? strVal.hashCode() : 0); - - return res; - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/1b0e45a2/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorAbstractSelfTest.java ---------------------------------------------------------------------- diff --git a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorAbstractSelfTest.java b/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorAbstractSelfTest.java deleted file mode 100644 index 6b0d69a..0000000 --- a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorAbstractSelfTest.java +++ /dev/null @@ -1,724 +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 org.gridgain.grid.kernal.processors.rest; - -import org.apache.ignite.internal.util.typedef.*; - -import java.io.*; -import java.net.*; -import java.util.*; -import java.util.regex.*; - -import static org.apache.ignite.IgniteSystemProperties.*; - -/** - * Tests for Jetty REST protocol. - */ -@SuppressWarnings("unchecked") -abstract class GridJettyRestProcessorAbstractSelfTest extends GridAbstractRestProcessorSelfTest { - /** Grid count. */ - private static final int GRID_CNT = 3; - - /** {@inheritDoc} */ - @Override protected void beforeTestsStarted() throws Exception { - System.setProperty(GG_JETTY_PORT, Integer.toString(restPort())); - - super.beforeTestsStarted(); - } - - /** {@inheritDoc} */ - @Override protected void afterTestsStopped() throws Exception { - super.afterTestsStopped(); - - System.clearProperty(GG_JETTY_PORT); - } - - /** {@inheritDoc} */ - @Override protected int gridCount() { - return GRID_CNT; - } - - /** - * @return Port to use for rest. Needs to be changed over time - * because Jetty has some delay before port unbind. - */ - protected abstract int restPort(); - - /** - * @param params Command parameters. - * @return Returned content. - * @throws Exception If failed. - */ - private String content(Map<String, String> params) throws Exception { - String addr = "http://" + LOC_HOST + ":" + restPort() + "/gridgain?"; - - for (Map.Entry<String, String> e : params.entrySet()) - addr += e.getKey() + '=' + e.getValue() + '&'; - - URL url = new URL(addr); - - URLConnection conn = url.openConnection(); - - String signature = signature(); - - if (signature != null) - conn.setRequestProperty("X-Signature", signature); - - InputStream in = conn.getInputStream(); - - LineNumberReader rdr = new LineNumberReader(new InputStreamReader(in)); - - StringBuilder buf = new StringBuilder(256); - - for (String line = rdr.readLine(); line != null; line = rdr.readLine()) - buf.append(line); - - return buf.toString(); - } - - /** - * @param json JSON response. - * @param ptrn Pattern to match. - */ - @SuppressWarnings("TypeMayBeWeakened") - private void jsonEquals(String json, String ptrn) { - assertTrue("JSON mismatch [json=" + json + ", ptrn=" + ptrn + ']', Pattern.matches(ptrn, json)); - } - - /** - * @param res Response. - * @param success Success flag. - * @return Regex pattern for JSON. - */ - private String cachePattern(String res, boolean success) { - return "\\{\\\"affinityNodeId\\\":\\\"\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}\\\"\\," + - "\\\"error\\\":\\\"\\\"\\," + - "\\\"response\\\":\\\"" + res + "\\\"\\," + - "\\\"sessionToken\\\":\\\"\\\"," + - "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}"; - } - - /** - * @param res Response. - * @param success Success flag. - * @return Regex pattern for JSON. - */ - private String cacheIntegerPattern(int res, boolean success) { - return "\\{\\\"affinityNodeId\\\":\\\"\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}\\\"\\," + - "\\\"error\\\":\\\"\\\"\\," + - "\\\"response\\\":" + res + "\\," + - "\\\"sessionToken\\\":\\\"\\\"," + - "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}"; - } - - /** - * @param res Response. - * @param success Success flag. - * @return Regex pattern for JSON. - */ - private String cacheBulkPattern(String res, boolean success) { - return "\\{\\\"affinityNodeId\\\":\\\"\\\"\\," + - "\\\"error\\\":\\\"\\\"\\," + - "\\\"response\\\":" + res + "\\," + - "\\\"sessionToken\\\":\\\"\\\"," + - "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}"; - } - - /** - * @param res Response. - * @param success Success flag. - * @return Regex pattern for JSON. - */ - private String cachePattern(boolean res, boolean success) { - return "\\{\\\"affinityNodeId\\\":\\\"\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}\\\"\\," + - "\\\"error\\\":\\\"\\\"\\," + - "\\\"response\\\":" + res + "\\," + - "\\\"sessionToken\\\":\\\"\\\"," + - "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}"; - } - - /** - * @param res Response. - * @param success Success flag. - * @return Regex pattern for JSON. - */ - private String cacheBulkPattern(boolean res, boolean success) { - return "\\{\\\"affinityNodeId\\\":\\\"\\\"\\," + - "\\\"error\\\":\\\"\\\"\\," + - "\\\"response\\\":" + res + "\\," + - "\\\"sessionToken\\\":\\\"\\\"," + - "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}"; - } - - /** - * @param res Response. - * @param success Success flag. - * @return Regex pattern for JSON. - */ - private String cacheMetricsPattern(String res, boolean success) { - return "\\{\\\"affinityNodeId\\\":\\\"(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})?\\\"\\," + - "\\\"error\\\":\\\"\\\"\\," + - "\\\"response\\\":" + res + "\\," + - "\\\"sessionToken\\\":\\\"\\\"," + - "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}"; - } - - /** - * @param res Response. - * @param success Success flag. - * @return Regex pattern for JSON. - */ - private String pattern(String res, boolean success) { - return "\\{\\\"error\\\":\\\"" + (!success ? ".+" : "") + "\\\"\\," + - "\\\"response\\\":" + res + "\\," + - "\\\"sessionToken\\\":\\\"\\\"," + - "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}"; - } - - /** - * @param res Response. - * @param success Success flag. - * @return Regex pattern for JSON. - */ - private String stringPattern(String res, boolean success) { - return "\\{\\\"error\\\":\\\"" + (!success ? ".+" : "") + "\\\"\\," + - "\\\"response\\\":\\\"" + res + "\\\"\\," + - "\\\"sessionToken\\\":\\\"\\\"," + - "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}"; - } - - /** - * @throws Exception If failed. - */ - public void testGet() throws Exception { - assertTrue(cache().putx("getKey", "getVal")); - - String ret = content(F.asMap("cmd", "get", "key", "getKey")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Get command result: " + ret); - - jsonEquals(ret, cachePattern("getVal", true)); - } - - /** - * @throws Exception If failed. - */ - public void testGetAll() throws Exception { - assertTrue(cache().putx("getKey1", "getVal1")); - assertTrue(cache().putx("getKey2", "getVal2")); - - String ret = content(F.asMap("cmd", "getall", "k1", "getKey1", "k2", "getKey2")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Get all command result: " + ret); - - jsonEquals(ret, cacheBulkPattern("\\{\\\"getKey1\\\":\\\"getVal1\\\"\\,\\\"getKey2\\\":\\\"getVal2\\\"\\}", - true)); - } - - /** - * @throws Exception If failed. - */ - public void testPut() throws Exception { - String ret = content(F.asMap("cmd", "put", "key", "putKey", "val", "putVal")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Put command result: " + ret); - - assertEquals("putVal", cache().peek("putKey")); - - jsonEquals(ret, cachePattern(true, true)); - } - - /** - * @throws Exception If failed. - */ - public void testPutWithExpiration() throws Exception { - String ret = content(F.asMap("cmd", "put", "key", "putKey", "val", "putVal", "exp", "2000")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - jsonEquals(ret, cachePattern(true, true)); - - assertEquals("putVal", cache().get("putKey")); - - Thread.sleep(2100); - - assertNull(cache().get("putKey")); - } - - /** - * @throws Exception If failed. - */ - public void testAdd() throws Exception { - assertTrue(cache().putx("addKey1", "addVal1")); - - String ret = content(F.asMap("cmd", "add", "key", "addKey2", "val", "addVal2")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - jsonEquals(ret, cachePattern(true, true)); - - assertEquals("addVal1", cache().peek("addKey1")); - assertEquals("addVal2", cache().peek("addKey2")); - } - - /** - * @throws Exception If failed. - */ - public void testAddWithExpiration() throws Exception { - String ret = content(F.asMap("cmd", "add", "key", "addKey", "val", "addVal", "exp", "2000")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - jsonEquals(ret, cachePattern(true, true)); - - assertEquals("addVal", cache().get("addKey")); - - Thread.sleep(2100); - - assertNull(cache().get("addKey")); - } - - /** - * @throws Exception If failed. - */ - public void testPutAll() throws Exception { - String ret = content(F.asMap("cmd", "putall", "k1", "putKey1", "k2", "putKey2", - "v1", "putVal1", "v2", "putVal2")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Put all command result: " + ret); - - assertEquals("putVal1", cache().peek("putKey1")); - assertEquals("putVal2", cache().peek("putKey2")); - - jsonEquals(ret, cacheBulkPattern(true, true)); - } - - /** - * @throws Exception If failed. - */ - public void testRemove() throws Exception { - assertTrue(cache().putx("rmvKey", "rmvVal")); - - assertEquals("rmvVal", cache().peek("rmvKey")); - - String ret = content(F.asMap("cmd", "rmv", "key", "rmvKey")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Remove command result: " + ret); - - assertNull(cache().peek("rmvKey")); - - jsonEquals(ret, cachePattern(true, true)); - } - - /** - * @throws Exception If failed. - */ - public void testRemoveAll() throws Exception { - assertTrue(cache().putx("rmvKey1", "rmvVal1")); - assertTrue(cache().putx("rmvKey2", "rmvVal2")); - assertTrue(cache().putx("rmvKey3", "rmvVal3")); - assertTrue(cache().putx("rmvKey4", "rmvVal4")); - - assertEquals("rmvVal1", cache().peek("rmvKey1")); - assertEquals("rmvVal2", cache().peek("rmvKey2")); - assertEquals("rmvVal3", cache().peek("rmvKey3")); - assertEquals("rmvVal4", cache().peek("rmvKey4")); - - String ret = content(F.asMap("cmd", "rmvall", "k1", "rmvKey1", "k2", "rmvKey2")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Remove all command result: " + ret); - - assertNull(cache().peek("rmvKey1")); - assertNull(cache().peek("rmvKey2")); - assertEquals("rmvVal3", cache().peek("rmvKey3")); - assertEquals("rmvVal4", cache().peek("rmvKey4")); - - jsonEquals(ret, cacheBulkPattern(true, true)); - - ret = content(F.asMap("cmd", "rmvall")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Remove all command result: " + ret); - - assertNull(cache().peek("rmvKey1")); - assertNull(cache().peek("rmvKey2")); - assertNull(cache().peek("rmvKey3")); - assertNull(cache().peek("rmvKey4")); - assertTrue(cache().isEmpty()); - - jsonEquals(ret, cacheBulkPattern(true, true)); - } - - /** - * @throws Exception If failed. - */ - public void testCas() throws Exception { - assertTrue(cache().putx("casKey", "casOldVal")); - - assertEquals("casOldVal", cache().peek("casKey")); - - String ret = content(F.asMap("cmd", "cas", "key", "casKey", "val2", "casOldVal", "val1", "casNewVal")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("CAS command result: " + ret); - - assertEquals("casNewVal", cache().peek("casKey")); - - jsonEquals(ret, cachePattern(true, true)); - - cache().remove("casKey"); - } - - /** - * @throws Exception If failed. - */ - public void testReplace() throws Exception { - assertTrue(cache().putx("repKey", "repOldVal")); - - assertEquals("repOldVal", cache().peek("repKey")); - - String ret = content(F.asMap("cmd", "rep", "key", "repKey", "val", "repVal")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Replace command result: " + ret); - - assertEquals("repVal", cache().peek("repKey")); - - jsonEquals(ret, cachePattern(true, true)); - } - - /** - * @throws Exception If failed. - */ - public void testReplaceWithExpiration() throws Exception { - assertTrue(cache().putx("replaceKey", "replaceVal")); - - assertEquals("replaceVal", cache().get("replaceKey")); - - String ret = content(F.asMap("cmd", "rep", "key", "replaceKey", "val", "replaceValNew", "exp", "2000")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - jsonEquals(ret, cachePattern(true, true)); - - assertEquals("replaceValNew", cache().get("replaceKey")); - - // Use larger value to avoid false positives. - Thread.sleep(2100); - - assertNull(cache().get("replaceKey")); - } - - /** - * @throws Exception If failed. - */ - public void testAppend() throws Exception { - assertTrue(cache().putx("appendKey", "appendVal")); - - String ret = content(F.asMap("cmd", "append", "key", "appendKey", "val", "_suffix")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - jsonEquals(ret, cachePattern(true, true)); - - assertEquals("appendVal_suffix", cache().get("appendKey")); - } - - /** - * @throws Exception If failed. - */ - public void testPrepend() throws Exception { - assertTrue(cache().putx("prependKey", "prependVal")); - - String ret = content(F.asMap("cmd", "prepend", "key", "prependKey", "val", "prefix_")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - jsonEquals(ret, cachePattern(true, true)); - - assertEquals("prefix_prependVal", cache().get("prependKey")); - } - - /** - * @throws Exception If failed. - */ - public void testIncrement() throws Exception { - String ret = content(F.asMap("cmd", "incr", "key", "incrKey", "init", "2", "delta", "3")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - jsonEquals(ret, cacheIntegerPattern(5, true)); - - assertEquals(5, cache().dataStructures().atomicLong("incrKey", 0, true).get()); - - ret = content(F.asMap("cmd", "incr", "key", "incrKey", "delta", "10")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - jsonEquals(ret, cacheIntegerPattern(15, true)); - - assertEquals(15, cache().dataStructures().atomicLong("incrKey", 0, true).get()); - } - - /** - * @throws Exception If failed. - */ - public void testDecrement() throws Exception { - String ret = content(F.asMap("cmd", "decr", "key", "decrKey", "init", "15", "delta", "10")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - jsonEquals(ret, cacheIntegerPattern(5, true)); - - assertEquals(5, cache().dataStructures().atomicLong("decrKey", 0, true).get()); - - ret = content(F.asMap("cmd", "decr", "key", "decrKey", "delta", "3")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - jsonEquals(ret, cacheIntegerPattern(2, true)); - - assertEquals(2, cache().dataStructures().atomicLong("decrKey", 0, true).get()); - } - - /** - * @throws Exception If failed. - */ - public void testCar() throws Exception { - assertTrue(cache().putx("casKey", "casOldVal")); - - assertEquals("casOldVal", cache().peek("casKey")); - - String ret = content(F.asMap("cmd", "cas", "key", "casKey", "val2", "casOldVal")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("CAR command result: " + ret); - - assertNull(cache().peek("casKey")); - - jsonEquals(ret, cachePattern(true, true)); - } - - /** - * @throws Exception If failed. - */ - public void testPutIfAbsent() throws Exception { - assertNull(cache().peek("casKey")); - - String ret = content(F.asMap("cmd", "cas", "key", "casKey", "val1", "casNewVal")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("PutIfAbsent command result: " + ret); - - assertEquals("casNewVal", cache().peek("casKey")); - - jsonEquals(ret, cachePattern(true, true)); - } - - /** - * @throws Exception If failed. - */ - public void testCasRemove() throws Exception { - assertTrue(cache().putx("casKey", "casVal")); - - assertEquals("casVal", cache().peek("casKey")); - - String ret = content(F.asMap("cmd", "cas", "key", "casKey")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("CAS Remove command result: " + ret); - - assertNull(cache().peek("casKey")); - - jsonEquals(ret, cachePattern(true, true)); - } - - /** - * @throws Exception If failed. - */ - public void testMetrics() throws Exception { - String ret = content(F.asMap("cmd", "cache")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Cache metrics command result: " + ret); - - jsonEquals(ret, cacheMetricsPattern("\\{.+\\}", true)); - } - - /** - * @throws Exception If failed. - */ - public void testTopology() throws Exception { - String ret = content(F.asMap("cmd", "top", "attr", "false", "mtr", "false")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Topology command result: " + ret); - - jsonEquals(ret, pattern("\\[\\{.+\\}\\]", true)); - } - - /** - * @throws Exception If failed. - */ - public void testNode() throws Exception { - String ret = content(F.asMap("cmd", "node", "attr", "true", "mtr", "true", "id", - grid(0).localNode().id().toString())); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Topology command result: " + ret); - - jsonEquals(ret, pattern("\\{.+\\}", true)); - - ret = content(F.asMap("cmd", "node", "attr", "false", "mtr", "false", "ip", LOC_HOST)); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Topology command result: " + ret); - - jsonEquals(ret, pattern("\\{.+\\}", true)); - - ret = content(F.asMap("cmd", "node", "attr", "false", "mtr", "false", "ip", LOC_HOST, "id", - UUID.randomUUID().toString())); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Topology command result: " + ret); - - jsonEquals(ret, pattern("null", true)); - } - - /** - * Tests {@code exe} command. - * <p> - * Note that attempt to execute unknown task (UNKNOWN_TASK) will result in exception on server. - * - * @throws Exception If failed. - */ - public void testExe() throws Exception { - String ret = content(F.asMap("cmd", "exe")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Exe command result: " + ret); - - jsonEquals(ret, pattern("null", false)); - - // Attempt to execute unknown task (UNKNOWN_TASK) will result in exception on server. - ret = content(F.asMap("cmd", "exe", "name", "UNKNOWN_TASK")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Exe command result: " + ret); - - jsonEquals(ret, pattern("null", false)); - - grid(0).compute().localDeployTask(TestTask1.class, TestTask1.class.getClassLoader()); - grid(0).compute().localDeployTask(TestTask2.class, TestTask2.class.getClassLoader()); - - ret = content(F.asMap("cmd", "exe", "name", TestTask1.class.getName())); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Exe command result: " + ret); - - jsonEquals(ret, pattern("\\{.+\\}", true)); - - ret = content(F.asMap("cmd", "exe", "name", TestTask2.class.getName())); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Exe command result: " + ret); - - jsonEquals(ret, pattern("\\{.+" + TestTask2.RES + ".+\\}", true)); - - ret = content(F.asMap("cmd", "res")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - info("Exe command result: " + ret); - - jsonEquals(ret, pattern("null", false)); - } - - /** - * @throws Exception If failed. - */ - public void testVersion() throws Exception { - String ret = content(F.asMap("cmd", "version")); - - assertNotNull(ret); - assertTrue(!ret.isEmpty()); - - jsonEquals(ret, stringPattern(".+", true)); - } - - protected abstract String signature() throws Exception; -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/1b0e45a2/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorSignedSelfTest.java ---------------------------------------------------------------------- diff --git a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorSignedSelfTest.java b/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorSignedSelfTest.java deleted file mode 100644 index a555f82..0000000 --- a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorSignedSelfTest.java +++ /dev/null @@ -1,103 +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 org.gridgain.grid.kernal.processors.rest; - -import org.apache.ignite.configuration.*; -import org.apache.ignite.internal.util.typedef.internal.*; -import sun.misc.*; - -import java.net.*; -import java.security.*; - -/** - * - */ -public class GridJettyRestProcessorSignedSelfTest extends GridJettyRestProcessorAbstractSelfTest { - /** */ - protected static final String REST_SECRET_KEY = "secret-key"; - - /** {@inheritDoc} */ - @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { - IgniteConfiguration cfg = super.getConfiguration(gridName); - - assert cfg.getClientConnectionConfiguration() != null; - - cfg.getClientConnectionConfiguration().setRestSecretKey(REST_SECRET_KEY); - - return cfg; - } - - /** {@inheritDoc} */ - @Override protected int restPort() { - return 8092; - } - - /** - * @throws Exception If failed. - */ - public void testUnauthorized() throws Exception { - String addr = "http://" + LOC_HOST + ":" + restPort() + "/gridgain?cmd=top"; - - URL url = new URL(addr); - - URLConnection conn = url.openConnection(); - - // Request has not been signed. - conn.connect(); - - assert ((HttpURLConnection)conn).getResponseCode() == 401; - - // Request with authentication info. - addr = "http://" + LOC_HOST + ":" + restPort() + "/gridgain?cmd=top"; - - url = new URL(addr); - - conn = url.openConnection(); - - conn.setRequestProperty("X-Signature", signature()); - - conn.connect(); - - assertEquals(200, ((HttpURLConnection)conn).getResponseCode()); - } - - /** - * @return Signature. - * @throws Exception If failed. - */ - @Override protected String signature() throws Exception { - long ts = U.currentTimeMillis(); - - String s = ts + ":" + REST_SECRET_KEY; - - try { - MessageDigest md = MessageDigest.getInstance("SHA-1"); - - BASE64Encoder enc = new BASE64Encoder(); - - md.update(s.getBytes()); - - String hash = enc.encode(md.digest()); - - return ts + ":" + hash; - } - catch (NoSuchAlgorithmException e) { - throw new Exception("Failed to create authentication signature.", e); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/1b0e45a2/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorUnsignedSelfTest.java ---------------------------------------------------------------------- diff --git a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorUnsignedSelfTest.java b/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorUnsignedSelfTest.java deleted file mode 100644 index 09cbbb8..0000000 --- a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridJettyRestProcessorUnsignedSelfTest.java +++ /dev/null @@ -1,36 +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 org.gridgain.grid.kernal.processors.rest; - -/** - * - */ -public class GridJettyRestProcessorUnsignedSelfTest extends GridJettyRestProcessorAbstractSelfTest { - /** {@inheritDoc} */ - @Override protected int restPort() { - return 8091; - } - - /** - * @return Signature. - * @throws Exception If failed. - */ - @Override protected String signature() throws Exception { - return null; - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/1b0e45a2/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridMemcacheRestProcessorTest.java ---------------------------------------------------------------------- diff --git a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridMemcacheRestProcessorTest.java b/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridMemcacheRestProcessorTest.java deleted file mode 100644 index 3822da4..0000000 --- a/modules/clients/src/test/java/org/gridgain/grid/kernal/processors/rest/GridMemcacheRestProcessorTest.java +++ /dev/null @@ -1,76 +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 org.gridgain.grid.kernal.processors.rest; - -import net.spy.memcached.*; -import org.apache.ignite.internal.util.typedef.*; -import org.gridgain.testframework.junits.common.*; - -import java.net.*; -import java.util.*; - -/** - */ -public class GridMemcacheRestProcessorTest extends GridCommonAbstractTest { - /** Client. */ - private MemcachedClientIF client; - - /** {@inheritDoc} */ - @Override protected void beforeTest() throws Exception { - client = new MemcachedClient(new BinaryConnectionFactory(), - F.asList(new InetSocketAddress("127.0.0.1", 11211))); - - assert client.flush().get(); - } - - /** - * @throws Exception If failed. - */ - public void testGetBulk() throws Exception { - assert client.add("key1", 0, 1).get(); - assert client.add("key2", 0, 2).get(); - - Map<String, Object> map = client.getBulk("key1", "key2"); - - assert map.size() == 2; - assert map.get("key1").equals(1); - assert map.get("key2").equals(2); - } - - /** - * @throws Exception If failed. - */ - public void testAppend() throws Exception { - assert client.add("key", 0, "val").get(); - - assert client.append(0, "key", "_1").get(); - - assert "val_1".equals(client.get("key")); - } - - /** - * @throws Exception If failed. - */ - public void testPrepend() throws Exception { - assert client.add("key", 0, "val").get(); - - assert client.prepend(0, "key", "1_").get(); - - assert "1_val".equals(client.get("key")); - } -}
