Search in sources :

Example 1 with ClientException

use of edu.umass.cs.gnscommon.exceptions.client.ClientException 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);
    }
}
Also used : GNSClientCommands(edu.umass.cs.gnsclient.client.GNSClientCommands) JSONObject(org.json.JSONObject) CommandPacket(edu.umass.cs.gnscommon.packets.CommandPacket) GuidEntry(edu.umass.cs.gnsclient.client.util.GuidEntry) ClientException(edu.umass.cs.gnscommon.exceptions.client.ClientException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 2 with ClientException

use of edu.umass.cs.gnscommon.exceptions.client.ClientException in project GNS by MobilityFirst.

the class SimpleClientExample 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. Connects to a default reconfigurator as specified in gigapaxos.properties file.
    client = new GNSClientCommands();
    try {
        // Create an account guid if one doesn't already exists.
        // The true makes it verbosely print out what it is doing.
        // The password is for future use.
        // Note that lookupOrCreateAccountGuid "cheats" by bypassing the account verification
        // mechanisms.
        accountGuid = GuidUtils.lookupOrCreateAccountGuid(client, ACCOUNT_ALIAS, PASSWORD, true);
    } catch (Exception e) {
        System.out.println("Exception during accountGuid creation: " + e);
        System.exit(1);
    }
    System.out.println("Client connected to GNS");
    // Retrive the GUID using the account id
    String guid = client.lookupGuid(ACCOUNT_ALIAS);
    System.out.println("Retrieved GUID for " + ACCOUNT_ALIAS + ": " + guid);
    // Get the public key from the GNS
    PublicKey publicKey = client.publicKeyLookupFromGuid(guid);
    System.out.println("Retrieved public key: " + publicKey.toString());
    // Use the GuidEntry create an new record in the GNS
    client.fieldUpdate(accountGuid, "homestate", "Florida");
    System.out.println("Added homestate -> Florida record to the GNS for GUID " + accountGuid.getGuid());
    // Retrive that record from the GNS
    String result = client.fieldRead(accountGuid.getGuid(), "homestate", accountGuid);
    System.out.println("Result of read location: " + result);
    System.exit(0);
}
Also used : GNSClientCommands(edu.umass.cs.gnsclient.client.GNSClientCommands) PublicKey(java.security.PublicKey) ClientException(edu.umass.cs.gnscommon.exceptions.client.ClientException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException)

Example 3 with ClientException

use of edu.umass.cs.gnscommon.exceptions.client.ClientException in project GNS by MobilityFirst.

the class CommandUtils method createAndSignCommandInternal.

/**
   * Creates a JSON Object from the given command, keypair and a variable
   * number of key and value pairs.
   * 
   * @param commandType
   * @param guidEntry
   * @param keysAndValues
   * @return Signed command.
   * @throws ClientException
   */
public static JSONObject createAndSignCommandInternal(CommandType commandType, GuidEntry guidEntry, Object... keysAndValues) throws ClientException {
    try {
        JSONObject result = createCommandWithTimestampAndNonce(commandType, true, keysAndValues);
        String canonicalJSON = CanonicalJSON.getCanonicalForm(result);
        String signatureString = null;
        long t = System.nanoTime();
        if (Config.getGlobalBoolean(GNSCC.ENABLE_SECRET_KEY)) {
            signatureString = CryptoUtils.signDigestOfMessageSecretKey(guidEntry, canonicalJSON);
        } else {
            signatureString = CryptoUtils.signDigestOfMessage(guidEntry, canonicalJSON);
        }
        result.put(GNSProtocol.SIGNATURE.toString(), signatureString);
        if (edu.umass.cs.utils.Util.oneIn(10)) {
            DelayProfiler.updateDelayNano("signature", t);
        }
        return result;
    } catch (JSONException e) {
        throw new ClientException("Error encoding message", e);
    }
}
Also used : JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) ClientException(edu.umass.cs.gnscommon.exceptions.client.ClientException)

Example 4 with ClientException

use of edu.umass.cs.gnscommon.exceptions.client.ClientException in project GNS by MobilityFirst.

the class CryptoUtils method signDigestOfMessage.

