use of edu.umass.cs.gnscommon.packets.CommandPacket in project GNS by MobilityFirst.
the class AbstractGNSClient method desktopSendCommmandAndWait.
// arun: changed this to return CommandValueReturnPacket
private ResponsePacket desktopSendCommmandAndWait(JSONObject command) throws IOException {
Object myMonitor = new Object();
long id;
monitorMap.put(id = this.generateNextRequestID(), myMonitor);
CommandPacket commandPacket = desktopSendCommmandNoWait(command, id);
// now we wait until the correct packet comes back
try {
GNSClientConfig.getLogger().log(Level.FINE, "{0} waiting for query {1}", new Object[] { this, id + "" });
long monitorStartTime = System.currentTimeMillis();
if (!USE_GLOBAL_MONITOR) {
synchronized (myMonitor) {
while (monitorMap.containsKey(id) && (readTimeout == 0 || System.currentTimeMillis() - monitorStartTime < readTimeout)) {
myMonitor.wait(readTimeout);
}
}
} else {
synchronized (monitor) {
while (!resultMap.containsKey(id) && (readTimeout == 0 || System.currentTimeMillis() - monitorStartTime < readTimeout)) {
monitor.wait(readTimeout);
}
}
}
if (readTimeout != 0 && System.currentTimeMillis() - monitorStartTime >= readTimeout) {
return getTimeoutResponse(this, commandPacket);
}
GNSClientConfig.getLogger().log(Level.FINE, "Response received for query {0}", new Object[] { id + "" });
} catch (InterruptedException x) {
GNSClientConfig.getLogger().severe("Wait for return packet was interrupted " + x);
}
//CommandResult
Request result = resultMap.remove(id);
GNSClientConfig.getLogger().log(Level.FINE, "{0} received response {1} ", new Object[] { this, result.getSummary() });
return result instanceof ResponsePacket ? ((ResponsePacket) result) : new ResponsePacket(result.getServiceName(), id, ResponseCode.ACTIVE_REPLICA_EXCEPTION, ((ActiveReplicaError) result).getResponseMessage());
}
use of edu.umass.cs.gnscommon.packets.CommandPacket in project GNS by MobilityFirst.
the class AbstractGNSClient method desktopSendCommmandNoWait.
private CommandPacket desktopSendCommmandNoWait(JSONObject command, long id) throws IOException {
long startTime = System.currentTimeMillis();
CommandPacket packet = new CommandPacket(id, command);
/* arun: moved this here from createCommand. This is the right place to
* put it because it is not easy to change "command" once it has been
* signed, and the command creation methods are and should be static. */
packet.setForceCoordinatedReads(this.isForceCoordinatedReads());
GNSClientConfig.getLogger().log(Level.FINE, "{0} sending {1}:{2}", new Object[] { this, id + "", packet.getSummary() });
sendCommandPacket(packet);
DelayProfiler.updateDelay("desktopSendCommmandNoWait", startTime);
return packet;
}
use of edu.umass.cs.gnscommon.packets.CommandPacket in project GNS by MobilityFirst.
the class ClientAsynchExample method main.
/**
*
* @param args
* @throws IOException
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws ClientException
* @throws InvalidKeyException
* @throws SignatureException
* @throws Exception
*/
public static void main(String[] args) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, ClientException, InvalidKeyException, SignatureException, Exception {
// Create the client
GNSClientCommands client = new GNSClientCommands(null);
GuidEntry accountGuidEntry = null;
try {
// Create a guid (which is also an account guid)
accountGuidEntry = GuidUtils.lookupOrCreateAccountGuid(client, ACCOUNT_ALIAS, "password", true);
} catch (Exception e) {
System.out.println("Exception during accountGuid creation: " + e);
e.printStackTrace();
System.exit(1);
}
System.out.println("Client connected to GNS");
JSONObject command;
if (args.length > 0 && args[0].equals("-write")) {
JSONObject json = new JSONObject("{\"occupation\":\"busboy\"," + "\"friends\":[\"Joe\",\"Sam\",\"Billy\"]," + "\"gibberish\":{\"meiny\":\"bloop\",\"einy\":\"floop\"}," + "\"location\":\"work\",\"name\":\"frank\"}");
command = createAndSignCommand(CommandType.ReplaceUserJSON, accountGuidEntry, GNSProtocol.GUID.toString(), accountGuidEntry.getGuid(), GNSProtocol.USER_JSON.toString(), json.toString(), GNSProtocol.WRITER.toString(), accountGuidEntry.getGuid());
} else {
command = createAndSignCommand(CommandType.Read, accountGuidEntry, GNSProtocol.GUID.toString(), accountGuidEntry.getGuid(), GNSProtocol.FIELD.toString(), "occupation", GNSProtocol.READER.toString(), accountGuidEntry.getGuid());
}
// Create the command packet with a bogus id
// arun: can not change request ID
CommandPacket commandPacket = new CommandPacket((long) (Math.random() * Long.MAX_VALUE), command);
// Keep track of what we've sent for the other thread to look at.
Set<Long> pendingIds = Collections.newSetFromMap(new ConcurrentHashMap<Long, Boolean>());
// Create and run another thread to pick up the responses
Runnable companion = new Runnable() {
@Override
public void run() {
lookForResponses(client, pendingIds);
}
};
//Does this on Android as of 9/16:
//ERROR: ClientAsynchExample.java:114: Lambda coming from jar file need their interfaces
//on the classpath to be compiled, unknown interfaces are java.lang.Runnable
// Runnable companion = () -> {
// lookForResponses(client, pendingIds);
// };
new Thread(companion).start();
while (true) {
//long id = client.generateNextRequestID();
// Important to set the new request id each time
//commandPacket.setClientRequestId(id);
// Record what we're sending
pendingIds.add(commandPacket.getRequestID());
// arun: disabled
if (true) {
throw new RuntimeException("disabled");
}
// Actually send out the packet
//client.sendCommandPacketAsynch(commandPacket);
// if you generate them too fast you'll clog things up
ThreadUtils.sleep(100);
}
}
use of edu.umass.cs.gnscommon.packets.CommandPacket in project GNS by MobilityFirst.
the class SelectRecordsExample method main.
/**
* @param args
* @throws IOException
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws ClientException
* @throws InvalidKeyException
* @throws SignatureException
* @throws Exception
*/
public static void main(String[] args) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, ClientException, InvalidKeyException, SignatureException, Exception {
// Create the client
client = new GNSClient();
// Create an account guid
client.execute(GNSCommand.createAccount(accountAlias));
accountGuidEntry = GuidUtils.getGUIDKeys(accountAlias);
// Next we create some fake user records as subguids
createUserRecords();
// Create the query string
String query = buildLocationsAgePrefQuery(GNSProtocol.LOCATION_FIELD_NAME.toString(), AREA_EXTENT, "age", 30, 50, "preference", "Long");
// Display the query
System.out.println("QUERY:");
System.out.println(new JSONObject("{" + query + "}").toString(4));
// Create the command
CommandPacket command = GNSCommand.selectRecords(accountGuidEntry, query, Arrays.asList(GNSProtocol.LOCATION_FIELD_NAME.toString(), "age", "preference"));
// Execute the query command and print the results
JSONArray jsonArray = client.execute(command).getResultJSONArray();
System.out.println("RESULT:");
System.out.println(jsonArray.toString(4));
}
use of edu.umass.cs.gnscommon.packets.CommandPacket in project GNS by MobilityFirst.
the class ByteificationComparisonFail method test_201_FromCommandPacket_128B_Signed.
/**
*
* @param byteificationComparison
* @throws UnsupportedEncodingException
* @throws JSONException
* @throws ClientException
* @throws NoSuchAlgorithmException
* @throws RequestParseException
*/
// FIXME: THIS TEST IS FAILING at new CommandPacket(bytes)
@Test
public void test_201_FromCommandPacket_128B_Signed(ByteificationComparisonFail byteificationComparison) throws UnsupportedEncodingException, JSONException, ClientException, NoSuchAlgorithmException, RequestParseException {
KeyPair keyPair = KeyPairGenerator.getInstance(GNSProtocol.RSA_ALGORITHM.toString()).generateKeyPair();
String guid = SharedGuidUtils.createGuidStringFromPublicKey(keyPair.getPublic().getEncoded());
// Squirrel this away now just in case the call below times out.
KeyPairUtils.saveKeyPair("gnsname", "alias", guid, keyPair);
GuidEntry querier = new GuidEntry("alias", guid, keyPair.getPublic(), keyPair.getPrivate());
CommandPacket packet = GNSCommand.fieldUpdate(querier, new String(Util.getRandomAlphanumericBytes(64)), new String(Util.getRandomAlphanumericBytes(64)));
String jsonBefore = packet.toJSONObject().toString();
byte[] bytes = packet.toBytes();
assert (jsonBefore.equals(packet.toJSONObject().toString()));
long startTime = System.nanoTime();
for (int i = 0; i < TEST_RUNS; i++) {
new CommandPacket(bytes);
}
long endTime = System.nanoTime();
double avg = (endTime - startTime) / (TEST_RUNS);
CommandPacket outputPacket = new CommandPacket(bytes);
System.out.println("Average time CommandPacket from bytes 128B Signed was " + avg + " nanoseconds.");
assert (Arrays.equals(bytes, outputPacket.toBytes()));
String canonicalJSON = CanonicalJSON.getCanonicalForm(jsonBefore);
String canonicalJSONOutput = CanonicalJSON.getCanonicalForm(outputPacket.toJSONObject());
//System.out.println(canonicalJSONOutput);
assert (canonicalJSON.equals(canonicalJSONOutput));
//CommandPacket outputPacket = CommandPacket.fromBytes(bytes);
//assert(packet.toJSONObject().toString().equals(outputPacket.toJSONObject().toString()));
}
Aggregations