Unnamed: 0
int64 0
3.76k
| func
stringlengths 25
81.8k
| target
bool 2
classes | project
stringlengths 52
140
|
---|---|---|---|
0 | public class PlaceHolder {
} | false | hazelcast-all_src_main_java_com_hazelcast_PlaceHolder.java |
1 | public abstract class AbstractTextCommand implements TextCommand {
protected final TextCommandType type;
private SocketTextReader socketTextReader;
private SocketTextWriter socketTextWriter;
private long requestId = -1;
protected AbstractTextCommand(TextCommandType type) {
this.type = type;
}
@Override
public TextCommandType getType() {
return type;
}
@Override
public SocketTextReader getSocketTextReader() {
return socketTextReader;
}
@Override
public SocketTextWriter getSocketTextWriter() {
return socketTextWriter;
}
@Override
public long getRequestId() {
return requestId;
}
@Override
public void init(SocketTextReader socketTextReader, long requestId) {
this.socketTextReader = socketTextReader;
this.requestId = requestId;
this.socketTextWriter = socketTextReader.getSocketTextWriter();
}
@Override
public boolean isUrgent() {
return false;
}
@Override
public boolean shouldReply() {
return true;
}
@Override
public String toString() {
return "AbstractTextCommand[" + type + "]{"
+ "requestId="
+ requestId
+ '}';
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_AbstractTextCommand.java |
2 | public abstract class AbstractTextCommandProcessor<T> implements TextCommandProcessor<T>, TextCommandConstants {
protected final TextCommandService textCommandService;
protected AbstractTextCommandProcessor(TextCommandService textCommandService) {
this.textCommandService = textCommandService;
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_AbstractTextCommandProcessor.java |
3 | public interface CommandParser extends TextCommandConstants {
TextCommand parser(SocketTextReader socketTextReader, String cmd, int space);
} | false | hazelcast_src_main_java_com_hazelcast_ascii_CommandParser.java |
4 | @RunWith(HazelcastSerialClassRunner.class)
@Category(SlowTest.class)
public class MemcacheTest {
final static Config config = new XmlConfigBuilder().build();
@BeforeClass
@AfterClass
public static void killAllHazelcastInstances() throws IOException {
Hazelcast.shutdownAll();
}
public MemcachedClient getMemcacheClient(HazelcastInstance instance) throws IOException {
final LinkedList<InetSocketAddress> addresses = new LinkedList<InetSocketAddress>();
addresses.add(instance.getCluster().getLocalMember().getInetSocketAddress());
final ConnectionFactory factory = new ConnectionFactoryBuilder().setOpTimeout(60 * 60 * 60).setDaemon(true).setFailureMode(FailureMode.Retry).build();
return new MemcachedClient(factory, addresses);
}
@Test
public void testMemcacheSimple() throws IOException, ExecutionException, InterruptedException {
final HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
MemcachedClient client = getMemcacheClient(instance);
try {
for (int i = 0; i < 100; i++) {
final OperationFuture<Boolean> future = client.set(String.valueOf(i), 0, i);
assertEquals(Boolean.TRUE, future.get());
}
for (int i = 0; i < 100; i++) {
assertEquals(i, client.get(String.valueOf(i)));
}
for (int i = 0; i < 100; i++) {
final OperationFuture<Boolean> future = client.add(String.valueOf(i), 0, i * 100);
assertEquals(Boolean.FALSE, future.get());
}
for (int i = 0; i < 100; i++) {
assertEquals(i, client.get(String.valueOf(i)));
}
for (int i = 100; i < 200; i++) {
final OperationFuture<Boolean> future = client.add(String.valueOf(i), 0, i);
assertEquals(Boolean.TRUE, future.get());
}
for (int i = 0; i < 200; i++) {
assertEquals(i, client.get(String.valueOf(i)));
}
for (int i = 0; i < 200; i++) {
final OperationFuture<Boolean> future = client.replace(String.valueOf(i), 0, i * 10);
assertEquals(Boolean.TRUE, future.get());
}
for (int i = 0; i < 200; i++) {
assertEquals(i * 10, client.get(String.valueOf(i)));
}
for (int i = 200; i < 400; i++) {
final OperationFuture<Boolean> future = client.replace(String.valueOf(i), 0, i);
assertEquals(Boolean.FALSE, future.get());
}
for (int i = 200; i < 400; i++) {
assertEquals(null, client.get(String.valueOf(i)));
}
for (int i = 100; i < 200; i++) {
final OperationFuture<Boolean> future = client.delete(String.valueOf(i));
assertEquals(Boolean.TRUE, future.get());
}
for (int i = 100; i < 200; i++) {
assertEquals(null, client.get(String.valueOf(100)));
}
for (int i = 100; i < 200; i++) {
final OperationFuture<Boolean> future = client.delete(String.valueOf(i));
assertEquals(Boolean.FALSE, future.get());
}
final LinkedList<String> keys = new LinkedList<String>();
for (int i = 0; i < 100; i++) {
keys.add(String.valueOf(i));
}
final Map<String, Object> bulk = client.getBulk(keys);
for (int i = 0; i < 100; i++) {
assertEquals(i * 10, bulk.get(String.valueOf(i)));
}
// STATS
final Map<String, String> stats = client.getStats().get(instance.getCluster().getLocalMember().getInetSocketAddress());
assertEquals("700", stats.get("cmd_set"));
assertEquals("1000", stats.get("cmd_get"));
assertEquals("700", stats.get("get_hits"));
assertEquals("300", stats.get("get_misses"));
assertEquals("100", stats.get("delete_hits"));
assertEquals("100", stats.get("delete_misses"));
} finally {
client.shutdown();
}
}
@Test
public void testMemcacheWithIMap() throws IOException, InterruptedException, ExecutionException {
final HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
MemcachedClient client = getMemcacheClient(instance);
final String prefix = "testMemcacheWithIMap:";
try {
final IMap<String, Object> map = instance.getMap("hz_memcache_testMemcacheWithIMap");
for (int i = 0; i < 100; i++) {
map.put(String.valueOf(i), String.valueOf(i));
}
for (int i = 0; i < 100; i++) {
assertEquals(String.valueOf(i), client.get(prefix + String.valueOf(i)));
final OperationFuture<Boolean> future = client.set(prefix + String.valueOf(i), 0, String.valueOf(i * 10));
future.get();
}
for (int i = 0; i < 100; i++) {
final MemcacheEntry memcacheEntry = (MemcacheEntry) map.get(String.valueOf(i));
final MemcacheEntry expected = new MemcacheEntry(prefix + String.valueOf(i), String.valueOf(i * 10).getBytes(), 0);
assertEquals(expected, memcacheEntry);
}
final OperationFuture<Boolean> future = client.delete(prefix);
future.get();
for (int i = 0; i < 100; i++) {
assertEquals(null, client.get(prefix + String.valueOf(i)));
}
} finally {
client.shutdown();
}
}
@Test
public void testIncrementAndDecrement() throws IOException, ExecutionException, InterruptedException {
final HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
MemcachedClient client = getMemcacheClient(instance);
try {
for (int i = 0; i < 100; i++) {
final OperationFuture<Boolean> future = client.set(String.valueOf(i), 0, i);
future.get();
}
for (int i = 0; i < 100; i++) {
assertEquals(i * 2, client.incr(String.valueOf(i), i));
}
for (int i = 100; i < 120; i++) {
assertEquals(-1, client.incr(String.valueOf(i), i));
}
for (int i = 0; i < 100; i++) {
assertEquals(i, client.decr(String.valueOf(i), i));
}
for (int i = 100; i < 130; i++) {
assertEquals(-1, client.decr(String.valueOf(i), i));
}
for (int i = 0; i < 100; i++) {
assertEquals(i, client.get(String.valueOf(i)));
}
final Map<String, String> stats = client.getStats().get(instance.getCluster().getLocalMember().getInetSocketAddress());
assertEquals("100", stats.get("cmd_set"));
assertEquals("100", stats.get("cmd_get"));
assertEquals("100", stats.get("incr_hits"));
assertEquals("20", stats.get("incr_misses"));
assertEquals("100", stats.get("decr_hits"));
assertEquals("30", stats.get("decr_misses"));
} finally {
client.shutdown();
}
}
@Test
public void testMemcacheAppendPrepend() throws IOException, ExecutionException, InterruptedException {
final HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
MemcachedClient client = getMemcacheClient(instance);
try {
for (int i = 0; i < 100; i++) {
final OperationFuture<Boolean> future = client.set(String.valueOf(i), 0, String.valueOf(i));
future.get();
}
for (int i = 0; i < 100; i++) {
final OperationFuture<Boolean> future = client.append(0, String.valueOf(i), "append");
assertEquals(Boolean.TRUE, future.get());
}
for (int i = 0; i < 100; i++) {
final OperationFuture<Boolean> future = client.prepend(0, String.valueOf(i), "prepend");
assertEquals(Boolean.TRUE, future.get());
}
for (int i = 1; i < 100; i++) {
assertEquals("prepend" + String.valueOf(i) + "append", client.get(String.valueOf(i)));
}
} finally {
client.shutdown();
}
}
@Test
public void testQuit() throws IOException {
final HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
MemcachedClient client = getMemcacheClient(instance);
client.shutdown();
}
@Test
public void testMemcacheTTL() throws IOException, ExecutionException, InterruptedException {
final HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
MemcachedClient client = getMemcacheClient(instance);
try {
OperationFuture<Boolean> future = client.set(String.valueOf(0), 3, 10);
future.get();
assertEquals(10, client.get(String.valueOf(0)));
Thread.sleep(6000);
assertEquals(null, client.get(String.valueOf(0)));
} finally {
client.shutdown();
}
}
} | false | hazelcast_src_test_java_com_hazelcast_ascii_MemcacheTest.java |
5 | public class NoOpCommand extends AbstractTextCommand {
final ByteBuffer response;
public NoOpCommand(byte[] response) {
super(TextCommandType.NO_OP);
this.response = ByteBuffer.wrap(response);
}
public boolean readFrom(ByteBuffer cb) {
return true;
}
public boolean writeTo(ByteBuffer bb) {
while (bb.hasRemaining() && response.hasRemaining()) {
bb.put(response.get());
}
return !response.hasRemaining();
}
@Override
public String toString() {
return "NoOpCommand {" + bytesToString(response.array()) + "}";
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_NoOpCommand.java |
6 | public class NoOpCommandProcessor extends AbstractTextCommandProcessor<NoOpCommand> {
public NoOpCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
public void handle(NoOpCommand command) {
textCommandService.sendResponse(command);
}
public void handleRejection(NoOpCommand command) {
handle(command);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_NoOpCommandProcessor.java |
7 | @RunWith(HazelcastSerialClassRunner.class)
@Category(SlowTest.class)
public class RestTest {
final static Config config = new XmlConfigBuilder().build();
@Before
@After
public void killAllHazelcastInstances() throws IOException {
Hazelcast.shutdownAll();
}
@Test
public void testTtl_issue1783() throws IOException, InterruptedException {
final Config conf = new Config();
String name = "map";
final CountDownLatch latch = new CountDownLatch(1);
final MapConfig mapConfig = conf.getMapConfig(name);
mapConfig.setTimeToLiveSeconds(3);
mapConfig.addEntryListenerConfig(new EntryListenerConfig()
.setImplementation(new EntryAdapter() {
@Override
public void entryEvicted(EntryEvent event) {
latch.countDown();
}
}));
final HazelcastInstance instance = Hazelcast.newHazelcastInstance(conf);
final HTTPCommunicator communicator = new HTTPCommunicator(instance);
communicator.put(name, "key", "value");
String value = communicator.get(name, "key");
assertNotNull(value);
assertEquals("value", value);
assertTrue(latch.await(30, TimeUnit.SECONDS));
value = communicator.get(name, "key");
assertTrue(value.isEmpty());
}
@Test
public void testRestSimple() throws IOException {
final HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
final HTTPCommunicator communicator = new HTTPCommunicator(instance);
final String name = "testRestSimple";
for (int i = 0; i < 100; i++) {
assertEquals(HttpURLConnection.HTTP_OK, communicator.put(name, String.valueOf(i), String.valueOf(i * 10)));
}
for (int i = 0; i < 100; i++) {
String actual = communicator.get(name, String.valueOf(i));
assertEquals(String.valueOf(i * 10), actual);
}
communicator.deleteAll(name);
for (int i = 0; i < 100; i++) {
String actual = communicator.get(name, String.valueOf(i));
assertEquals("", actual);
}
for (int i = 0; i < 100; i++) {
assertEquals(HttpURLConnection.HTTP_OK, communicator.put(name, String.valueOf(i), String.valueOf(i * 10)));
}
for (int i = 0; i < 100; i++) {
assertEquals(String.valueOf(i * 10), communicator.get(name, String.valueOf(i)));
}
for (int i = 0; i < 100; i++) {
assertEquals(HttpURLConnection.HTTP_OK, communicator.delete(name, String.valueOf(i)));
}
for (int i = 0; i < 100; i++) {
assertEquals("", communicator.get(name, String.valueOf(i)));
}
for (int i = 0; i < 100; i++) {
assertEquals(HttpURLConnection.HTTP_OK, communicator.offer(name, String.valueOf(i)));
}
for (int i = 0; i < 100; i++) {
assertEquals(String.valueOf(i), communicator.poll(name, 2));
}
}
@Test
public void testQueueSizeEmpty() throws IOException {
final HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
final HTTPCommunicator communicator = new HTTPCommunicator(instance);
final String name = "testQueueSizeEmpty";
IQueue queue = instance.getQueue(name);
Assert.assertEquals(queue.size(), communicator.size(name));
}
@Test
public void testQueueSizeNonEmpty() throws IOException {
final HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
final HTTPCommunicator communicator = new HTTPCommunicator(instance);
final String name = "testQueueSizeNotEmpty";
final int num_items = 100;
IQueue queue = instance.getQueue(name);
for (int i = 0; i < num_items; i++) {
queue.add(i);
}
Assert.assertEquals(queue.size(), communicator.size(name));
}
private class HTTPCommunicator {
final HazelcastInstance instance;
final String address;
HTTPCommunicator(HazelcastInstance instance) {
this.instance = instance;
this.address = "http:/" + instance.getCluster().getLocalMember().getInetSocketAddress().toString() + "/hazelcast/rest/";
}
public String poll(String queueName, long timeout) {
String url = address + "queues/" + queueName + "/" + String.valueOf(timeout);
String result = doGet(url);
return result;
}
public int size(String queueName) {
String url = address + "queues/" + queueName + "/size";
Integer result = Integer.parseInt(doGet(url));
return result;
}
public int offer(String queueName, String data) throws IOException {
String url = address + "queues/" + queueName;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
/** post the data */
OutputStream out = null;
out = urlConnection.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(data);
writer.close();
out.close();
return urlConnection.getResponseCode();
}
public String get(String mapName, String key) {
String url = address + "maps/" + mapName + "/" + key;
String result = doGet(url);
return result;
}
public int put(String mapName, String key, String value) throws IOException {
String url = address + "maps/" + mapName + "/" + key;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
/** post the data */
OutputStream out = urlConnection.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(value);
writer.close();
out.close();
return urlConnection.getResponseCode();
}
public int deleteAll(String mapName) throws IOException {
String url = address + "maps/" + mapName;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("DELETE");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
return urlConnection.getResponseCode();
}
public int delete(String mapName, String key) throws IOException {
String url = address + "maps/" + mapName + "/" + key;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("DELETE");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
return urlConnection.getResponseCode();
}
private String doGet(final String url) {
String result = null;
try {
HttpURLConnection httpUrlConnection = (HttpURLConnection) (new URL(url)).openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
StringBuilder data = new StringBuilder(150);
String line;
while ((line = rd.readLine()) != null) data.append(line);
rd.close();
result = data.toString();
httpUrlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
} | false | hazelcast_src_test_java_com_hazelcast_ascii_RestTest.java |
8 | .setImplementation(new EntryAdapter() {
@Override
public void entryEvicted(EntryEvent event) {
latch.countDown();
}
})); | false | hazelcast_src_test_java_com_hazelcast_ascii_RestTest.java |
9 | private class HTTPCommunicator {
final HazelcastInstance instance;
final String address;
HTTPCommunicator(HazelcastInstance instance) {
this.instance = instance;
this.address = "http:/" + instance.getCluster().getLocalMember().getInetSocketAddress().toString() + "/hazelcast/rest/";
}
public String poll(String queueName, long timeout) {
String url = address + "queues/" + queueName + "/" + String.valueOf(timeout);
String result = doGet(url);
return result;
}
public int size(String queueName) {
String url = address + "queues/" + queueName + "/size";
Integer result = Integer.parseInt(doGet(url));
return result;
}
public int offer(String queueName, String data) throws IOException {
String url = address + "queues/" + queueName;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
/** post the data */
OutputStream out = null;
out = urlConnection.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(data);
writer.close();
out.close();
return urlConnection.getResponseCode();
}
public String get(String mapName, String key) {
String url = address + "maps/" + mapName + "/" + key;
String result = doGet(url);
return result;
}
public int put(String mapName, String key, String value) throws IOException {
String url = address + "maps/" + mapName + "/" + key;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
/** post the data */
OutputStream out = urlConnection.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(value);
writer.close();
out.close();
return urlConnection.getResponseCode();
}
public int deleteAll(String mapName) throws IOException {
String url = address + "maps/" + mapName;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("DELETE");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
return urlConnection.getResponseCode();
}
public int delete(String mapName, String key) throws IOException {
String url = address + "maps/" + mapName + "/" + key;
/** set up the http connection parameters */
HttpURLConnection urlConnection = (HttpURLConnection) (new URL(url)).openConnection();
urlConnection.setRequestMethod("DELETE");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
return urlConnection.getResponseCode();
}
private String doGet(final String url) {
String result = null;
try {
HttpURLConnection httpUrlConnection = (HttpURLConnection) (new URL(url)).openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
StringBuilder data = new StringBuilder(150);
String line;
while ((line = rd.readLine()) != null) data.append(line);
rd.close();
result = data.toString();
httpUrlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
} | false | hazelcast_src_test_java_com_hazelcast_ascii_RestTest.java |
10 | public interface TextCommand extends TextCommandConstants, SocketWritable, SocketReadable {
TextCommandType getType();
void init(SocketTextReader socketTextReader, long requestId);
SocketTextReader getSocketTextReader();
SocketTextWriter getSocketTextWriter();
long getRequestId();
boolean shouldReply();
} | false | hazelcast_src_main_java_com_hazelcast_ascii_TextCommand.java |
11 | @edu.umd.cs.findbugs.annotations.SuppressWarnings("MS_OOI_PKGPROTECT")
public interface TextCommandConstants {
int MONTH_SECONDS = 60 * 60 * 24 * 30;
byte[] SPACE = stringToBytes(" ");
byte[] RETURN = stringToBytes("\r\n");
byte[] FLAG_ZERO = stringToBytes(" 0 ");
byte[] VALUE_SPACE = stringToBytes("VALUE ");
byte[] DELETED = stringToBytes("DELETED\r\n");
byte[] STORED = stringToBytes("STORED\r\n");
byte[] TOUCHED = stringToBytes("TOUCHED\r\n");
byte[] NOT_STORED = stringToBytes("NOT_STORED\r\n");
byte[] NOT_FOUND = stringToBytes("NOT_FOUND\r\n");
byte[] RETURN_END = stringToBytes("\r\nEND\r\n");
byte[] END = stringToBytes("END\r\n");
byte[] ERROR = stringToBytes("ERROR");
byte[] CLIENT_ERROR = stringToBytes("CLIENT_ERROR ");
byte[] SERVER_ERROR = stringToBytes("SERVER_ERROR ");
enum TextCommandType {
GET((byte) 0),
PARTIAL_GET((byte) 1),
GETS((byte) 2),
SET((byte) 3),
APPEND((byte) 4),
PREPEND((byte) 5),
ADD((byte) 6),
REPLACE((byte) 7),
DELETE((byte) 8),
QUIT((byte) 9),
STATS((byte) 10),
GET_END((byte) 11),
ERROR_CLIENT((byte) 12),
ERROR_SERVER((byte) 13),
UNKNOWN((byte) 14),
VERSION((byte) 15),
TOUCH((byte) 16),
INCREMENT((byte) 17),
DECREMENT((byte) 18),
HTTP_GET((byte) 30),
HTTP_POST((byte) 31),
HTTP_PUT((byte) 32),
HTTP_DELETE((byte) 33),
NO_OP((byte) 98),
STOP((byte) 99);
final byte value;
TextCommandType(byte type) {
value = type;
}
public byte getValue() {
return value;
}
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_TextCommandConstants.java |
12 | enum TextCommandType {
GET((byte) 0),
PARTIAL_GET((byte) 1),
GETS((byte) 2),
SET((byte) 3),
APPEND((byte) 4),
PREPEND((byte) 5),
ADD((byte) 6),
REPLACE((byte) 7),
DELETE((byte) 8),
QUIT((byte) 9),
STATS((byte) 10),
GET_END((byte) 11),
ERROR_CLIENT((byte) 12),
ERROR_SERVER((byte) 13),
UNKNOWN((byte) 14),
VERSION((byte) 15),
TOUCH((byte) 16),
INCREMENT((byte) 17),
DECREMENT((byte) 18),
HTTP_GET((byte) 30),
HTTP_POST((byte) 31),
HTTP_PUT((byte) 32),
HTTP_DELETE((byte) 33),
NO_OP((byte) 98),
STOP((byte) 99);
final byte value;
TextCommandType(byte type) {
value = type;
}
public byte getValue() {
return value;
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_TextCommandConstants.java |
13 | public interface TextCommandProcessor<T> {
void handle(T request);
void handleRejection(T request);
} | false | hazelcast_src_main_java_com_hazelcast_ascii_TextCommandProcessor.java |
14 | public interface TextCommandService {
boolean offer(String queueName, Object value);
Object poll(String queueName, int seconds);
Object poll(String queueName);
void processRequest(TextCommand command);
void sendResponse(TextCommand textCommand);
Object get(String mapName, String key);
byte[] getByteArray(String mapName, String key);
Object put(String mapName, String key, Object value);
Object put(String mapName, String key, Object value, int ttlSeconds);
Object putIfAbsent(String mapName, String key, Object value, int ttlSeconds);
Object replace(String mapName, String key, Object value);
void lock(String mapName, String key) throws InterruptedException;
void unlock(String mapName, String key);
int getAdjustedTTLSeconds(int ttl);
long incrementDeleteHitCount(int inc);
long incrementDeleteMissCount();
long incrementGetHitCount();
long incrementGetMissCount();
long incrementSetCount();
long incrementIncHitCount();
long incrementIncMissCount();
long incrementDecrHitCount();
long incrementDecrMissCount();
long incrementTouchCount();
/**
* Returns the size of the distributed queue instance with the specified name
* @param queueName name of the distributed queue
* @return the size of the distributed queue instance with the specified name
*/
int size(String queueName);
Object delete(String mapName, String key);
void deleteAll(String mapName);
Stats getStats();
Node getNode();
byte[] toByteArray(Object value);
} | false | hazelcast_src_main_java_com_hazelcast_ascii_TextCommandService.java |
15 | public class TextCommandServiceImpl implements TextCommandService, TextCommandConstants {
private final Node node;
private final TextCommandProcessor[] textCommandProcessors = new TextCommandProcessor[100];
private final HazelcastInstance hazelcast;
private final AtomicLong sets = new AtomicLong();
private final AtomicLong touches = new AtomicLong();
private final AtomicLong getHits = new AtomicLong();
private final AtomicLong getMisses = new AtomicLong();
private final AtomicLong deleteMisses = new AtomicLong();
private final AtomicLong deleteHits = new AtomicLong();
private final AtomicLong incrementHits = new AtomicLong();
private final AtomicLong incrementMisses = new AtomicLong();
private final AtomicLong decrementHits = new AtomicLong();
private final AtomicLong decrementMisses = new AtomicLong();
private final long startTime = Clock.currentTimeMillis();
private final ILogger logger;
private volatile ResponseThreadRunnable responseThreadRunnable;
private volatile boolean running = true;
public TextCommandServiceImpl(Node node) {
this.node = node;
this.hazelcast = node.hazelcastInstance;
this.logger = node.getLogger(this.getClass().getName());
textCommandProcessors[GET.getValue()] = new GetCommandProcessor(this, true);
textCommandProcessors[PARTIAL_GET.getValue()] = new GetCommandProcessor(this, false);
textCommandProcessors[SET.getValue()] = new SetCommandProcessor(this);
textCommandProcessors[APPEND.getValue()] = new SetCommandProcessor(this);
textCommandProcessors[PREPEND.getValue()] = new SetCommandProcessor(this);
textCommandProcessors[ADD.getValue()] = new SetCommandProcessor(this);
textCommandProcessors[REPLACE.getValue()] = new SetCommandProcessor(this);
textCommandProcessors[GET_END.getValue()] = new NoOpCommandProcessor(this);
textCommandProcessors[DELETE.getValue()] = new DeleteCommandProcessor(this);
textCommandProcessors[QUIT.getValue()] = new SimpleCommandProcessor(this);
textCommandProcessors[STATS.getValue()] = new StatsCommandProcessor(this);
textCommandProcessors[UNKNOWN.getValue()] = new ErrorCommandProcessor(this);
textCommandProcessors[VERSION.getValue()] = new VersionCommandProcessor(this);
textCommandProcessors[TOUCH.getValue()] = new TouchCommandProcessor(this);
textCommandProcessors[INCREMENT.getValue()] = new IncrementCommandProcessor(this);
textCommandProcessors[DECREMENT.getValue()] = new IncrementCommandProcessor(this);
textCommandProcessors[ERROR_CLIENT.getValue()] = new ErrorCommandProcessor(this);
textCommandProcessors[ERROR_SERVER.getValue()] = new ErrorCommandProcessor(this);
textCommandProcessors[HTTP_GET.getValue()] = new HttpGetCommandProcessor(this);
textCommandProcessors[HTTP_POST.getValue()] = new HttpPostCommandProcessor(this);
textCommandProcessors[HTTP_PUT.getValue()] = new HttpPostCommandProcessor(this);
textCommandProcessors[HTTP_DELETE.getValue()] = new HttpDeleteCommandProcessor(this);
textCommandProcessors[NO_OP.getValue()] = new NoOpCommandProcessor(this);
}
@Override
public Node getNode() {
return node;
}
@Override
public byte[] toByteArray(Object value) {
Data data = node.getSerializationService().toData(value);
return data.getBuffer();
}
@Override
public Stats getStats() {
Stats stats = new Stats();
stats.uptime = (int) ((Clock.currentTimeMillis() - startTime) / 1000);
stats.cmd_get = getMisses.get() + getHits.get();
stats.cmd_set = sets.get();
stats.cmd_touch = touches.get();
stats.get_hits = getHits.get();
stats.get_misses = getMisses.get();
stats.delete_hits = deleteHits.get();
stats.delete_misses = deleteMisses.get();
stats.incr_hits = incrementHits.get();
stats.incr_misses = incrementMisses.get();
stats.decr_hits = decrementHits.get();
stats.decr_misses = decrementMisses.get();
stats.curr_connections = node.connectionManager.getCurrentClientConnections();
stats.total_connections = node.connectionManager.getAllTextConnections();
return stats;
}
@Override
public long incrementDeleteHitCount(int inc) {
return deleteHits.addAndGet(inc);
}
@Override
public long incrementDeleteMissCount() {
return deleteMisses.incrementAndGet();
}
@Override
public long incrementGetHitCount() {
return getHits.incrementAndGet();
}
@Override
public long incrementGetMissCount() {
return getMisses.incrementAndGet();
}
@Override
public long incrementSetCount() {
return sets.incrementAndGet();
}
@Override
public long incrementIncHitCount() {
return incrementHits.incrementAndGet();
}
@Override
public long incrementIncMissCount() {
return incrementMisses.incrementAndGet();
}
@Override
public long incrementDecrHitCount() {
return decrementHits.incrementAndGet();
}
@Override
public long incrementDecrMissCount() {
return decrementMisses.incrementAndGet();
}
@Override
public long incrementTouchCount() {
return touches.incrementAndGet();
}
@Override
public void processRequest(TextCommand command) {
if (responseThreadRunnable == null) {
synchronized (this) {
if (responseThreadRunnable == null) {
responseThreadRunnable = new ResponseThreadRunnable();
String threadNamePrefix = node.getThreadNamePrefix("ascii.service.response");
Thread thread = new Thread(node.threadGroup, responseThreadRunnable, threadNamePrefix);
thread.start();
}
}
}
node.nodeEngine.getExecutionService().execute("hz:text", new CommandExecutor(command));
}
@Override
public Object get(String mapName, String key) {
return hazelcast.getMap(mapName).get(key);
}
@Override
public int getAdjustedTTLSeconds(int ttl) {
if (ttl <= MONTH_SECONDS) {
return ttl;
} else {
return ttl - (int) (Clock.currentTimeMillis() / 1000);
}
}
@Override
public byte[] getByteArray(String mapName, String key) {
Object value = hazelcast.getMap(mapName).get(key);
byte[] result = null;
if (value != null) {
if (value instanceof RestValue) {
RestValue restValue = (RestValue) value;
result = restValue.getValue();
} else if (value instanceof byte[]) {
result = (byte[]) value;
} else {
result = toByteArray(value);
}
}
return result;
}
@Override
public Object put(String mapName, String key, Object value) {
return hazelcast.getMap(mapName).put(key, value);
}
@Override
public Object put(String mapName, String key, Object value, int ttlSeconds) {
return hazelcast.getMap(mapName).put(key, value, ttlSeconds, TimeUnit.SECONDS);
}
@Override
public Object putIfAbsent(String mapName, String key, Object value, int ttlSeconds) {
return hazelcast.getMap(mapName).putIfAbsent(key, value, ttlSeconds, TimeUnit.SECONDS);
}
@Override
public Object replace(String mapName, String key, Object value) {
return hazelcast.getMap(mapName).replace(key, value);
}
@Override
public void lock(String mapName, String key) throws InterruptedException {
if (!hazelcast.getMap(mapName).tryLock(key, 1, TimeUnit.MINUTES)) {
throw new RuntimeException("Memcache client could not get the lock for map:"
+ mapName + " key:" + key + " in 1 minute");
}
}
@Override
public void unlock(String mapName, String key) {
hazelcast.getMap(mapName).unlock(key);
}
@Override
public void deleteAll(String mapName) {
final IMap<Object, Object> map = hazelcast.getMap(mapName);
map.clear();
}
@Override
public Object delete(String mapName, String key) {
return hazelcast.getMap(mapName).remove(key);
}
@Override
public boolean offer(String queueName, Object value) {
return hazelcast.getQueue(queueName).offer(value);
}
@Override
public Object poll(String queueName, int seconds) {
try {
return hazelcast.getQueue(queueName).poll(seconds, TimeUnit.SECONDS);
} catch (InterruptedException e) {
return null;
}
}
@Override
public Object poll(String queueName) {
return hazelcast.getQueue(queueName).poll();
}
@Override
public int size(String queueName) {
return hazelcast.getQueue(queueName).size();
}
@Override
public void sendResponse(TextCommand textCommand) {
if (!textCommand.shouldReply() || textCommand.getRequestId() == -1) {
throw new RuntimeException("Shouldn't reply " + textCommand);
}
responseThreadRunnable.sendResponse(textCommand);
}
public void stop() {
final ResponseThreadRunnable rtr = responseThreadRunnable;
if (rtr != null) {
rtr.stop();
}
}
class CommandExecutor implements Runnable {
final TextCommand command;
CommandExecutor(TextCommand command) {
this.command = command;
}
@Override
public void run() {
try {
TextCommandType type = command.getType();
TextCommandProcessor textCommandProcessor = textCommandProcessors[type.getValue()];
textCommandProcessor.handle(command);
} catch (Throwable e) {
logger.warning(e);
}
}
}
private class ResponseThreadRunnable implements Runnable {
private final BlockingQueue<TextCommand> blockingQueue = new ArrayBlockingQueue<TextCommand>(200);
private final Object stopObject = new Object();
@edu.umd.cs.findbugs.annotations.SuppressWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
public void sendResponse(TextCommand textCommand) {
blockingQueue.offer(textCommand);
}
@Override
public void run() {
while (running) {
try {
TextCommand textCommand = blockingQueue.take();
if (TextCommandConstants.TextCommandType.STOP == textCommand.getType()) {
synchronized (stopObject) {
stopObject.notify();
}
} else {
SocketTextWriter socketTextWriter = textCommand.getSocketTextWriter();
socketTextWriter.enqueue(textCommand);
}
} catch (InterruptedException e) {
return;
} catch (OutOfMemoryError e) {
OutOfMemoryErrorDispatcher.onOutOfMemory(e);
throw e;
}
}
}
@edu.umd.cs.findbugs.annotations.SuppressWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
void stop() {
running = false;
synchronized (stopObject) {
try {
blockingQueue.offer(new AbstractTextCommand(TextCommandConstants.TextCommandType.STOP) {
@Override
public boolean readFrom(ByteBuffer cb) {
return true;
}
@Override
public boolean writeTo(ByteBuffer bb) {
return true;
}
});
//noinspection WaitNotInLoop
stopObject.wait(1000);
} catch (Exception ignored) {
}
}
}
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_TextCommandServiceImpl.java |
16 | class CommandExecutor implements Runnable {
final TextCommand command;
CommandExecutor(TextCommand command) {
this.command = command;
}
@Override
public void run() {
try {
TextCommandType type = command.getType();
TextCommandProcessor textCommandProcessor = textCommandProcessors[type.getValue()];
textCommandProcessor.handle(command);
} catch (Throwable e) {
logger.warning(e);
}
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_TextCommandServiceImpl.java |
17 | private class ResponseThreadRunnable implements Runnable {
private final BlockingQueue<TextCommand> blockingQueue = new ArrayBlockingQueue<TextCommand>(200);
private final Object stopObject = new Object();
@edu.umd.cs.findbugs.annotations.SuppressWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
public void sendResponse(TextCommand textCommand) {
blockingQueue.offer(textCommand);
}
@Override
public void run() {
while (running) {
try {
TextCommand textCommand = blockingQueue.take();
if (TextCommandConstants.TextCommandType.STOP == textCommand.getType()) {
synchronized (stopObject) {
stopObject.notify();
}
} else {
SocketTextWriter socketTextWriter = textCommand.getSocketTextWriter();
socketTextWriter.enqueue(textCommand);
}
} catch (InterruptedException e) {
return;
} catch (OutOfMemoryError e) {
OutOfMemoryErrorDispatcher.onOutOfMemory(e);
throw e;
}
}
}
@edu.umd.cs.findbugs.annotations.SuppressWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
void stop() {
running = false;
synchronized (stopObject) {
try {
blockingQueue.offer(new AbstractTextCommand(TextCommandConstants.TextCommandType.STOP) {
@Override
public boolean readFrom(ByteBuffer cb) {
return true;
}
@Override
public boolean writeTo(ByteBuffer bb) {
return true;
}
});
//noinspection WaitNotInLoop
stopObject.wait(1000);
} catch (Exception ignored) {
}
}
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_TextCommandServiceImpl.java |
18 | blockingQueue.offer(new AbstractTextCommand(TextCommandConstants.TextCommandType.STOP) {
@Override
public boolean readFrom(ByteBuffer cb) {
return true;
}
@Override
public boolean writeTo(ByteBuffer bb) {
return true;
}
}); | false | hazelcast_src_main_java_com_hazelcast_ascii_TextCommandServiceImpl.java |
19 | public abstract class TypeAwareCommandParser implements CommandParser {
protected final TextCommandConstants.TextCommandType type;
protected TypeAwareCommandParser(TextCommandConstants.TextCommandType type) {
this.type = type;
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_TypeAwareCommandParser.java |
20 | public class DeleteCommand extends AbstractTextCommand {
ByteBuffer response;
private final String key;
private final int expiration;
private final boolean noreply;
public DeleteCommand(String key, int expiration, boolean noreply) {
super(TextCommandType.DELETE);
this.key = key;
this.expiration = expiration;
this.noreply = noreply;
}
public boolean readFrom(ByteBuffer cb) {
return true;
}
public void setResponse(byte[] value) {
this.response = ByteBuffer.wrap(value);
}
public boolean writeTo(ByteBuffer bb) {
if (response == null) {
response = ByteBuffer.wrap(STORED);
}
while (bb.hasRemaining() && response.hasRemaining()) {
bb.put(response.get());
}
return !response.hasRemaining();
}
public boolean shouldReply() {
return !noreply;
}
public int getExpiration() {
return expiration;
}
public String getKey() {
return key;
}
@Override
public String toString() {
return "DeleteCommand [" + type + "]{"
+ "key='" + key + '\''
+ ", expiration=" + expiration
+ ", noreply=" + noreply + '}'
+ super.toString();
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_DeleteCommand.java |
21 | public class DeleteCommandParser implements CommandParser {
public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) {
StringTokenizer st = new StringTokenizer(cmd);
st.nextToken();
String key = null;
int expiration = 0;
boolean noReply = false;
if (st.hasMoreTokens()) {
key = st.nextToken();
}
if (st.hasMoreTokens()) {
expiration = Integer.parseInt(st.nextToken());
}
if (st.hasMoreTokens()) {
noReply = "noreply".equals(st.nextToken());
}
return new DeleteCommand(key, expiration, noReply);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_DeleteCommandParser.java |
22 | public class DeleteCommandProcessor extends MemcacheCommandProcessor<DeleteCommand> {
public DeleteCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
public void handle(DeleteCommand command) {
String key;
try {
key = URLDecoder.decode(command.getKey(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(format("failed to decode key [%s] using UTF-8", command.getKey()));
}
String mapName = DEFAULT_MAP_NAME;
int index = key.indexOf(':');
if (index != -1) {
mapName = MAP_NAME_PRECEDER + key.substring(0, index);
key = key.substring(index + 1);
}
if (key.equals("")) {
textCommandService.deleteAll(mapName);
} else {
final Object oldValue = textCommandService.delete(mapName, key);
if (oldValue == null) {
textCommandService.incrementDeleteMissCount();
command.setResponse(NOT_FOUND);
} else {
textCommandService.incrementDeleteHitCount(1);
command.setResponse(DELETED);
}
}
if (command.shouldReply()) {
textCommandService.sendResponse(command);
}
}
public void handleRejection(DeleteCommand command) {
handle(command);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_DeleteCommandProcessor.java |
23 | public class EndCommand extends NoOpCommand {
public EndCommand() {
super(END);
}
@Override
public String toString() {
return "EndCommand{}";
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_EndCommand.java |
24 | public class ErrorCommand extends AbstractTextCommand {
ByteBuffer response;
private final String message;
public ErrorCommand(TextCommandType type) {
this(type, null);
}
public ErrorCommand(TextCommandType type, String message) {
super(type);
byte[] error = ERROR;
if (type == TextCommandType.ERROR_CLIENT) {
error = CLIENT_ERROR;
} else if (type == TextCommandType.ERROR_SERVER) {
error = SERVER_ERROR;
}
this.message = message;
byte[] msg = (message == null) ? null : stringToBytes(message);
int total = error.length;
if (msg != null) {
total += msg.length;
}
total += 2;
response = ByteBuffer.allocate(total);
response.put(error);
if (msg != null) {
response.put(msg);
}
response.put(RETURN);
response.flip();
}
public boolean readFrom(ByteBuffer cb) {
return true;
}
public boolean writeTo(ByteBuffer bb) {
IOUtil.copyToHeapBuffer(response, bb);
return !response.hasRemaining();
}
@Override
public String toString() {
return "ErrorCommand{"
+ "type=" + type
+ ", msg=" + message
+ '}'
+ super.toString();
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_ErrorCommand.java |
25 | public class ErrorCommandProcessor extends AbstractTextCommandProcessor<ErrorCommand> {
public ErrorCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
public void handle(ErrorCommand command) {
textCommandService.sendResponse(command);
}
public void handleRejection(ErrorCommand command) {
handle(command);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_ErrorCommandProcessor.java |
26 | public class GetCommand extends AbstractTextCommand {
final String key;
ByteBuffer value;
ByteBuffer lastOne;
public GetCommand(TextCommandType type, String key) {
super(type);
this.key = key;
}
public GetCommand(String key) {
this(TextCommandType.GET, key);
}
public String getKey() {
return key;
}
public boolean readFrom(ByteBuffer cb) {
return true;
}
public void setValue(MemcacheEntry entry, boolean singleGet) {
if (entry != null) {
value = entry.toNewBuffer();
}
lastOne = (singleGet) ? ByteBuffer.wrap(END) : null;
}
public boolean writeTo(ByteBuffer bb) {
if (value != null) {
IOUtil.copyToHeapBuffer(value, bb);
}
if (lastOne != null) {
IOUtil.copyToHeapBuffer(lastOne, bb);
}
return !((value != null && value.hasRemaining())
|| (lastOne != null && lastOne.hasRemaining()));
}
@Override
public String toString() {
return "GetCommand{"
+ "key='"
+ key
+ ", value="
+ value
+ '\''
+ "} "
+ super.toString();
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_GetCommand.java |
27 | public class GetCommandParser implements CommandParser {
public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) {
String key = cmd.substring(space + 1);
if (key.indexOf(' ') == -1) {
GetCommand r = new GetCommand(key);
socketTextReader.publishRequest(r);
} else {
StringTokenizer st = new StringTokenizer(key);
while (st.hasMoreTokens()) {
PartialGetCommand r = new PartialGetCommand(st.nextToken());
socketTextReader.publishRequest(r);
}
socketTextReader.publishRequest(new EndCommand());
}
return null;
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_GetCommandParser.java |
28 | public class GetCommandProcessor extends MemcacheCommandProcessor<GetCommand> {
final boolean single;
private final ILogger logger;
public GetCommandProcessor(TextCommandService textCommandService, boolean single) {
super(textCommandService);
this.single = single;
logger = textCommandService.getNode().getLogger(this.getClass().getName());
}
public void handle(GetCommand getCommand) {
String key = null;
try {
key = URLDecoder.decode(getCommand.getKey(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new HazelcastException(e);
}
String mapName = DEFAULT_MAP_NAME;
int index = key.indexOf(':');
if (index != -1) {
mapName = MAP_NAME_PRECEDER + key.substring(0, index);
key = key.substring(index + 1);
}
Object value = textCommandService.get(mapName, key);
MemcacheEntry entry = null;
if (value != null) {
if (value instanceof MemcacheEntry) {
entry = (MemcacheEntry) value;
} else if (value instanceof byte[]) {
entry = new MemcacheEntry(getCommand.getKey(), ((byte[]) value), 0);
} else if (value instanceof String) {
entry = new MemcacheEntry(getCommand.getKey(), stringToBytes((String) value), 0);
} else {
try {
entry = new MemcacheEntry(getCommand.getKey(), textCommandService.toByteArray(value), 0);
} catch (Exception e) {
logger.warning(e);
}
}
}
if (entry != null) {
textCommandService.incrementGetHitCount();
} else {
textCommandService.incrementGetMissCount();
}
getCommand.setValue(entry, single);
textCommandService.sendResponse(getCommand);
}
public void handleRejection(GetCommand getCommand) {
getCommand.setValue(null, single);
textCommandService.sendResponse(getCommand);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_GetCommandProcessor.java |
29 | public class IncrementCommand extends AbstractTextCommand {
String key;
int value;
boolean noreply;
ByteBuffer response;
public IncrementCommand(TextCommandType type, String key, int value, boolean noReply) {
super(type);
this.key = key;
this.value = value;
this.noreply = noReply;
}
public boolean writeTo(ByteBuffer destination) {
while (destination.hasRemaining() && response.hasRemaining()) {
destination.put(response.get());
}
return !response.hasRemaining();
}
public boolean readFrom(ByteBuffer source) {
return true;
}
public boolean shouldReply() {
return !noreply;
}
public String getKey() {
return key;
}
public int getValue() {
return value;
}
public void setResponse(byte[] value) {
this.response = ByteBuffer.wrap(value);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_IncrementCommand.java |
30 | public class IncrementCommandParser extends TypeAwareCommandParser {
public IncrementCommandParser(TextCommandType type) {
super(type);
}
public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) {
StringTokenizer st = new StringTokenizer(cmd);
st.nextToken();
String key = null;
int value = 0;
boolean noReply = false;
if (st.hasMoreTokens()) {
key = st.nextToken();
} else {
return new ErrorCommand(ERROR_CLIENT);
}
if (st.hasMoreTokens()) {
value = Integer.parseInt(st.nextToken());
} else {
return new ErrorCommand(ERROR_CLIENT);
}
if (st.hasMoreTokens()) {
noReply = "noreply".equals(st.nextToken());
}
return new IncrementCommand(type, key, value, noReply);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_IncrementCommandParser.java |
31 | public class IncrementCommandProcessor extends MemcacheCommandProcessor<IncrementCommand> {
private final ILogger logger;
public IncrementCommandProcessor(TextCommandServiceImpl textCommandService) {
super(textCommandService);
logger = textCommandService.getNode().getLogger(this.getClass().getName());
}
public void handle(IncrementCommand incrementCommand) {
String key = null;
try {
key = URLDecoder.decode(incrementCommand.getKey(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new HazelcastException(e);
}
String mapName = DEFAULT_MAP_NAME;
int index = key.indexOf(':');
if (index != -1) {
mapName = MAP_NAME_PRECEDER + key.substring(0, index);
key = key.substring(index + 1);
}
try {
textCommandService.lock(mapName, key);
} catch (Exception e) {
incrementCommand.setResponse(NOT_FOUND);
if (incrementCommand.shouldReply()) {
textCommandService.sendResponse(incrementCommand);
}
return;
}
Object value = textCommandService.get(mapName, key);
MemcacheEntry entry = null;
if (value != null) {
if (value instanceof MemcacheEntry) {
entry = (MemcacheEntry) value;
} else if (value instanceof byte[]) {
entry = new MemcacheEntry(incrementCommand.getKey(), (byte[]) value, 0);
} else if (value instanceof String) {
entry = new MemcacheEntry(incrementCommand.getKey(), stringToBytes((String) value), 0);
} else {
try {
entry = new MemcacheEntry(incrementCommand.getKey(), textCommandService.toByteArray(value), 0);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
final byte[] value1 = entry.getValue();
final long current = (value1 == null || value1.length == 0) ? 0 : byteArrayToLong(value1);
long result = -1;
if (incrementCommand.getType() == TextCommandType.INCREMENT) {
result = current + incrementCommand.getValue();
result = 0 > result ? Long.MAX_VALUE : result;
textCommandService.incrementIncHitCount();
} else if (incrementCommand.getType() == TextCommandType.DECREMENT) {
result = current - incrementCommand.getValue();
result = 0 > result ? 0 : result;
textCommandService.incrementDecrHitCount();
}
incrementCommand.setResponse(ByteUtil.concatenate(stringToBytes(String.valueOf(result)), RETURN));
MemcacheEntry newValue = new MemcacheEntry(key, longToByteArray(result), entry.getFlag());
textCommandService.put(mapName, key, newValue);
} else {
if (incrementCommand.getType() == TextCommandType.INCREMENT) {
textCommandService.incrementIncMissCount();
} else {
textCommandService.incrementDecrMissCount();
}
incrementCommand.setResponse(NOT_FOUND);
}
textCommandService.unlock(mapName, key);
if (incrementCommand.shouldReply()) {
textCommandService.sendResponse(incrementCommand);
}
}
public void handleRejection(IncrementCommand incrementCommand) {
incrementCommand.setResponse(NOT_FOUND);
if (incrementCommand.shouldReply()) {
textCommandService.sendResponse(incrementCommand);
}
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_IncrementCommandProcessor.java |
32 | public abstract class MemcacheCommandProcessor<T> extends AbstractTextCommandProcessor<T> {
public static final String MAP_NAME_PRECEDER = "hz_memcache_";
public static final String DEFAULT_MAP_NAME = "hz_memcache_default";
protected MemcacheCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
public static byte[] longToByteArray(long v) {
int len = (int) (v / 256) + 1;
final byte[] bytes = new byte[len];
for (int i = len - 1; i >= 0; i--) {
final long t = v % 256;
bytes[i] = t < 128 ? (byte) t : (byte) (t - 256);
v = (v - t) / 256;
}
return bytes;
}
public static int byteArrayToLong(byte[] v) {
if (v.length > 8) {
return -1;
}
int r = 0;
for (int i = 0; i < v.length; i++) {
int t = (int) v[i];
t = t >= 0 ? t : t + 256;
r = r * 256 + t;
}
return r;
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_MemcacheCommandProcessor.java |
33 | @edu.umd.cs.findbugs.annotations.SuppressWarnings("EI_EXPOSE_REP")
public class MemcacheEntry implements DataSerializable, TextCommandConstants {
private byte[] bytes;
private byte[] value;
private int flag;
public MemcacheEntry(String key, byte[] value, int flag) {
byte[] flagBytes = stringToBytes(" " + flag + " ");
byte[] valueLen = stringToBytes(String.valueOf(value.length));
byte[] keyBytes = stringToBytes(key);
this.value = value.clone();
int size = VALUE_SPACE.length
+ keyBytes.length
+ flagBytes.length
+ valueLen.length
+ RETURN.length
+ value.length
+ RETURN.length;
ByteBuffer entryBuffer = ByteBuffer.allocate(size);
entryBuffer.put(VALUE_SPACE);
entryBuffer.put(keyBytes);
entryBuffer.put(flagBytes);
entryBuffer.put(valueLen);
entryBuffer.put(RETURN);
entryBuffer.put(value);
entryBuffer.put(RETURN);
this.bytes = entryBuffer.array();
this.flag = flag;
}
public MemcacheEntry() {
}
public void readData(ObjectDataInput in) throws IOException {
int size = in.readInt();
bytes = new byte[size];
in.readFully(bytes);
size = in.readInt();
value = new byte[size];
in.readFully(value);
flag = in.readInt();
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(bytes.length);
out.write(bytes);
out.writeInt(value.length);
out.write(value);
out.writeInt(flag);
}
public ByteBuffer toNewBuffer() {
return ByteBuffer.wrap(bytes);
}
public int getFlag() {
return flag;
}
public byte[] getBytes() {
return bytes;
}
public byte[] getValue() {
return value;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MemcacheEntry that = (MemcacheEntry) o;
if (flag != that.flag) {
return false;
}
if (!Arrays.equals(bytes, that.bytes)) {
return false;
}
if (!Arrays.equals(value, that.value)) {
return false;
}
return true;
}
public int hashCode() {
int result = bytes != null ? Arrays.hashCode(bytes) : 0;
result = 31 * result + (value != null ? Arrays.hashCode(value) : 0);
result = 31 * result + flag;
return result;
}
public String toString() {
return "MemcacheEntry{"
+ "bytes="
+ bytesToString(bytes)
+ ", flag="
+ flag
+ '}';
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_MemcacheEntry.java |
34 | public class PartialGetCommand extends GetCommand {
public PartialGetCommand(String key) {
super(TextCommandType.PARTIAL_GET, key);
}
@Override
public String toString() {
return "PartialGetCommand{"
+ "key='"
+ key + '\''
+ '}';
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_PartialGetCommand.java |
35 | public class SetCommand extends AbstractTextCommand {
ByteBuffer response;
private final String key;
private final int flag;
private final int expiration;
private final int valueLen;
private final boolean noreply;
private final ByteBuffer bbValue;
public SetCommand(TextCommandType type, String key, int flag, int expiration, int valueLen, boolean noreply) {
super(type);
this.key = key;
this.flag = flag;
this.expiration = expiration;
this.valueLen = valueLen;
this.noreply = noreply;
bbValue = ByteBuffer.allocate(valueLen);
}
public boolean readFrom(ByteBuffer cb) {
copy(cb);
if (!bbValue.hasRemaining()) {
while (cb.hasRemaining()) {
char c = (char) cb.get();
if (c == '\n') {
bbValue.flip();
return true;
}
}
}
return false;
}
void copy(ByteBuffer cb) {
if (cb.isDirect()) {
int n = Math.min(cb.remaining(), bbValue.remaining());
if (n > 0) {
cb.get(bbValue.array(), bbValue.position(), n);
bbValue.position(bbValue.position() + n);
}
} else {
IOUtil.copyToHeapBuffer(cb, bbValue);
}
}
public void setResponse(byte[] value) {
this.response = ByteBuffer.wrap(value);
}
public boolean writeTo(ByteBuffer bb) {
if (response == null) {
response = ByteBuffer.wrap(STORED);
}
while (bb.hasRemaining() && response.hasRemaining()) {
bb.put(response.get());
}
return !response.hasRemaining();
}
public boolean shouldReply() {
return !noreply;
}
public int getExpiration() {
return expiration;
}
public String getKey() {
return key;
}
public byte[] getValue() {
return bbValue.array();
}
public int getFlag() {
return flag;
}
@Override
public String toString() {
return "SetCommand [" + type + "]{"
+ "key='"
+ key
+ '\''
+ ", flag="
+ flag
+ ", expiration="
+ expiration
+ ", valueLen="
+ valueLen
+ ", value="
+ bbValue
+ '}'
+ super.toString();
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_SetCommand.java |
36 | public class SetCommandParser extends TypeAwareCommandParser {
public SetCommandParser(TextCommandConstants.TextCommandType type) {
super(type);
}
public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) {
StringTokenizer st = new StringTokenizer(cmd);
st.nextToken();
String key = null;
int valueLen = 0;
int flag = 0;
int expiration = 0;
boolean noReply = false;
if (st.hasMoreTokens()) {
key = st.nextToken();
} else {
return new ErrorCommand(ERROR_CLIENT);
}
if (st.hasMoreTokens()) {
flag = Integer.parseInt(st.nextToken());
} else {
return new ErrorCommand(ERROR_CLIENT);
}
if (st.hasMoreTokens()) {
expiration = Integer.parseInt(st.nextToken());
} else {
return new ErrorCommand(ERROR_CLIENT);
}
if (st.hasMoreTokens()) {
valueLen = Integer.parseInt(st.nextToken());
} else {
return new ErrorCommand(ERROR_CLIENT);
}
if (st.hasMoreTokens()) {
noReply = "noreply".equals(st.nextToken());
}
return new SetCommand(type, key, flag, expiration, valueLen, noReply);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_SetCommandParser.java |
37 | public class SetCommandProcessor extends MemcacheCommandProcessor<SetCommand> {
private final ILogger logger;
public SetCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
logger = textCommandService.getNode().getLogger(this.getClass().getName());
}
/**
* "set" means "store this data".
* <p/>
* "add" means "store this data, but only if the server *doesn't* already
* hold data for this key".
* <p/>
* "replace" means "store this data, but only if the server *does*
* already hold data for this key".
* <p/>
* <p/>
* After sending the command line and the data block the client awaits
* the reply, which may be:
* <p/>
* - "STORED\r\n", to indicate success.
* <p/>
* - "NOT_STORED\r\n" to indicate the data was not stored, but not
* because of an error. This normally means that either that the
* condition for an "add" or a "replace" command wasn't met, or that the
* item is in a delete queue (see the "delete" command below).
*/
public void handle(SetCommand setCommand) {
String key = null;
try {
key = URLDecoder.decode(setCommand.getKey(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new HazelcastException(e);
}
String mapName = DEFAULT_MAP_NAME;
int index = key.indexOf(':');
if (index != -1) {
mapName = MAP_NAME_PRECEDER + key.substring(0, index);
key = key.substring(index + 1);
}
Object value = new MemcacheEntry(setCommand.getKey(), setCommand.getValue(), setCommand.getFlag());
int ttl = textCommandService.getAdjustedTTLSeconds(setCommand.getExpiration());
textCommandService.incrementSetCount();
if (SET == setCommand.getType()) {
textCommandService.put(mapName, key, value, ttl);
setCommand.setResponse(STORED);
} else if (ADD == setCommand.getType()) {
boolean added = (textCommandService.putIfAbsent(mapName, key, value, ttl) == null);
if (added) {
setCommand.setResponse(STORED);
} else {
setCommand.setResponse(NOT_STORED);
}
} else if (REPLACE == setCommand.getType()) {
boolean replaced = (textCommandService.replace(mapName, key, value) != null);
if (replaced) {
setCommand.setResponse(STORED);
} else {
setCommand.setResponse(NOT_STORED);
}
} else if (APPEND == setCommand.getType()) {
try {
textCommandService.lock(mapName, key);
} catch (Exception e) {
setCommand.setResponse(NOT_STORED);
if (setCommand.shouldReply()) {
textCommandService.sendResponse(setCommand);
}
return;
}
Object oldValue = textCommandService.get(mapName, key);
MemcacheEntry entry = null;
if (oldValue != null) {
if (oldValue instanceof MemcacheEntry) {
final MemcacheEntry oldEntry = (MemcacheEntry) oldValue;
entry = new MemcacheEntry(setCommand.getKey(),
ByteUtil.concatenate(oldEntry.getValue(), setCommand.getValue()), 0);
} else if (oldValue instanceof byte[]) {
entry = new MemcacheEntry(setCommand.getKey(),
ByteUtil.concatenate(((byte[]) oldValue), setCommand.getValue()), 0);
} else if (oldValue instanceof String) {
entry = new MemcacheEntry(setCommand.getKey(),
ByteUtil.concatenate(stringToBytes((String) oldValue), setCommand.getValue()), 0);
} else {
try {
entry = new MemcacheEntry(setCommand.getKey(),
ByteUtil.concatenate(textCommandService.toByteArray(oldValue), setCommand.getValue()), 0);
} catch (Exception e) {
logger.warning(e);
}
}
textCommandService.put(mapName, key, entry, ttl);
setCommand.setResponse(STORED);
} else {
setCommand.setResponse(NOT_STORED);
}
textCommandService.unlock(mapName, key);
} else if (PREPEND == setCommand.getType()) {
try {
textCommandService.lock(mapName, key);
} catch (Exception e) {
setCommand.setResponse(NOT_STORED);
if (setCommand.shouldReply()) {
textCommandService.sendResponse(setCommand);
}
return;
}
Object oldValue = textCommandService.get(mapName, key);
MemcacheEntry entry = null;
if (oldValue != null) {
if (oldValue instanceof MemcacheEntry) {
final MemcacheEntry oldEntry = (MemcacheEntry) oldValue;
entry = new MemcacheEntry(setCommand.getKey(),
ByteUtil.concatenate(setCommand.getValue(), oldEntry.getValue()), oldEntry.getFlag());
} else if (oldValue instanceof byte[]) {
entry = new MemcacheEntry(setCommand.getKey(),
ByteUtil.concatenate(setCommand.getValue(), ((byte[]) oldValue)), 0);
} else if (oldValue instanceof String) {
entry = new MemcacheEntry(setCommand.getKey(),
ByteUtil.concatenate(setCommand.getValue(), stringToBytes((String) oldValue)), 0);
} else {
try {
entry = new MemcacheEntry(setCommand.getKey(),
ByteUtil.concatenate(setCommand.getValue(), textCommandService.toByteArray(oldValue)), 0);
} catch (Exception e) {
logger.warning(e);
}
}
textCommandService.put(mapName, key, entry, ttl);
setCommand.setResponse(STORED);
} else {
setCommand.setResponse(NOT_STORED);
}
textCommandService.unlock(mapName, key);
}
if (setCommand.shouldReply()) {
textCommandService.sendResponse(setCommand);
}
}
public void handleRejection(SetCommand request) {
request.setResponse(NOT_STORED);
if (request.shouldReply()) {
textCommandService.sendResponse(request);
}
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_SetCommandProcessor.java |
38 | public class SimpleCommand extends AbstractTextCommand {
ByteBuffer response;
public SimpleCommand(TextCommandType type) {
super(type);
}
public boolean readFrom(ByteBuffer cb) {
return true;
}
public void setResponse(byte[] value) {
this.response = ByteBuffer.wrap(value);
}
public boolean writeTo(ByteBuffer bb) {
while (bb.hasRemaining() && response.hasRemaining()) {
bb.put(response.get());
}
return !response.hasRemaining();
}
@Override
public String toString() {
return "SimpleCommand [" + type + "]{"
+ '}'
+ super.toString();
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_SimpleCommand.java |
39 | public class SimpleCommandParser extends TypeAwareCommandParser {
public SimpleCommandParser(TextCommandConstants.TextCommandType type) {
super(type);
}
public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) {
if (type == QUIT) {
return new SimpleCommand(type);
} else if (type == STATS) {
return new StatsCommand();
} else if (type == VERSION) {
return new VersionCommand(type);
} else {
return new ErrorCommand(UNKNOWN);
}
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_SimpleCommandParser.java |
40 | public class SimpleCommandProcessor extends MemcacheCommandProcessor<SimpleCommand> {
private final ILogger logger;
public SimpleCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
logger = textCommandService.getNode().getLogger(this.getClass().getName());
}
public void handle(SimpleCommand command) {
if (command.getType() == QUIT) {
try {
command.getSocketTextReader().closeConnection();
} catch (Exception e) {
logger.warning(e);
}
} else if (command.getType() == UNKNOWN) {
command.setResponse(ERROR);
textCommandService.sendResponse(command);
}
}
public void handleRejection(SimpleCommand command) {
handle(command);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_SimpleCommandProcessor.java |
41 | public class Stats {
public int waiting_requests;
public int threads;
public int uptime; //seconds
public long cmd_get;
public long cmd_set;
public long cmd_touch;
public long get_hits;
public long get_misses;
public long delete_hits;
public long delete_misses;
public long incr_hits;
public long incr_misses;
public long decr_hits;
public long decr_misses;
public long bytes;
public int curr_connections;
public int total_connections;
// public Stats(int uptime, int threads, long get_misses, long get_hits, long cmd_set, long cmd_get, long bytes) {
// this.uptime = uptime;
// this.threads = threads;
// this.get_misses = get_misses;
// this.get_hits = get_hits;
// this.cmd_set = cmd_set;
// this.cmd_get = cmd_get;
// this.bytes = bytes;
// }
public Stats() {
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_Stats.java |
42 | public class StatsCommand extends AbstractTextCommand {
static final byte[] STAT = stringToBytes("STAT ");
static final byte[] UPTIME = stringToBytes("uptime ");
static final byte[] BYTES = stringToBytes("bytes ");
static final byte[] CMD_SET = stringToBytes("cmd_set ");
static final byte[] CMD_GET = stringToBytes("cmd_get ");
static final byte[] CMD_TOUCH = stringToBytes("cmd_touch ");
static final byte[] THREADS = stringToBytes("threads ");
static final byte[] WAITING_REQUESTS = stringToBytes("waiting_requests ");
static final byte[] GET_HITS = stringToBytes("get_hits ");
static final byte[] GET_MISSES = stringToBytes("get_misses ");
static final byte[] DELETE_HITS = stringToBytes("delete_hits ");
static final byte[] DELETE_MISSES = stringToBytes("delete_misses ");
static final byte[] INCR_HITS = stringToBytes("incr_hits ");
static final byte[] INCR_MISSES = stringToBytes("incr_misses ");
static final byte[] DECR_HITS = stringToBytes("decr_hits ");
static final byte[] DECR_MISSES = stringToBytes("decr_misses ");
static final byte[] CURR_CONNECTIONS = stringToBytes("curr_connections ");
static final byte[] TOTAL_CONNECTIONS = stringToBytes("total_connections ");
ByteBuffer response;
public StatsCommand() {
super(TextCommandType.STATS);
}
public boolean readFrom(ByteBuffer cb) {
return true;
}
public void setResponse(Stats stats) {
response = ByteBuffer.allocate(1000);
putInt(UPTIME, stats.uptime);
putInt(THREADS, stats.threads);
putInt(WAITING_REQUESTS, stats.waiting_requests);
putInt(CURR_CONNECTIONS, stats.curr_connections);
putInt(TOTAL_CONNECTIONS, stats.total_connections);
putLong(BYTES, stats.bytes);
putLong(CMD_GET, stats.cmd_get);
putLong(CMD_SET, stats.cmd_set);
putLong(CMD_TOUCH, stats.cmd_touch);
putLong(GET_HITS, stats.get_hits);
putLong(GET_MISSES, stats.get_misses);
putLong(DELETE_HITS, stats.delete_hits);
putLong(DELETE_MISSES, stats.delete_misses);
putLong(INCR_HITS, stats.incr_hits);
putLong(INCR_MISSES, stats.incr_misses);
putLong(DECR_HITS, stats.decr_hits);
putLong(DECR_MISSES, stats.decr_misses);
response.put(END);
response.flip();
}
private void putInt(byte[] name, int value) {
response.put(STAT);
response.put(name);
response.put(stringToBytes(String.valueOf(value)));
response.put(RETURN);
}
private void putLong(byte[] name, long value) {
response.put(STAT);
response.put(name);
response.put(stringToBytes(String.valueOf(value)));
response.put(RETURN);
}
public boolean writeTo(ByteBuffer bb) {
if (response == null) {
response = ByteBuffer.allocate(0);
}
IOUtil.copyToHeapBuffer(response, bb);
return !response.hasRemaining();
}
@Override
public String toString() {
return "StatsCommand{"
+ '}' + super.toString();
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_StatsCommand.java |
43 | public class StatsCommandProcessor extends MemcacheCommandProcessor<StatsCommand> {
public StatsCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
public void handle(StatsCommand command) {
Stats stats = textCommandService.getStats();
command.setResponse(stats);
textCommandService.sendResponse(command);
}
public void handleRejection(StatsCommand command) {
handle(command);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_StatsCommandProcessor.java |
44 | public class TouchCommand extends AbstractTextCommand {
String key;
int expiration;
boolean noreply;
ByteBuffer response;
public TouchCommand(TextCommandType type, String key, int expiration, boolean noReply) {
super(type);
this.key = key;
this.expiration = expiration;
this.noreply = noReply;
}
public boolean writeTo(ByteBuffer destination) {
if (response == null) {
response = ByteBuffer.wrap(STORED);
}
while (destination.hasRemaining() && response.hasRemaining()) {
destination.put(response.get());
}
return !response.hasRemaining();
}
public boolean readFrom(ByteBuffer source) {
return true;
}
public boolean shouldReply() {
return !noreply;
}
public String getKey() {
return key;
}
public int getExpiration() {
return expiration;
}
public void setResponse(byte[] value) {
this.response = ByteBuffer.wrap(value);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_TouchCommand.java |
45 | public class TouchCommandParser extends TypeAwareCommandParser {
public TouchCommandParser(TextCommandType type) {
super(type);
}
public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) {
StringTokenizer st = new StringTokenizer(cmd);
st.nextToken();
String key = null;
int expiration = 0;
boolean noReply = false;
if (st.hasMoreTokens()) {
key = st.nextToken();
} else {
return new ErrorCommand(ERROR_CLIENT);
}
if (st.hasMoreTokens()) {
expiration = Integer.parseInt(st.nextToken());
} else {
return new ErrorCommand(ERROR_CLIENT);
}
if (st.hasMoreTokens()) {
noReply = "noreply".equals(st.nextToken());
}
return new TouchCommand(type, key, expiration, noReply);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_TouchCommandParser.java |
46 | public class TouchCommandProcessor extends MemcacheCommandProcessor<TouchCommand> {
private final ILogger logger;
public TouchCommandProcessor(TextCommandServiceImpl textCommandService) {
super(textCommandService);
logger = textCommandService.getNode().getLogger(this.getClass().getName());
}
public void handle(TouchCommand touchCommand) {
String key = null;
try {
key = URLDecoder.decode(touchCommand.getKey(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new HazelcastException(e);
}
String mapName = DEFAULT_MAP_NAME;
int index = key.indexOf(':');
if (index != -1) {
mapName = MAP_NAME_PRECEDER + key.substring(0, index);
key = key.substring(index + 1);
}
int ttl = textCommandService.getAdjustedTTLSeconds(touchCommand.getExpiration());
try {
textCommandService.lock(mapName, key);
} catch (Exception e) {
touchCommand.setResponse(NOT_STORED);
if (touchCommand.shouldReply()) {
textCommandService.sendResponse(touchCommand);
}
return;
}
final Object value = textCommandService.get(mapName, key);
textCommandService.incrementTouchCount();
if (value != null) {
textCommandService.put(mapName, key, value, ttl);
touchCommand.setResponse(TOUCHED);
} else {
touchCommand.setResponse(NOT_STORED);
}
textCommandService.unlock(mapName, key);
if (touchCommand.shouldReply()) {
textCommandService.sendResponse(touchCommand);
}
}
public void handleRejection(TouchCommand request) {
request.setResponse(NOT_STORED);
if (request.shouldReply()) {
textCommandService.sendResponse(request);
}
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_TouchCommandProcessor.java |
47 | public class VersionCommand extends AbstractTextCommand {
private static final byte[] VERSION = stringToBytes("VERSION Hazelcast\r\n");
protected VersionCommand(TextCommandType type) {
super(type);
}
public boolean writeTo(ByteBuffer destination) {
destination.put(VERSION);
return true;
}
public boolean readFrom(ByteBuffer source) {
return true;
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_VersionCommand.java |
48 | public class VersionCommandProcessor extends MemcacheCommandProcessor<VersionCommand> {
public VersionCommandProcessor(TextCommandServiceImpl textCommandService) {
super(textCommandService);
}
public void handle(VersionCommand request) {
textCommandService.sendResponse(request);
}
public void handleRejection(VersionCommand request) {
handle(request);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_memcache_VersionCommandProcessor.java |
49 | @edu.umd.cs.findbugs.annotations.SuppressWarnings({ "EI_EXPOSE_REP", "MS_MUTABLE_ARRAY", "MS_PKGPROTECT" })
public abstract class HttpCommand extends AbstractTextCommand {
public static final String HEADER_CONTENT_TYPE = "content-type: ";
public static final String HEADER_CONTENT_LENGTH = "content-length: ";
public static final String HEADER_CHUNKED = "transfer-encoding: chunked";
public static final String HEADER_EXPECT_100 = "expect: 100";
public static final byte[] RES_200 = stringToBytes("HTTP/1.1 200 OK\r\n");
public static final byte[] RES_400 = stringToBytes("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n");
public static final byte[] RES_403 = stringToBytes("HTTP/1.1 403 Forbidden\r\n\r\n");
public static final byte[] RES_404 = stringToBytes("HTTP/1.1 404 Not Found\r\n\r\n");
public static final byte[] RES_100 = stringToBytes("HTTP/1.1 100 Continue\r\n\r\n");
public static final byte[] RES_204 = stringToBytes("HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n");
public static final byte[] RES_503 = stringToBytes("HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n");
public static final byte[] RES_500 = stringToBytes("HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n");
public static final byte[] CONTENT_TYPE = stringToBytes("Content-Type: ");
public static final byte[] CONTENT_LENGTH = stringToBytes("Content-Length: ");
public static final byte[] CONTENT_TYPE_PLAIN_TEXT = stringToBytes("text/plain");
public static final byte[] CONTENT_TYPE_BINARY = stringToBytes("application/binary");
protected final String uri;
protected ByteBuffer response;
public HttpCommand(TextCommandType type, String uri) {
super(type);
this.uri = uri;
}
public boolean shouldReply() {
return true;
}
public String getURI() {
return uri;
}
public void send204() {
this.response = ByteBuffer.wrap(RES_204);
}
public void send400() {
this.response = ByteBuffer.wrap(RES_400);
}
public void setResponse(byte[] value) {
this.response = ByteBuffer.wrap(value);
}
public void send200() {
setResponse(null, null);
}
/**
* HTTP/1.0 200 OK
* Date: Fri, 31 Dec 1999 23:59:59 GMT
* Content-TextCommandType: text/html
* Content-Length: 1354
*
* @param contentType
* @param value
*/
public void setResponse(byte[] contentType, byte[] value) {
int valueSize = (value == null) ? 0 : value.length;
byte[] len = stringToBytes(String.valueOf(valueSize));
int size = RES_200.length;
if (contentType != null) {
size += CONTENT_TYPE.length;
size += contentType.length;
size += RETURN.length;
}
size += CONTENT_LENGTH.length;
size += len.length;
size += RETURN.length;
size += RETURN.length;
size += valueSize;
size += RETURN.length;
this.response = ByteBuffer.allocate(size);
response.put(RES_200);
if (contentType != null) {
response.put(CONTENT_TYPE);
response.put(contentType);
response.put(RETURN);
}
response.put(CONTENT_LENGTH);
response.put(len);
response.put(RETURN);
response.put(RETURN);
if (value != null) {
response.put(value);
}
response.put(RETURN);
response.flip();
}
public boolean writeTo(ByteBuffer bb) {
IOUtil.copyToHeapBuffer(response, bb);
return !response.hasRemaining();
}
@Override
public String toString() {
return "HttpCommand ["
+ type + "]{"
+ "uri='"
+ uri
+ '\''
+ '}'
+ super.toString();
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpCommand.java |
50 | public abstract class HttpCommandProcessor<T> extends AbstractTextCommandProcessor<T> {
public static final String URI_MAPS = "/hazelcast/rest/maps/";
public static final String URI_QUEUES = "/hazelcast/rest/queues/";
public static final String URI_CLUSTER = "/hazelcast/rest/cluster";
public static final String URI_STATE_DUMP = "/hazelcast/rest/dump";
public static final String URI_MANCENTER_CHANGE_URL = "/hazelcast/rest/mancenter/changeurl";
protected HttpCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpCommandProcessor.java |
51 | public class HttpDeleteCommand extends HttpCommand {
boolean nextLine;
public HttpDeleteCommand(String uri) {
super(TextCommandType.HTTP_DELETE, uri);
}
public boolean readFrom(ByteBuffer cb) {
while (cb.hasRemaining()) {
char c = (char) cb.get();
if (c == '\n') {
if (nextLine) {
return true;
}
nextLine = true;
} else if (c != '\r') {
nextLine = false;
}
}
return false;
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpDeleteCommand.java |
52 | public class HttpDeleteCommandParser implements CommandParser {
public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) {
StringTokenizer st = new StringTokenizer(cmd);
st.nextToken();
String uri = null;
if (st.hasMoreTokens()) {
uri = st.nextToken();
} else {
return new ErrorCommand(ERROR_CLIENT);
}
return new HttpDeleteCommand(uri);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpDeleteCommandParser.java |
53 | public class HttpDeleteCommandProcessor extends HttpCommandProcessor<HttpDeleteCommand> {
public HttpDeleteCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
public void handle(HttpDeleteCommand command) {
String uri = command.getURI();
if (uri.startsWith(URI_MAPS)) {
int indexEnd = uri.indexOf('/', URI_MAPS.length());
if (indexEnd == -1) {
String mapName = uri.substring(URI_MAPS.length(), uri.length());
textCommandService.deleteAll(mapName);
command.send200();
} else {
String mapName = uri.substring(URI_MAPS.length(), indexEnd);
String key = uri.substring(indexEnd + 1);
textCommandService.delete(mapName, key);
command.send200();
}
} else if (uri.startsWith(URI_QUEUES)) {
// Poll an item from the default queue in 3 seconds
// http://127.0.0.1:5701/hazelcast/rest/queues/default/3
int indexEnd = uri.indexOf('/', URI_QUEUES.length());
String queueName = uri.substring(URI_QUEUES.length(), indexEnd);
String secondStr = (uri.length() > (indexEnd + 1)) ? uri.substring(indexEnd + 1) : null;
int seconds = (secondStr == null) ? 0 : Integer.parseInt(secondStr);
Object value = textCommandService.poll(queueName, seconds);
if (value == null) {
command.send204();
} else {
if (value instanceof byte[]) {
command.setResponse(null, (byte[]) value);
} else if (value instanceof RestValue) {
RestValue restValue = (RestValue) value;
command.setResponse(restValue.getContentType(), restValue.getValue());
} else if (value instanceof String) {
command.setResponse(HttpCommand.CONTENT_TYPE_PLAIN_TEXT, stringToBytes((String) value));
} else {
command.setResponse(null, textCommandService.toByteArray(value));
}
}
} else {
command.send400();
}
textCommandService.sendResponse(command);
}
public void handleRejection(HttpDeleteCommand command) {
handle(command);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpDeleteCommandProcessor.java |
54 | public class HttpGetCommand extends HttpCommand {
boolean nextLine;
public HttpGetCommand(String uri) {
super(TextCommandType.HTTP_GET, uri);
}
public boolean readFrom(ByteBuffer cb) {
while (cb.hasRemaining()) {
char c = (char) cb.get();
if (c == '\n') {
if (nextLine) {
return true;
}
nextLine = true;
} else if (c != '\r') {
nextLine = false;
}
}
return false;
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpGetCommand.java |
55 | public class HttpGetCommandParser implements CommandParser {
public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) {
StringTokenizer st = new StringTokenizer(cmd);
st.nextToken();
String uri = null;
if (st.hasMoreTokens()) {
uri = st.nextToken();
} else {
return new ErrorCommand(ERROR_CLIENT);
}
return new HttpGetCommand(uri);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpGetCommandParser.java |
56 | public class HttpGetCommandProcessor extends HttpCommandProcessor<HttpGetCommand> {
public static final String QUEUE_SIZE_COMMAND = "size";
public HttpGetCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
public void handle(HttpGetCommand command) {
String uri = command.getURI();
if (uri.startsWith(URI_MAPS)) {
int indexEnd = uri.indexOf('/', URI_MAPS.length());
String mapName = uri.substring(URI_MAPS.length(), indexEnd);
String key = uri.substring(indexEnd + 1);
Object value = textCommandService.get(mapName, key);
prepareResponse(command, value);
} else if (uri.startsWith(URI_QUEUES)) {
int indexEnd = uri.indexOf('/', URI_QUEUES.length());
String queueName = uri.substring(URI_QUEUES.length(), indexEnd);
String secondStr = (uri.length() > (indexEnd + 1)) ? uri.substring(indexEnd + 1) : null;
if (QUEUE_SIZE_COMMAND.equalsIgnoreCase(secondStr)) {
int size = textCommandService.size(queueName);
prepareResponse(command, Integer.toString(size));
} else {
int seconds = (secondStr == null) ? 0 : Integer.parseInt(secondStr);
Object value = textCommandService.poll(queueName, seconds);
prepareResponse(command, value);
}
} else if (uri.startsWith(URI_CLUSTER)) {
Node node = textCommandService.getNode();
StringBuilder res = new StringBuilder(node.getClusterService().membersString());
res.append("\n");
ConnectionManager connectionManager = node.getConnectionManager();
res.append("ConnectionCount: ").append(connectionManager.getCurrentClientConnections());
res.append("\n");
res.append("AllConnectionCount: ").append(connectionManager.getAllTextConnections());
res.append("\n");
command.setResponse(null, stringToBytes(res.toString()));
} else if (uri.startsWith(URI_STATE_DUMP)) {
String stateDump = textCommandService.getNode().getSystemLogService().dump();
stateDump += textCommandService.getNode().getPartitionService().toString() + "\n";
command.setResponse(HttpCommand.CONTENT_TYPE_PLAIN_TEXT, stringToBytes(stateDump));
} else {
command.send400();
}
textCommandService.sendResponse(command);
}
public void handleRejection(HttpGetCommand command) {
handle(command);
}
private void prepareResponse(HttpGetCommand command, Object value) {
if (value == null) {
command.send204();
} else {
if (value instanceof byte[]) {
command.setResponse(HttpCommand.CONTENT_TYPE_BINARY, (byte[]) value);
} else if (value instanceof RestValue) {
RestValue restValue = (RestValue) value;
command.setResponse(restValue.getContentType(), restValue.getValue());
} else if (value instanceof String) {
command.setResponse(HttpCommand.CONTENT_TYPE_PLAIN_TEXT, stringToBytes((String) value));
} else {
command.setResponse(HttpCommand.CONTENT_TYPE_BINARY, textCommandService.toByteArray(value));
}
}
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpGetCommandProcessor.java |
57 | public class HttpPostCommand extends HttpCommand {
boolean nextLine;
boolean readyToReadData;
private ByteBuffer data;
private ByteBuffer line = ByteBuffer.allocate(500);
private String contentType;
private final SocketTextReader socketTextRequestReader;
private boolean chunked;
public HttpPostCommand(SocketTextReader socketTextRequestReader, String uri) {
super(TextCommandType.HTTP_POST, uri);
this.socketTextRequestReader = socketTextRequestReader;
}
/**
* POST /path HTTP/1.0
* User-Agent: HTTPTool/1.0
* Content-TextCommandType: application/x-www-form-urlencoded
* Content-Length: 45
* <next_line>
* <next_line>
* byte[45]
* <next_line>
*
* @param cb
* @return
*/
public boolean readFrom(ByteBuffer cb) {
boolean complete = doActualRead(cb);
while (!complete && readyToReadData && chunked && cb.hasRemaining()) {
complete = doActualRead(cb);
}
if (complete) {
if (data != null) {
data.flip();
}
}
return complete;
}
public byte[] getData() {
if (data == null) {
return null;
} else {
return data.array();
}
}
public byte[] getContentType() {
if (contentType == null) {
return null;
} else {
return stringToBytes(contentType);
}
}
public boolean doActualRead(ByteBuffer cb) {
if (readyToReadData) {
if (chunked && (data == null || !data.hasRemaining())) {
boolean hasLine = readLine(cb);
String lineStr = null;
if (hasLine) {
lineStr = toStringAndClear(line).trim();
}
if (hasLine) {
// hex string
int dataSize = lineStr.length() == 0 ? 0 : Integer.parseInt(lineStr, 16);
if (dataSize == 0) {
return true;
}
if (data != null) {
ByteBuffer newData = ByteBuffer.allocate(data.capacity() + dataSize);
newData.put(data.array());
data = newData;
} else {
data = ByteBuffer.allocate(dataSize);
}
}
}
IOUtil.copyToHeapBuffer(cb, data);
}
while (!readyToReadData && cb.hasRemaining()) {
byte b = cb.get();
char c = (char) b;
if (c == '\n') {
processLine(toStringAndClear(line).toLowerCase());
if (nextLine) {
readyToReadData = true;
}
nextLine = true;
} else if (c != '\r') {
nextLine = false;
line.put(b);
}
}
return !chunked && ((data != null) && !data.hasRemaining());
}
String toStringAndClear(ByteBuffer bb) {
if (bb == null) {
return "";
}
String result;
if (bb.position() == 0) {
result = "";
} else {
result = StringUtil.bytesToString(bb.array(), 0, bb.position());
}
bb.clear();
return result;
}
boolean readLine(ByteBuffer cb) {
while (cb.hasRemaining()) {
byte b = cb.get();
char c = (char) b;
if (c == '\n') {
return true;
} else if (c != '\r') {
line.put(b);
}
}
return false;
}
private void processLine(String currentLine) {
if (contentType == null && currentLine.startsWith(HEADER_CONTENT_TYPE)) {
contentType = currentLine.substring(currentLine.indexOf(' ') + 1);
} else if (data == null && currentLine.startsWith(HEADER_CONTENT_LENGTH)) {
data = ByteBuffer.allocate(Integer.parseInt(currentLine.substring(currentLine.indexOf(' ') + 1)));
} else if (!chunked && currentLine.startsWith(HEADER_CHUNKED)) {
chunked = true;
} else if (currentLine.startsWith(HEADER_EXPECT_100)) {
socketTextRequestReader.sendResponse(new NoOpCommand(RES_100));
}
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpPostCommand.java |
58 | public class HttpPostCommandParser implements CommandParser {
public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) {
StringTokenizer st = new StringTokenizer(cmd);
st.nextToken();
String uri = null;
if (st.hasMoreTokens()) {
uri = st.nextToken();
} else {
return new ErrorCommand(ERROR_CLIENT);
}
return new HttpPostCommand(socketTextReader, uri);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpPostCommandParser.java |
59 | public class HttpPostCommandProcessor extends HttpCommandProcessor<HttpPostCommand> {
private static final byte[] QUEUE_SIMPLE_VALUE_CONTENT_TYPE = stringToBytes("text/plain");
public HttpPostCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
public void handle(HttpPostCommand command) {
try {
String uri = command.getURI();
if (uri.startsWith(URI_MAPS)) {
handleMap(command, uri);
} else if (uri.startsWith(URI_MANCENTER_CHANGE_URL)) {
handleManagementCenterUrlChange(command);
} else if (uri.startsWith(URI_QUEUES)) {
handleQueue(command, uri);
} else {
command.setResponse(HttpCommand.RES_400);
}
} catch (Exception e) {
command.setResponse(HttpCommand.RES_500);
}
textCommandService.sendResponse(command);
}
private void handleQueue(HttpPostCommand command, String uri) {
String simpleValue = null;
String suffix;
if (uri.endsWith("/")) {
suffix = uri.substring(URI_QUEUES.length(), uri.length() - 1);
} else {
suffix = uri.substring(URI_QUEUES.length(), uri.length());
}
int indexSlash = suffix.lastIndexOf('/');
String queueName;
if (indexSlash == -1) {
queueName = suffix;
} else {
queueName = suffix.substring(0, indexSlash);
simpleValue = suffix.substring(indexSlash + 1, suffix.length());
}
byte[] data;
byte[] contentType;
if (simpleValue == null) {
data = command.getData();
contentType = command.getContentType();
} else {
data = stringToBytes(simpleValue);
contentType = QUEUE_SIMPLE_VALUE_CONTENT_TYPE;
}
boolean offerResult = textCommandService.offer(queueName, new RestValue(data, contentType));
if (offerResult) {
command.send200();
} else {
command.setResponse(HttpCommand.RES_503);
}
}
private void handleManagementCenterUrlChange(HttpPostCommand command) throws UnsupportedEncodingException {
if (textCommandService.getNode().getGroupProperties().MC_URL_CHANGE_ENABLED.getBoolean()) {
byte[] res = HttpCommand.RES_204;
byte[] data = command.getData();
String[] strList = bytesToString(data).split("&");
String cluster = URLDecoder.decode(strList[0], "UTF-8");
String pass = URLDecoder.decode(strList[1], "UTF-8");
String url = URLDecoder.decode(strList[2], "UTF-8");
ManagementCenterService managementCenterService = textCommandService.getNode().getManagementCenterService();
if (managementCenterService != null) {
res = managementCenterService.clusterWideUpdateManagementCenterUrl(cluster, pass, url);
}
command.setResponse(res);
} else {
command.setResponse(HttpCommand.RES_503);
}
}
private void handleMap(HttpPostCommand command, String uri) {
int indexEnd = uri.indexOf('/', URI_MAPS.length());
String mapName = uri.substring(URI_MAPS.length(), indexEnd);
String key = uri.substring(indexEnd + 1);
byte[] data = command.getData();
textCommandService.put(mapName, key, new RestValue(data, command.getContentType()), -1);
command.send200();
}
public void handleRejection(HttpPostCommand command) {
handle(command);
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpPostCommandProcessor.java |
60 | @edu.umd.cs.findbugs.annotations.SuppressWarnings("EI_EXPOSE_REP")
public class RestValue implements DataSerializable {
private byte[] value;
private byte[] contentType;
public RestValue() {
}
public RestValue(byte[] value, byte[] contentType) {
this.value = value;
this.contentType = contentType;
}
public void readData(ObjectDataInput in) throws IOException {
value = IOUtil.readByteArray(in);
contentType = IOUtil.readByteArray(in);
}
public void writeData(ObjectDataOutput out) throws IOException {
IOUtil.writeByteArray(out, value);
IOUtil.writeByteArray(out, contentType);
}
public byte[] getContentType() {
return contentType;
}
public void setContentType(byte[] contentType) {
this.contentType = contentType;
}
public byte[] getValue() {
return value;
}
public void setValue(byte[] value) {
this.value = value;
}
@Override
public String toString() {
String contentTypeStr;
if (contentType == null) {
contentTypeStr = "unknown-content-type";
} else {
contentTypeStr = bytesToString(contentType);
}
String valueStr;
if (value == null) {
valueStr = "value.length=0";
} else if (contentTypeStr.contains("text")) {
valueStr = "value=\"" + bytesToString(value) + "\"";
} else {
valueStr = "value.length=" + value.length;
}
return "RestValue{"
+ "contentType='"
+ contentTypeStr
+ "', " + valueStr
+ '}';
}
} | false | hazelcast_src_main_java_com_hazelcast_ascii_rest_RestValue.java |
61 | public class AWSClient {
private String endpoint;
private final AwsConfig awsConfig;
public AWSClient(AwsConfig awsConfig) {
if (awsConfig == null) {
throw new IllegalArgumentException("AwsConfig is required!");
}
if (awsConfig.getAccessKey() == null) {
throw new IllegalArgumentException("AWS access key is required!");
}
if (awsConfig.getSecretKey() == null) {
throw new IllegalArgumentException("AWS secret key is required!");
}
this.awsConfig = awsConfig;
endpoint = awsConfig.getHostHeader();
}
public List<String> getPrivateIpAddresses() throws Exception {
return new DescribeInstances(awsConfig).execute(endpoint);
}
public void setEndpoint(String s) {
this.endpoint = s;
}
} | false | hazelcast-cloud_src_main_java_com_hazelcast_aws_AWSClient.java |
62 | public interface Constants {
String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
String DOC_VERSION = "2011-05-15";
String SIGNATURE_METHOD = "HmacSHA256";
String SIGNATURE_VERSION = "2";
String GET = "GET";
} | false | hazelcast-cloud_src_main_java_com_hazelcast_aws_impl_Constants.java |
63 | public class DescribeInstances {
private final EC2RequestSigner rs;
private final AwsConfig awsConfig;
public DescribeInstances(AwsConfig awsConfig) {
if (awsConfig == null) {
throw new IllegalArgumentException("AwsConfig is required!");
}
if (awsConfig.getAccessKey() == null) {
throw new IllegalArgumentException("AWS access key is required!");
}
rs = new EC2RequestSigner(awsConfig.getSecretKey());
attributes.put("Action", this.getClass().getSimpleName());
attributes.put("Version", DOC_VERSION);
attributes.put("SignatureVersion", SIGNATURE_VERSION);
attributes.put("SignatureMethod", SIGNATURE_METHOD);
attributes.put("AWSAccessKeyId", awsConfig.getAccessKey());
attributes.put("Timestamp", getFormattedTimestamp());
this.awsConfig = awsConfig;
}
/**
* Formats date as ISO 8601 timestamp
*/
private String getFormattedTimestamp() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
return df.format(new Date());
}
private Map<String, String> attributes = new HashMap<String, String>();
public String getQueryString() {
return CloudyUtility.getQueryString(attributes);
}
public Map<String, String> getAttributes() {
return attributes;
}
public void putSignature(String value) {
attributes.put("Signature", value);
}
public <T> T execute(String endpoint) throws Exception {
rs.sign(this, endpoint);
Object result = callService(endpoint);
return (T) result;
}
public Object callService(String endpoint) throws Exception {
String query = getQueryString();
URL url = new URL("https", endpoint, -1, "/" + query);
HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
httpConnection.setRequestMethod(GET);
httpConnection.setDoOutput(true);
httpConnection.connect();
Object response = unmarshalTheResponse(httpConnection.getInputStream(), awsConfig);
return response;
}
} | false | hazelcast-cloud_src_main_java_com_hazelcast_aws_impl_DescribeInstances.java |
64 | public class EC2RequestSigner {
private static final String HTTP_VERB = "GET\n";
private static final String HTTP_REQUEST_URI = "/\n";
private final String secretKey;
public EC2RequestSigner(String secretKey) {
if (secretKey == null) {
throw new IllegalArgumentException("AWS secret key is required!");
}
this.secretKey = secretKey;
}
public void sign(DescribeInstances request, String endpoint) {
String canonicalizedQueryString = getCanonicalizedQueryString(request);
String stringToSign = HTTP_VERB + endpoint + "\n" + HTTP_REQUEST_URI + canonicalizedQueryString;
String signature = signTheString(stringToSign);
request.putSignature(signature);
}
private String signTheString(String stringToSign) {
String signature = null;
try {
signature = RFC2104HMAC.calculateRFC2104HMAC(stringToSign, secretKey);
} catch (SignatureException e) {
throw new RuntimeException(e);
}
return signature;
}
private String getCanonicalizedQueryString(DescribeInstances request) {
List<String> components = getListOfEntries(request.getAttributes());
Collections.sort(components);
return getCanonicalizedQueryString(components);
}
private void addComponents(List<String> components, Map<String, String> attributes, String key) {
components.add(AwsURLEncoder.urlEncode(key) + "=" + AwsURLEncoder.urlEncode(attributes.get(key)));
}
private List<String> getListOfEntries(Map<String, String> entries) {
List<String> components = new ArrayList<String>();
for (String key : entries.keySet()) {
addComponents(components, entries, key);
}
return components;
}
/**
* @param list
* @return
*/
private String getCanonicalizedQueryString(List<String> list) {
Iterator<String> it = list.iterator();
StringBuilder result = new StringBuilder(it.next());
while (it.hasNext()) {
result.append("&").append(it.next());
}
return result.toString();
}
} | false | hazelcast-cloud_src_main_java_com_hazelcast_aws_security_EC2RequestSigner.java |
65 | public class RFC2104HMAC {
private RFC2104HMAC(){}
public static String calculateRFC2104HMAC(String data, String key)
throws SignatureException {
String result;
try {
SecretKeySpec signingKey = new SecretKeySpec(stringToBytes(key),
SIGNATURE_METHOD);
Mac mac = Mac.getInstance(SIGNATURE_METHOD);
mac.init(signingKey);
byte[] rawSignature = mac.doFinal(stringToBytes(data));
result = bytesToString(encode(rawSignature));
result = result.trim();
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : "
+ e.getMessage());
}
return result;
}
} | false | hazelcast-cloud_src_main_java_com_hazelcast_aws_security_RFC2104HMAC.java |
66 | public class AwsURLEncoder {
private AwsURLEncoder() {
}
public static String urlEncode(String string) {
String encoded;
try {
encoded = URLEncoder.encode(string, "UTF-8").replace("+", "%20");
} catch (UnsupportedEncodingException e) {
throw new HazelcastException(e);
}
return encoded;
}
} | false | hazelcast-cloud_src_main_java_com_hazelcast_aws_utility_AwsURLEncoder.java |
67 | public class CloudyUtility {
final static ILogger logger = Logger.getLogger(CloudyUtility.class);
private CloudyUtility() {
}
public static String getQueryString(Map<String, String> attributes) {
StringBuilder query = new StringBuilder();
for (Iterator<Map.Entry<String,String>> iterator = attributes.entrySet().iterator(); iterator.hasNext(); ) {
final Map.Entry<String,String> entry = iterator.next();
final String value = entry.getValue();
query.append(AwsURLEncoder.urlEncode(entry.getKey())).append("=").append(AwsURLEncoder.urlEncode(value)).append("&");
}
String result = query.toString();
if (result != null && !result.equals(""))
result = "?" + result.substring(0, result.length() - 1);
return result;
}
public static Object unmarshalTheResponse(InputStream stream, AwsConfig awsConfig) throws IOException {
Object o = parse(stream, awsConfig);
return o;
}
private static Object parse(InputStream in, AwsConfig awsConfig) {
final DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
Element element = doc.getDocumentElement();
NodeHolder elementNodeHolder = new NodeHolder(element);
List<String> names = new ArrayList<String>();
List<NodeHolder> reservationset = elementNodeHolder.getSubNodes("reservationset");
for (NodeHolder reservation : reservationset) {
List<NodeHolder> items = reservation.getSubNodes("item");
for (NodeHolder item : items) {
NodeHolder instancesset = item.getSub("instancesset");
names.addAll(instancesset.getList("privateipaddress", awsConfig));
}
}
return names;
} catch (Exception e) {
logger.warning(e);
}
return new ArrayList<String>();
}
static class NodeHolder {
Node node;
public NodeHolder(Node node) {
this.node = node;
}
public NodeHolder getSub(String name) {
if (node != null) {
for (org.w3c.dom.Node node : new AbstractXmlConfigHelper.IterableNodeList(this.node.getChildNodes())) {
String nodeName = cleanNodeName(node.getNodeName());
if (name.equals(nodeName)) {
return new NodeHolder(node);
}
}
}
return new NodeHolder(null);
}
public List<NodeHolder> getSubNodes(String name) {
List<NodeHolder> list = new ArrayList<NodeHolder>();
if (node != null) {
for (org.w3c.dom.Node node : new AbstractXmlConfigHelper.IterableNodeList(this.node.getChildNodes())) {
String nodeName = cleanNodeName(node.getNodeName());
if (name.equals(nodeName)) {
list.add(new NodeHolder(node));
}
}
}
return list;
}
public List<String> getList(String name, AwsConfig awsConfig) {
List<String> list = new ArrayList<String>();
if (node == null) return list;
for (org.w3c.dom.Node node : new AbstractXmlConfigHelper.IterableNodeList(this.node.getChildNodes())) {
String nodeName = cleanNodeName(node.getNodeName());
if (!"item".equals(nodeName)) continue;
final NodeHolder nodeHolder = new NodeHolder(node);
final String state = getState(nodeHolder);
final String ip = getIp(name, nodeHolder);
final String instanceName = getInstanceName(nodeHolder);
if (ip != null) {
if (!acceptState(state)) {
logger.finest(format("Ignoring EC2 instance [%s][%s] reason: the instance is not running but %s", instanceName, ip, state));
} else if (!acceptTag(awsConfig, node)) {
logger.finest(format("Ignoring EC2 instance [%s][%s] reason: tag-key/tag-value don't match", instanceName, ip));
} else if (!acceptGroupName(awsConfig, node)) {
logger.finest(format("Ignoring EC2 instance [%s][%s] reason: security-group-name doesn't match", instanceName, ip));
} else {
list.add(ip);
logger.finest(format("Accepting EC2 instance [%s][%s]",instanceName, ip));
}
}
}
return list;
}
private boolean acceptState(String state) {
return "running".equals(state);
}
private static String getState(NodeHolder nodeHolder) {
final NodeHolder instancestate = nodeHolder.getSub("instancestate");
return instancestate.getSub("name").getNode().getFirstChild().getNodeValue();
}
private static String getInstanceName(NodeHolder nodeHolder) {
final NodeHolder tagSetNode = nodeHolder.getSub("tagset");
if (tagSetNode.getNode() == null) {
return null;
}
final NodeList childNodes = tagSetNode.getNode().getChildNodes();
for (int k = 0; k < childNodes.getLength(); k++) {
Node item = childNodes.item(k);
if (!item.getNodeName().equals("item")) continue;
NodeHolder itemHolder = new NodeHolder(item);
final Node keyNode = itemHolder.getSub("key").getNode();
if (keyNode == null || keyNode.getFirstChild() == null) continue;
final String nodeValue = keyNode.getFirstChild().getNodeValue();
if (!"Name".equals(nodeValue)) continue;
final Node valueNode = itemHolder.getSub("value").getNode();
if (valueNode == null || valueNode.getFirstChild() == null) continue;
return valueNode.getFirstChild().getNodeValue();
}
return null;
}
private static String getIp(String name, NodeHolder nodeHolder) {
final Node node1 = nodeHolder.getSub(name).getNode();
return node1 == null ? null : node1.getFirstChild().getNodeValue();
}
private boolean acceptTag(AwsConfig awsConfig, Node node) {
return applyTagFilter(node, awsConfig.getTagKey(), awsConfig.getTagValue());
}
private boolean acceptGroupName(AwsConfig awsConfig, Node node) {
return applyFilter(node, awsConfig.getSecurityGroupName(), "groupset", "groupname");
}
private boolean applyFilter(Node node, String filter, String set, String filterField) {
if (nullOrEmpty(filter)) {
return true;
} else {
for (NodeHolder group : new NodeHolder(node).getSub(set).getSubNodes("item")) {
NodeHolder nh = group.getSub(filterField);
if (nh != null && nh.getNode().getFirstChild() != null && filter.equals(nh.getNode().getFirstChild().getNodeValue())) {
return true;
}
}
return false;
}
}
private boolean applyTagFilter(Node node, String keyExpected, String valueExpected) {
if (nullOrEmpty(keyExpected)) {
return true;
} else {
for (NodeHolder group : new NodeHolder(node).getSub("tagset").getSubNodes("item")) {
if (keyEquals(keyExpected, group) &&
(nullOrEmpty(valueExpected) || valueEquals(valueExpected, group))) {
return true;
}
}
return false;
}
}
private boolean valueEquals(String valueExpected, NodeHolder group) {
NodeHolder nhValue = group.getSub("value");
return nhValue != null && nhValue.getNode().getFirstChild() != null && valueExpected.equals(nhValue.getNode().getFirstChild().getNodeValue());
}
private boolean nullOrEmpty(String keyExpected) {
return keyExpected == null || keyExpected.equals("");
}
private boolean keyEquals(String keyExpected, NodeHolder group) {
NodeHolder nhKey = group.getSub("key");
return nhKey != null && nhKey.getNode().getFirstChild() != null && keyExpected.equals(nhKey.getNode().getFirstChild().getNodeValue());
}
public Node getNode() {
return node;
}
}
} | true | hazelcast-cloud_src_main_java_com_hazelcast_aws_utility_CloudyUtility.java |
68 | static class NodeHolder {
Node node;
public NodeHolder(Node node) {
this.node = node;
}
public NodeHolder getSub(String name) {
if (node != null) {
for (org.w3c.dom.Node node : new AbstractXmlConfigHelper.IterableNodeList(this.node.getChildNodes())) {
String nodeName = cleanNodeName(node.getNodeName());
if (name.equals(nodeName)) {
return new NodeHolder(node);
}
}
}
return new NodeHolder(null);
}
public List<NodeHolder> getSubNodes(String name) {
List<NodeHolder> list = new ArrayList<NodeHolder>();
if (node != null) {
for (org.w3c.dom.Node node : new AbstractXmlConfigHelper.IterableNodeList(this.node.getChildNodes())) {
String nodeName = cleanNodeName(node.getNodeName());
if (name.equals(nodeName)) {
list.add(new NodeHolder(node));
}
}
}
return list;
}
public List<String> getList(String name, AwsConfig awsConfig) {
List<String> list = new ArrayList<String>();
if (node == null) return list;
for (org.w3c.dom.Node node : new AbstractXmlConfigHelper.IterableNodeList(this.node.getChildNodes())) {
String nodeName = cleanNodeName(node.getNodeName());
if (!"item".equals(nodeName)) continue;
final NodeHolder nodeHolder = new NodeHolder(node);
final String state = getState(nodeHolder);
final String ip = getIp(name, nodeHolder);
final String instanceName = getInstanceName(nodeHolder);
if (ip != null) {
if (!acceptState(state)) {
logger.finest(format("Ignoring EC2 instance [%s][%s] reason: the instance is not running but %s", instanceName, ip, state));
} else if (!acceptTag(awsConfig, node)) {
logger.finest(format("Ignoring EC2 instance [%s][%s] reason: tag-key/tag-value don't match", instanceName, ip));
} else if (!acceptGroupName(awsConfig, node)) {
logger.finest(format("Ignoring EC2 instance [%s][%s] reason: security-group-name doesn't match", instanceName, ip));
} else {
list.add(ip);
logger.finest(format("Accepting EC2 instance [%s][%s]",instanceName, ip));
}
}
}
return list;
}
private boolean acceptState(String state) {
return "running".equals(state);
}
private static String getState(NodeHolder nodeHolder) {
final NodeHolder instancestate = nodeHolder.getSub("instancestate");
return instancestate.getSub("name").getNode().getFirstChild().getNodeValue();
}
private static String getInstanceName(NodeHolder nodeHolder) {
final NodeHolder tagSetNode = nodeHolder.getSub("tagset");
if (tagSetNode.getNode() == null) {
return null;
}
final NodeList childNodes = tagSetNode.getNode().getChildNodes();
for (int k = 0; k < childNodes.getLength(); k++) {
Node item = childNodes.item(k);
if (!item.getNodeName().equals("item")) continue;
NodeHolder itemHolder = new NodeHolder(item);
final Node keyNode = itemHolder.getSub("key").getNode();
if (keyNode == null || keyNode.getFirstChild() == null) continue;
final String nodeValue = keyNode.getFirstChild().getNodeValue();
if (!"Name".equals(nodeValue)) continue;
final Node valueNode = itemHolder.getSub("value").getNode();
if (valueNode == null || valueNode.getFirstChild() == null) continue;
return valueNode.getFirstChild().getNodeValue();
}
return null;
}
private static String getIp(String name, NodeHolder nodeHolder) {
final Node node1 = nodeHolder.getSub(name).getNode();
return node1 == null ? null : node1.getFirstChild().getNodeValue();
}
private boolean acceptTag(AwsConfig awsConfig, Node node) {
return applyTagFilter(node, awsConfig.getTagKey(), awsConfig.getTagValue());
}
private boolean acceptGroupName(AwsConfig awsConfig, Node node) {
return applyFilter(node, awsConfig.getSecurityGroupName(), "groupset", "groupname");
}
private boolean applyFilter(Node node, String filter, String set, String filterField) {
if (nullOrEmpty(filter)) {
return true;
} else {
for (NodeHolder group : new NodeHolder(node).getSub(set).getSubNodes("item")) {
NodeHolder nh = group.getSub(filterField);
if (nh != null && nh.getNode().getFirstChild() != null && filter.equals(nh.getNode().getFirstChild().getNodeValue())) {
return true;
}
}
return false;
}
}
private boolean applyTagFilter(Node node, String keyExpected, String valueExpected) {
if (nullOrEmpty(keyExpected)) {
return true;
} else {
for (NodeHolder group : new NodeHolder(node).getSub("tagset").getSubNodes("item")) {
if (keyEquals(keyExpected, group) &&
(nullOrEmpty(valueExpected) || valueEquals(valueExpected, group))) {
return true;
}
}
return false;
}
}
private boolean valueEquals(String valueExpected, NodeHolder group) {
NodeHolder nhValue = group.getSub("value");
return nhValue != null && nhValue.getNode().getFirstChild() != null && valueExpected.equals(nhValue.getNode().getFirstChild().getNodeValue());
}
private boolean nullOrEmpty(String keyExpected) {
return keyExpected == null || keyExpected.equals("");
}
private boolean keyEquals(String keyExpected, NodeHolder group) {
NodeHolder nhKey = group.getSub("key");
return nhKey != null && nhKey.getNode().getFirstChild() != null && keyExpected.equals(nhKey.getNode().getFirstChild().getNodeValue());
}
public Node getNode() {
return node;
}
} | true | hazelcast-cloud_src_main_java_com_hazelcast_aws_utility_CloudyUtility.java |
69 | @RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class CloudyUtilityTest {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n" +
" <requestId>c0f82bf8-b7f5-4cf1-bbfa-b95ea4bd38da</requestId>\n" +
" <reservationSet>\n" +
" <item>\n" +
" <reservationId>r-48ff3826</reservationId>\n" +
" <ownerId>665466731577</ownerId>\n" +
" <groupSet>\n" +
" <item>\n" +
" <groupId>sg-b67baddf</groupId>\n" +
" <groupName>hazelcast</groupName>\n" +
" </item>\n" +
" </groupSet>\n" +
" <instancesSet>\n" +
" <item>\n" +
" <instanceId>i-0a0c616a</instanceId>\n" +
" <imageId>ami-7f418316</imageId>\n" +
" <instanceState>\n" +
" <code>16</code>\n" +
" <name>running</name>\n" +
" </instanceState>\n" +
" <privateDnsName>domU-12-31-39-07-C5-C4.compute-1.internal</privateDnsName>\n" +
" <dnsName>ec2-50-17-19-37.compute-1.amazonaws.com</dnsName>\n" +
" <reason/>\n" +
" <keyName>hazelcast_key_pair</keyName>\n" +
" <amiLaunchIndex>0</amiLaunchIndex>\n" +
" <productCodes/>\n" +
" <instanceType>t1.micro</instanceType>\n" +
" <launchTime>2011-09-27T11:37:35.000Z</launchTime>\n" +
" <placement>\n" +
" <availabilityZone>us-east-1a</availabilityZone>\n" +
" <groupName/>\n" +
" <tenancy>default</tenancy>\n" +
" </placement>\n" +
" <kernelId>aki-805ea7e9</kernelId>\n" +
" <monitoring>\n" +
" <state>disabled</state>\n" +
" </monitoring>\n" +
" <privateIpAddress>10.209.198.50</privateIpAddress>\n" +
" <ipAddress>50.17.19.37</ipAddress>\n" +
" <groupSet>\n" +
" <item>\n" +
" <groupId>sg-b67baddf</groupId>\n" +
" <groupName>hazelcast</groupName>\n" +
" </item>\n" +
" </groupSet>\n" +
" <architecture>i386</architecture>\n" +
" <rootDeviceType>ebs</rootDeviceType>\n" +
" <rootDeviceName>/dev/sda1</rootDeviceName>\n" +
" <blockDeviceMapping>\n" +
" <item>\n" +
" <deviceName>/dev/sda1</deviceName>\n" +
" <ebs>\n" +
" <volumeId>vol-d5bdffbf</volumeId>\n" +
" <status>attached</status>\n" +
" <attachTime>2011-09-27T11:37:56.000Z</attachTime>\n" +
" <deleteOnTermination>true</deleteOnTermination>\n" +
" </ebs>\n" +
" </item>\n" +
" </blockDeviceMapping>\n" +
" <virtualizationType>paravirtual</virtualizationType>\n" +
" <clientToken/>\n" +
" <tagSet>\n" +
" <item>\n" +
" <key>name2</key>\n" +
" <value>value2</value>\n" +
" </item>\n" +
" <item>\n" +
" <key>Name1</key>\n" +
" <value>value1</value>\n" +
" </item>\n" +
" <item>\n" +
" <key>name</key>\n" +
" <value/>\n" +
" </item>\n" +
" </tagSet>\n" +
" <hypervisor>xen</hypervisor>\n" +
" </item>\n" +
" <item>\n" +
" <instanceId>i-0c0c616c</instanceId>\n" +
" <imageId>ami-7f418316</imageId>\n" +
" <instanceState>\n" +
" <code>16</code>\n" +
" <name>running</name>\n" +
" </instanceState>\n" +
" <privateDnsName>domU-12-31-39-07-C2-60.compute-1.internal</privateDnsName>\n" +
" <dnsName>ec2-50-16-102-143.compute-1.amazonaws.com</dnsName>\n" +
" <reason/>\n" +
" <keyName>hazelcast_key_pair</keyName>\n" +
" <amiLaunchIndex>1</amiLaunchIndex>\n" +
" <productCodes/>\n" +
" <instanceType>t1.micro</instanceType>\n" +
" <launchTime>2011-09-27T11:37:35.000Z</launchTime>\n" +
" <placement>\n" +
" <availabilityZone>us-east-1a</availabilityZone>\n" +
" <groupName/>\n" +
" <tenancy>default</tenancy>\n" +
" </placement>\n" +
" <kernelId>aki-805ea7e9</kernelId>\n" +
" <monitoring>\n" +
" <state>disabled</state>\n" +
" </monitoring>\n" +
" <privateIpAddress>10.209.193.170</privateIpAddress>\n" +
" <ipAddress>50.16.102.143</ipAddress>\n" +
" <groupSet>\n" +
" <item>\n" +
" <groupId>sg-b67baddf</groupId>\n" +
" <groupName>hazelcast</groupName>\n" +
" </item>\n" +
" </groupSet>\n" +
" <architecture>i386</architecture>\n" +
" <rootDeviceType>ebs</rootDeviceType>\n" +
" <rootDeviceName>/dev/sda1</rootDeviceName>\n" +
" <blockDeviceMapping>\n" +
" <item>\n" +
" <deviceName>/dev/sda1</deviceName>\n" +
" <ebs>\n" +
" <volumeId>vol-abbdffc1</volumeId>\n" +
" <status>attached</status>\n" +
" <attachTime>2011-09-27T11:37:57.000Z</attachTime>\n" +
" <deleteOnTermination>true</deleteOnTermination>\n" +
" </ebs>\n" +
" </item>\n" +
" </blockDeviceMapping>\n" +
" <virtualizationType>paravirtual</virtualizationType>\n" +
" <clientToken/>\n" +
" <tagSet>\n" +
" <item>\n" +
" <key>Name1</key>\n" +
" <value>value1</value>\n" +
" </item>\n" +
" <item>\n" +
" <key>name2</key>\n" +
" <value>value2</value>\n" +
" </item>\n" +
" </tagSet>\n" +
" <hypervisor>xen</hypervisor>\n" +
" </item>\n" +
" </instancesSet>\n" +
" <requesterId>058890971305</requesterId>\n" +
" </item>\n" +
" </reservationSet>\n" +
"</DescribeInstancesResponse>";
@Test
public void testNoTags() throws IOException {
InputStream is = new ByteArrayInputStream(xml.getBytes());
AwsConfig awsConfig = new AwsConfig();
awsConfig.setAccessKey("some-access-key");
awsConfig.setSecretKey("some-secret-key");
awsConfig.setSecurityGroupName("hazelcast");
List<String> result = (List<String>) CloudyUtility.unmarshalTheResponse(is, awsConfig);
assertEquals(2, result.size());
}
@Test
public void testTagsBothNodeHave() throws IOException {
InputStream is = new ByteArrayInputStream(xml.getBytes());
AwsConfig awsConfig = new AwsConfig();
awsConfig.setAccessKey("some-access-key");
awsConfig.setSecretKey("some-secret-key");
awsConfig.setSecurityGroupName("hazelcast");
awsConfig.setTagKey("Name1");
awsConfig.setTagValue("value1");
List<String> result = (List<String>) CloudyUtility.unmarshalTheResponse(is, awsConfig);
assertEquals(2, result.size());
}
@Test
public void testTagOnlyOneNodeHave() throws IOException {
InputStream is = new ByteArrayInputStream(xml.getBytes());
AwsConfig awsConfig = new AwsConfig();
awsConfig.setAccessKey("some-access-key");
awsConfig.setSecretKey("some-secret-key");
awsConfig.setSecurityGroupName("hazelcast");
awsConfig.setTagKey("name");
awsConfig.setTagValue("");
List<String> result = (List<String>) CloudyUtility.unmarshalTheResponse(is, awsConfig);
assertEquals(1, result.size());
}
} | false | hazelcast-cloud_src_test_java_com_hazelcast_aws_utility_CloudyUtilityTest.java |
70 | public abstract class AllPartitionsClientRequest extends ClientRequest {
@Override
final void process() throws Exception {
ClientEndpoint endpoint = getEndpoint();
OperationFactory operationFactory = new OperationFactoryWrapper(createOperationFactory(), endpoint.getUuid());
Map<Integer, Object> map = clientEngine.invokeOnAllPartitions(getServiceName(), operationFactory);
Object result = reduce(map);
endpoint.sendResponse(result, getCallId());
}
protected abstract OperationFactory createOperationFactory();
protected abstract Object reduce(Map<Integer, Object> map);
} | false | hazelcast_src_main_java_com_hazelcast_client_AllPartitionsClientRequest.java |
71 | public class AuthenticationException extends HazelcastException {
public AuthenticationException() {
super("Wrong group name and password.");
}
public AuthenticationException(String message) {
super(message);
}
} | false | hazelcast_src_main_java_com_hazelcast_client_AuthenticationException.java |
72 | public final class AuthenticationRequest extends CallableClientRequest {
private Credentials credentials;
private ClientPrincipal principal;
private boolean reAuth;
private boolean firstConnection;
public AuthenticationRequest() {
}
public AuthenticationRequest(Credentials credentials) {
this.credentials = credentials;
}
public AuthenticationRequest(Credentials credentials, ClientPrincipal principal) {
this.credentials = credentials;
this.principal = principal;
}
public Object call() throws Exception {
boolean authenticated = authenticate();
if (authenticated) {
return handleAuthenticated();
} else {
return handleUnauthenticated();
}
}
private boolean authenticate() {
ClientEngineImpl clientEngine = getService();
Connection connection = endpoint.getConnection();
ILogger logger = clientEngine.getLogger(getClass());
boolean authenticated;
if (credentials == null) {
authenticated = false;
logger.severe("Could not retrieve Credentials object!");
} else if (clientEngine.getSecurityContext() != null) {
authenticated = authenticate(clientEngine.getSecurityContext());
} else if (credentials instanceof UsernamePasswordCredentials) {
UsernamePasswordCredentials usernamePasswordCredentials = (UsernamePasswordCredentials) credentials;
authenticated = authenticate(usernamePasswordCredentials);
} else {
authenticated = false;
logger.severe("Hazelcast security is disabled.\nUsernamePasswordCredentials or cluster "
+ "group-name and group-password should be used for authentication!\n"
+ "Current credentials type is: " + credentials.getClass().getName());
}
logger.log((authenticated ? Level.INFO : Level.WARNING), "Received auth from " + connection
+ ", " + (authenticated ? "successfully authenticated" : "authentication failed"));
return authenticated;
}
private boolean authenticate(UsernamePasswordCredentials credentials) {
ClientEngineImpl clientEngine = getService();
GroupConfig groupConfig = clientEngine.getConfig().getGroupConfig();
String nodeGroupName = groupConfig.getName();
String nodeGroupPassword = groupConfig.getPassword();
boolean usernameMatch = nodeGroupName.equals(credentials.getUsername());
boolean passwordMatch = nodeGroupPassword.equals(credentials.getPassword());
return usernameMatch && passwordMatch;
}
private boolean authenticate(SecurityContext securityContext) {
Connection connection = endpoint.getConnection();
credentials.setEndpoint(connection.getInetAddress().getHostAddress());
try {
LoginContext lc = securityContext.createClientLoginContext(credentials);
lc.login();
endpoint.setLoginContext(lc);
return true;
} catch (LoginException e) {
ILogger logger = clientEngine.getLogger(getClass());
logger.warning(e);
return false;
}
}
private Object handleUnauthenticated() {
ClientEngineImpl clientEngine = getService();
clientEngine.removeEndpoint(endpoint.getConnection());
return new AuthenticationException("Invalid credentials!");
}
private Object handleAuthenticated() {
ClientEngineImpl clientEngine = getService();
if (principal != null && reAuth) {
principal = new ClientPrincipal(principal.getUuid(), clientEngine.getLocalMember().getUuid());
reAuthLocal();
Collection<MemberImpl> members = clientEngine.getClusterService().getMemberList();
for (MemberImpl member : members) {
if (!member.localMember()) {
ClientReAuthOperation op = new ClientReAuthOperation(principal.getUuid(), firstConnection);
clientEngine.sendOperation(op, member.getAddress());
}
}
}
if (principal == null) {
principal = new ClientPrincipal(endpoint.getUuid(), clientEngine.getLocalMember().getUuid());
}
endpoint.authenticated(principal, firstConnection);
clientEngine.bind(endpoint);
return new SerializableCollection(clientEngine.toData(clientEngine.getThisAddress()), clientEngine.toData(principal));
}
private void reAuthLocal() {
final Set<ClientEndpoint> endpoints = clientEngine.getEndpoints(principal.getUuid());
for (ClientEndpoint endpoint : endpoints) {
endpoint.authenticated(principal, firstConnection);
}
}
public String getServiceName() {
return ClientEngineImpl.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return ClientPortableHook.ID;
}
@Override
public int getClassId() {
return ClientPortableHook.AUTH;
}
public void setReAuth(boolean reAuth) {
this.reAuth = reAuth;
}
public boolean isFirstConnection() {
return firstConnection;
}
public void setFirstConnection(boolean firstConnection) {
this.firstConnection = firstConnection;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writePortable("credentials", (Portable) credentials);
if (principal != null) {
writer.writePortable("principal", principal);
} else {
writer.writeNullPortable("principal", ClientPortableHook.ID, ClientPortableHook.PRINCIPAL);
}
writer.writeBoolean("reAuth", reAuth);
writer.writeBoolean("firstConnection", firstConnection);
}
@Override
public void read(PortableReader reader) throws IOException {
credentials = (Credentials) reader.readPortable("credentials");
principal = reader.readPortable("principal");
reAuth = reader.readBoolean("reAuth");
firstConnection = reader.readBoolean("firstConnection");
}
@Override
public Permission getRequiredPermission() {
return null;
}
} | true | hazelcast_src_main_java_com_hazelcast_client_AuthenticationRequest.java |
73 | public abstract class BaseClientRemoveListenerRequest extends CallableClientRequest {
protected String name;
protected String registrationId;
protected BaseClientRemoveListenerRequest() {
}
protected BaseClientRemoveListenerRequest(String name, String registrationId) {
this.name = name;
this.registrationId = registrationId;
}
public String getRegistrationId() {
return registrationId;
}
public void setRegistrationId(String registrationId) {
this.registrationId = registrationId;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
writer.writeUTF("r", registrationId);
}
@Override
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
registrationId = reader.readUTF("r");
}
} | false | hazelcast_src_main_java_com_hazelcast_client_BaseClientRemoveListenerRequest.java |
74 | public abstract class CallableClientRequest extends ClientRequest implements Callable {
@Override
final void process() throws Exception {
ClientEndpoint endpoint = getEndpoint();
try {
Object result = call();
endpoint.sendResponse(result, getCallId());
} catch (Exception e) {
clientEngine.getLogger(getClass()).warning(e);
endpoint.sendResponse(e, getCallId());
}
}
} | false | hazelcast_src_main_java_com_hazelcast_client_CallableClientRequest.java |
75 | @Ignore//TODO
@RunWith(Categories.class)
@Categories.IncludeCategory(ClientCompatibleTest.class)
@Suite.SuiteClasses({})
public class ClientCompatibleTestsSuit {
@BeforeClass
public static void setUp() {
System.setProperty(TestEnvironment.HAZELCAST_TEST_USE_NETWORK, "true");
System.setProperty(TestEnvironment.HAZELCAST_TEST_USE_CLIENT, "true");
System.setProperty("hazelcast.version.check.enabled", "false");
System.setProperty("hazelcast.mancenter.enabled", "false");
System.setProperty("hazelcast.wait.seconds.before.join", "1");
System.setProperty("hazelcast.local.localAddress", "127.0.0.1");
System.setProperty("java.net.preferIPv4Stack", "true");
}
} | false | hazelcast-client_src_test_java_com_hazelcast_client_ClientCompatibleTestsSuit.java |
76 | public class ClientCreateRequest extends CallableClientRequest implements Portable, RetryableRequest, SecureRequest {
private String name;
private String serviceName;
public ClientCreateRequest() {
}
public ClientCreateRequest(String name, String serviceName) {
this.name = name;
this.serviceName = serviceName;
}
@Override
public Object call() throws Exception {
ProxyService proxyService = clientEngine.getProxyService();
proxyService.initializeDistributedObject(serviceName, name);
return null;
}
@Override
public String getServiceName() {
return serviceName;
}
@Override
public int getFactoryId() {
return ClientPortableHook.ID;
}
@Override
public int getClassId() {
return ClientPortableHook.CREATE_PROXY;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
writer.writeUTF("s", serviceName);
}
@Override
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
serviceName = reader.readUTF("s");
}
@Override
public Permission getRequiredPermission() {
return ActionConstants.getPermission(name, serviceName, ActionConstants.ACTION_CREATE);
}
} | false | hazelcast_src_main_java_com_hazelcast_client_ClientCreateRequest.java |
77 | public final class ClientDataSerializerHook implements DataSerializerHook {
public static final int ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.CLIENT_DS_FACTORY, -3);
public static final int CLIENT_RESPONSE = 1;
@Override
public int getFactoryId() {
return ID;
}
@Override
public DataSerializableFactory createFactory() {
return new DataSerializableFactory() {
@Override
public IdentifiedDataSerializable create(int typeId) {
switch (typeId) {
case CLIENT_RESPONSE:
return new ClientResponse();
default:
return null;
}
}
};
}
} | false | hazelcast_src_main_java_com_hazelcast_client_ClientDataSerializerHook.java |
78 | return new DataSerializableFactory() {
@Override
public IdentifiedDataSerializable create(int typeId) {
switch (typeId) {
case CLIENT_RESPONSE:
return new ClientResponse();
default:
return null;
}
}
}; | false | hazelcast_src_main_java_com_hazelcast_client_ClientDataSerializerHook.java |
79 | public class ClientDestroyRequest extends CallableClientRequest implements Portable, RetryableRequest, SecureRequest {
private String name;
private String serviceName;
public ClientDestroyRequest() {
}
public ClientDestroyRequest(String name, String serviceName) {
this.name = name;
this.serviceName = serviceName;
}
@Override
public Object call() throws Exception {
ProxyService proxyService = getClientEngine().getProxyService();
proxyService.destroyDistributedObject(getServiceName(), name);
return null;
}
@Override
public String getServiceName() {
return serviceName;
}
@Override
public int getFactoryId() {
return ClientPortableHook.ID;
}
@Override
public int getClassId() {
return ClientPortableHook.DESTROY_PROXY;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
writer.writeUTF("s", serviceName);
}
@Override
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
serviceName = reader.readUTF("s");
}
@Override
public Permission getRequiredPermission() {
return getPermission(name, serviceName, ActionConstants.ACTION_DESTROY);
}
} | false | hazelcast_src_main_java_com_hazelcast_client_ClientDestroyRequest.java |
80 | public class ClientDisconnectionOperation extends AbstractOperation implements UrgentSystemOperation {
private String clientUuid;
public ClientDisconnectionOperation() {
}
public ClientDisconnectionOperation(String clientUuid) {
this.clientUuid = clientUuid;
}
@Override
public void run() throws Exception {
ClientEngineImpl engine = getService();
Set<ClientEndpoint> endpoints = engine.getEndpoints(clientUuid);
for (ClientEndpoint endpoint : endpoints) {
Connection connection = endpoint.getConnection();
engine.removeEndpoint(connection, true);
}
NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine();
nodeEngine.onClientDisconnected(clientUuid);
Collection<ClientAwareService> services = nodeEngine.getServices(ClientAwareService.class);
for (ClientAwareService service : services) {
service.clientDisconnected(clientUuid);
}
}
@Override
public boolean returnsResponse() {
return false;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeUTF(clientUuid);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
clientUuid = in.readUTF();
}
} | true | hazelcast_src_main_java_com_hazelcast_client_ClientDisconnectionOperation.java |
81 | public final class ClientEndpoint implements Client {
private final ClientEngineImpl clientEngine;
private final Connection conn;
private final ConcurrentMap<String, TransactionContext> transactionContextMap
= new ConcurrentHashMap<String, TransactionContext>();
private final List<Runnable> removeListenerActions = Collections.synchronizedList(new LinkedList<Runnable>());
private final SocketAddress socketAddress;
private String uuid;
private LoginContext loginContext;
private ClientPrincipal principal;
private boolean firstConnection;
private volatile boolean authenticated;
ClientEndpoint(ClientEngineImpl clientEngine, Connection conn, String uuid) {
this.clientEngine = clientEngine;
this.conn = conn;
if (conn instanceof TcpIpConnection) {
TcpIpConnection tcpIpConnection = (TcpIpConnection) conn;
socketAddress = tcpIpConnection.getSocketChannelWrapper().socket().getRemoteSocketAddress();
} else {
socketAddress = null;
}
this.uuid = uuid;
}
Connection getConnection() {
return conn;
}
@Override
public String getUuid() {
return uuid;
}
public boolean live() {
return conn.live();
}
void setLoginContext(LoginContext loginContext) {
this.loginContext = loginContext;
}
public Subject getSubject() {
return loginContext != null ? loginContext.getSubject() : null;
}
public boolean isFirstConnection() {
return firstConnection;
}
void authenticated(ClientPrincipal principal, boolean firstConnection) {
this.principal = principal;
this.uuid = principal.getUuid();
this.firstConnection = firstConnection;
this.authenticated = true;
}
public boolean isAuthenticated() {
return authenticated;
}
public ClientPrincipal getPrincipal() {
return principal;
}
@Override
public InetSocketAddress getSocketAddress() {
return (InetSocketAddress) socketAddress;
}
@Override
public ClientType getClientType() {
switch (conn.getType()) {
case JAVA_CLIENT:
return ClientType.JAVA;
case CSHARP_CLIENT:
return ClientType.CSHARP;
case CPP_CLIENT:
return ClientType.CPP;
case PYTHON_CLIENT:
return ClientType.PYTHON;
case RUBY_CLIENT:
return ClientType.RUBY;
case BINARY_CLIENT:
return ClientType.OTHER;
default:
throw new IllegalArgumentException("Invalid connection type: " + conn.getType());
}
}
public TransactionContext getTransactionContext(String txnId) {
final TransactionContext transactionContext = transactionContextMap.get(txnId);
if (transactionContext == null) {
throw new TransactionException("No transaction context found for txnId:" + txnId);
}
return transactionContext;
}
public void setTransactionContext(TransactionContext transactionContext) {
transactionContextMap.put(transactionContext.getTxnId(), transactionContext);
}
public void removeTransactionContext(String txnId) {
transactionContextMap.remove(txnId);
}
public void setListenerRegistration(final String service, final String topic, final String id) {
removeListenerActions.add(new Runnable() {
@Override
public void run() {
EventService eventService = clientEngine.getEventService();
eventService.deregisterListener(service, topic, id);
}
});
}
public void setDistributedObjectListener(final String id) {
removeListenerActions.add(new Runnable() {
@Override
public void run() {
clientEngine.getProxyService().removeProxyListener(id);
}
});
}
public void clearAllListeners() {
for (Runnable removeAction : removeListenerActions) {
try {
removeAction.run();
} catch (Exception e) {
getLogger().warning("Exception during destroy action", e);
}
}
removeListenerActions.clear();
}
void destroy() throws LoginException {
for (Runnable removeAction : removeListenerActions) {
try {
removeAction.run();
} catch (Exception e) {
getLogger().warning("Exception during destroy action", e);
}
}
LoginContext lc = loginContext;
if (lc != null) {
lc.logout();
}
for (TransactionContext context : transactionContextMap.values()) {
Transaction transaction = TransactionAccessor.getTransaction(context);
if (context.isXAManaged() && transaction.getState() == PREPARED) {
TransactionManagerServiceImpl transactionManager =
(TransactionManagerServiceImpl) clientEngine.getTransactionManagerService();
transactionManager.addTxBackupLogForClientRecovery(transaction);
} else {
try {
context.rollbackTransaction();
} catch (HazelcastInstanceNotActiveException e) {
getLogger().finest(e);
} catch (Exception e) {
getLogger().warning(e);
}
}
}
authenticated = false;
}
private ILogger getLogger() {
return clientEngine.getLogger(getClass());
}
public void sendResponse(Object response, int callId) {
boolean isError = false;
Object clientResponseObject;
if (response == null) {
clientResponseObject = ClientEngineImpl.NULL;
} else if (response instanceof Throwable) {
isError = true;
ClientExceptionConverter converter = ClientExceptionConverters.get(getClientType());
clientResponseObject = converter.convert((Throwable) response);
} else {
clientResponseObject = response;
}
ClientResponse clientResponse = new ClientResponse(clientEngine.toData(clientResponseObject), isError, callId);
clientEngine.sendResponse(this, clientResponse);
}
public void sendEvent(Object event, int callId) {
Data data = clientEngine.toData(event);
clientEngine.sendResponse(this, new ClientResponse(data, callId, true));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ClientEndpoint{");
sb.append("conn=").append(conn);
sb.append(", uuid='").append(uuid).append('\'');
sb.append(", firstConnection=").append(firstConnection);
sb.append(", authenticated=").append(authenticated);
sb.append('}');
return sb.toString();
}
} | true | hazelcast_src_main_java_com_hazelcast_client_ClientEndpoint.java |
82 | removeListenerActions.add(new Runnable() {
@Override
public void run() {
EventService eventService = clientEngine.getEventService();
eventService.deregisterListener(service, topic, id);
}
}); | false | hazelcast_src_main_java_com_hazelcast_client_ClientEndpoint.java |
83 | removeListenerActions.add(new Runnable() {
@Override
public void run() {
clientEngine.getProxyService().removeProxyListener(id);
}
}); | false | hazelcast_src_main_java_com_hazelcast_client_ClientEndpoint.java |
84 | public interface ClientEngine {
int getClientEndpointCount();
InternalPartitionService getPartitionService();
ClusterService getClusterService();
SerializationService getSerializationService();
EventService getEventService();
TransactionManagerService getTransactionManagerService();
ProxyService getProxyService();
Config getConfig();
ILogger getLogger(Class clazz);
ILogger getLogger(String className);
Object toObject(Data data);
Data toData(Object obj);
Address getMasterAddress();
Address getThisAddress();
MemberImpl getLocalMember();
SecurityContext getSecurityContext();
} | false | hazelcast_src_main_java_com_hazelcast_client_ClientEngine.java |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 31