/**
     * Signs a digest of a message using private key of the given guid.
     *
     * @param guidEntry
     * @param message
     * @return a signed digest of the message string encoded as a hex string
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws SignatureException
     * @throws java.io.UnsupportedEncodingException
     *
     * arun: This method need to be synchronized over the signature
     * instance, otherwise it will result in corrupted signatures.
     */
public static String signDigestOfMessage(GuidEntry guidEntry, String message) throws ClientException {
    try {
        Signature signatureInstance = getSignatureInstance();
        synchronized (signatureInstance) {
            signatureInstance.initSign(guidEntry.getPrivateKey());
            // iOS client uses UTF-8 - should switch to ISO-8859-1 to be consistent with
            // secret key version
            signatureInstance.update(message.getBytes("UTF-8"));
            byte[] signedString = signatureInstance.sign();
            // We used to encode this as a hex so we could send it with the html without
            // encoding. Not really necessary anymore for the socket based client,
            // but the iOS client does as well so we need to keep it like this.
            // Also note that the secret based method doesn't do this - it just returns a string
            // using the ISO-8859-1 charset.
            String result = DatatypeConverter.printHexBinary(signedString);
            //String result = ByteUtils.toHex(signedString);
            return result;
        }
    } catch (InvalidKeyException | UnsupportedEncodingException | SignatureException e) {
        throw new ClientException("Error encoding message", e);
    }
}
Also used : Signature(java.security.Signature) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SignatureException(java.security.SignatureException) ClientException(edu.umass.cs.gnscommon.exceptions.client.ClientException) InvalidKeyException(java.security.InvalidKeyException)

Example 5 with ClientException

use of edu.umass.cs.gnscommon.exceptions.client.ClientException in project GNS by MobilityFirst.

the class GNSClient method sendSyncInternal.

/**
	 * Gets a {@link RespponsePacket} or {@link ActiveReplicaError} as a
	 * response.
	 * 
	 * @param packet
	 * @param timeout
	 * @param retries
	 * @return
	 * @throws IOException
	 * @throws ClientException
	 */
private ResponsePacket sendSyncInternal(CommandPacket packet, final long timeout, int retries) throws IOException, ClientException {
    ResponsePacket response = null;
    int count = 0;
    do {
        if (count > 0)
            GNSClientConfig.getLogger().log(Level.INFO, "{0} attempting retransmission {1} upon timeout of {2}; {3}", new Object[] { this, count, packet.getSummary(), response == null ? "[null response]" : "" });
        try {
            response = defaultHandleResponse(this.sendSyncInternal(packet, timeout));
        } catch (ClientException ce) {
        // iOS client doesn't support empty body "if" statements
        //if (ce.getCode() == ResponseCode.TIMEOUT)
        // do nothing
        //	;
        }
    } while ((count++ < this.numRetriesUponTimeout && (response == null || response.getErrorCode() == ResponseCode.TIMEOUT)));
    return (response);
}
Also used : ResponsePacket(edu.umass.cs.gnscommon.packets.ResponsePacket) JSONObject(org.json.JSONObject) ClientException(edu.umass.cs.gnscommon.exceptions.client.ClientException)

Aggregations

ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)239 IOException (java.io.IOException)215 Test (org.junit.Test)134 JSONException (org.json.JSONException)126 DefaultGNSTest (edu.umass.cs.gnsserver.utils.DefaultGNSTest)125 RandomString (edu.umass.cs.gnscommon.utils.RandomString)113 JSONArray (org.json.JSONArray)74 GuidEntry (edu.umass.cs.gnsclient.client.util.GuidEntry)71 JSONObject (org.json.JSONObject)59 GNSClientCommands (edu.umass.cs.gnsclient.client.GNSClientCommands)40 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)37 StringTokenizer (java.util.StringTokenizer)30 EncryptionException (edu.umass.cs.gnscommon.exceptions.client.EncryptionException)23 BasicGuidEntry (edu.umass.cs.gnsclient.client.util.BasicGuidEntry)20 FieldNotFoundException (edu.umass.cs.gnscommon.exceptions.client.FieldNotFoundException)19 FileNotFoundException (java.io.FileNotFoundException)18 InternalRequestException (edu.umass.cs.gnscommon.exceptions.server.InternalRequestException)15 ResponseCode (edu.umass.cs.gnscommon.ResponseCode)13 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)13 InvalidKeyException (java.security.InvalidKeyException)12