Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[cf-dev] Issue in Calfornian library - Coap Client not able to invoke HelloWorldHandler

I had made some modification to the COAP client code as it was throwing an error "An identity must be set".
The code seems to be compiling fine but the coapClient doesn't seems to invoke the handler.

Relevant files are attached.

Kindly help.

 

Thanks,

Jasbir Singh

 

::DISCLAIMER::
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The contents of this e-mail and any attachment(s) are confidential and intended for the named recipient(s) only. E-mail transmission is not guaranteed to be secure or error-free as information could be intercepted, corrupted, lost, destroyed, arrive late or incomplete, or may contain viruses in transmission. The e mail and its contents (with or without referred errors) shall therefore not attach any liability on the originator or HCL or its affiliates. Views or opinions, if any, presented in this email are solely those of the author and may not necessarily reflect the views or opinions of HCL or its affiliates. Any form of reproduction, dissemination, copying, disclosure, modification, distribution and / or publication of this message without the prior written consent of authorized representative of HCL is strictly prohibited. If you have received this email in error please delete it and notify the sender immediately. Before opening any email and/or attachments, please check them for viruses and other defects.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package samples.com.microsoft.azure.sdk.iot;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;

import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapServer;
import org.eclipse.californium.core.network.CoapEndpoint;
import org.eclipse.californium.core.network.config.NetworkConfig;
import org.eclipse.californium.scandium.DTLSConnector;
import org.eclipse.californium.scandium.config.DtlsConnectorConfig;
import org.eclipse.californium.scandium.dtls.cipher.CipherSuite;
import org.eclipse.californium.scandium.dtls.pskstore.InMemoryPskStore;
import org.eclipse.californium.scandium.dtls.pskstore.StaticPskStore;

/**
 * A basic Hello World example over DTLS. The server and the client are located
 * in the same machine. This class contains the main method that creates the
 * server and the client. Use the GenKeys.sh to generate the the keystore and
 * the truststore. In this example only the server is authenticated, using a
 * self-signed certificate.
 * 
 * @author fotiou
 */
public class DTLS {

	// If you have modified GenKeys.sh modify the following variables accordingly
	private final static String KEY_STORE_PASSWORD = "endPass";
	private static final String KEY_STORE_LOCATION = "D:\\keystore2\\keyStore.jks";
	private final static String TRUST_STORE_PASSWORD = "rootPass";
	private static final String TRUST_STORE_LOCATION = "D:\\keystore2\\trustStore.jks";
	
	

	public static void main(String[] args) {

		// prepapre server
		CoapServer server = new CoapServer();
		// create a new resource
		HelloWorldResource resource = new HelloWorldResource();
		// add the resource to the server
		server.add(resource);
		// prepare client
		CoapClient client = new CoapClient("coap://localhost:5684/helloWorld");
		// Creates a new handler
		HelloWorldHandler handler = new HelloWorldHandler();
		try {
			InMemoryPskStore pskStore = new InMemoryPskStore();
			pskStore.setKey("Client_identity", "secretPSK".getBytes());			
			
			// Here starts DTLS configuration of the server
			// load the key store
			KeyStore keyStore = KeyStore.getInstance("JKS");
			InputStream in = new FileInputStream(KEY_STORE_LOCATION);
			keyStore.load(in, KEY_STORE_PASSWORD.toCharArray());
			DtlsConnectorConfig.Builder serverConfig = new DtlsConnectorConfig.Builder(new InetSocketAddress(5684));
			serverConfig.setPskStore(pskStore);
			serverConfig.setSupportedCipherSuites(new CipherSuite[] { CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 });
			serverConfig.setIdentity((PrivateKey) keyStore.getKey("server", KEY_STORE_PASSWORD.toCharArray()),
					keyStore.getCertificateChain("server"), true);
			serverConfig.setClientAuthenticationRequired(false);
			DTLSConnector serverConnector = new DTLSConnector(serverConfig.build(), null);
			server.addEndpoint(new CoapEndpoint(serverConnector, NetworkConfig.getStandard()));
			server.start();

			// Here starts DTLS configuration of the client
			// load the trust store
			KeyStore trustStore = KeyStore.getInstance("JKS");
			InputStream inTrust = new FileInputStream(TRUST_STORE_LOCATION);
			trustStore.load(inTrust, TRUST_STORE_PASSWORD.toCharArray());
			// load certificates
			Certificate[] trustedCertificates = new Certificate[1];
			trustedCertificates[0] = trustStore.getCertificate("root");

			DtlsConnectorConfig.Builder clientConfig = new DtlsConnectorConfig.Builder(new InetSocketAddress(0));
			clientConfig.setPskStore(new StaticPskStore("Client_identity", "secretPSK".getBytes()));
			clientConfig.setIdentity((PrivateKey)keyStore.getKey("client", KEY_STORE_PASSWORD.toCharArray()),
					keyStore.getCertificateChain("client"), true);

			clientConfig.setTrustStore(trustedCertificates);
			clientConfig.setSupportedCipherSuites(new CipherSuite[] { CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 });
			DTLSConnector clientConnector = new DTLSConnector(clientConfig.build(), null);
			client.setEndpoint(new CoapEndpoint(clientConnector, NetworkConfig.getStandard()));
			// start the client
			client.get(handler);
			// Just a trick to wait until the user press enter
			System.out.println("Press enter to close the server and end the program");
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			br.readLine();
			// Stop the server
			server.destroy();

		} catch (Exception e) {
			System.out.println("Exception " + e.toString());
			e.printStackTrace();

		}

	}

	public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {
		try {
			Key key = keystore.getKey(alias, password);
			if (key instanceof PrivateKey) {
				Certificate cert = keystore.getCertificate(alias);
				PublicKey publicKey = cert.getPublicKey();
				return new KeyPair(publicKey, (PrivateKey) key);
			}
		} catch (UnrecoverableKeyException e) {
		} catch (NoSuchAlgorithmException e) {
		} catch (KeyStoreException e) {
		}
		return null;
	}

}
package samples.com.microsoft.azure.sdk.iot;

import org.eclipse.californium.core.CoapHandler;
import org.eclipse.californium.core.CoapResponse;

/**
 * This is a simple Handler. It prints the server's response or if an error occurs
 * it prints the error.
 * @author fotiou
 */
public class HelloWorldHandler implements CoapHandler{

    /**
     * It is called when the CoAP server responds with some content. It prints the content of the 
     * response.
     * @param response The response of the server
     */
    public void onLoad(CoapResponse response) {
        String content = response.getResponseText();
	System.out.println("Received response from Server : " + content);
    }

    /**
     * It is called when an error occurs.
     */
    public void onError() {
        System.out.println("Error");
    }
    
}
package samples.com.microsoft.azure.sdk.iot;

import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.server.resources.CoapExchange;


/**
 * This is a basic resource. It can be accessed using the GET method and returns
 * the string ''Hello World''
 * @author Nikos Fotiou
 */
public class HelloWorldResource extends CoapResource {
        
    /**
     * The constructor
     */    
    public HelloWorldResource() {  
            // set resource identifier
            super("helloWorld");
        }
        
    /**
     * It is called when a GET method is received. 
     * @param exchange The user request
     */
    @Override
    public void handleGET(CoapExchange exchange) { 
       exchange.respond("Hello World!!");

    }
    }

Back to the top