Search in sources :

Example 6 with ObjectModel

use of org.eclipse.leshan.core.model.ObjectModel in project leshan by eclipse.

the class ObjectsInitializer method createMandatory.

public List<LwM2mObjectEnabler> createMandatory() {
    Collection<ObjectModel> objectModels = model.getObjectModels();
    List<LwM2mObjectEnabler> enablers = new ArrayList<>();
    for (ObjectModel objectModel : objectModels) {
        if (objectModel.mandatory) {
            ObjectEnabler objectEnabler = createNodeEnabler(objectModel);
            if (objectEnabler != null)
                enablers.add(objectEnabler);
        }
    }
    return enablers;
}
Also used : ObjectModel(org.eclipse.leshan.core.model.ObjectModel) ArrayList(java.util.ArrayList)

Example 7 with ObjectModel

use of org.eclipse.leshan.core.model.ObjectModel in project leshan by eclipse.

the class LeshanServerDemo method createAndStartServer.

public static void createAndStartServer(int webPort, String localAddress, int localPort, String secureLocalAddress, int secureLocalPort, String modelsFolderPath, String redisUrl, String keyStorePath, String keyStoreType, String keyStorePass, String keyStoreAlias, String keyStoreAliasPass, Boolean publishDNSSdServices) throws Exception {
    // Prepare LWM2M server
    LeshanServerBuilder builder = new LeshanServerBuilder();
    builder.setLocalAddress(localAddress, localPort);
    builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort);
    builder.setEncoder(new DefaultLwM2mNodeEncoder());
    LwM2mNodeDecoder decoder = new DefaultLwM2mNodeDecoder();
    builder.setDecoder(decoder);
    // Create CoAP Config
    NetworkConfig coapConfig;
    File configFile = new File(NetworkConfig.DEFAULT_FILE_NAME);
    if (configFile.isFile()) {
        coapConfig = new NetworkConfig();
        coapConfig.load(configFile);
    } else {
        coapConfig = LeshanServerBuilder.createDefaultNetworkConfig();
        coapConfig.store(configFile);
    }
    builder.setCoapConfig(coapConfig);
    // connect to redis if needed
    Pool<Jedis> jedis = null;
    if (redisUrl != null) {
        // TODO: support sentinel pool and make pool configurable
        jedis = new JedisPool(new URI(redisUrl));
    }
    PublicKey publicKey = null;
    // Set up X.509 mode
    if (keyStorePath != null) {
        try {
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            try (FileInputStream fis = new FileInputStream(keyStorePath)) {
                keyStore.load(fis, keyStorePass == null ? null : keyStorePass.toCharArray());
                List<Certificate> trustedCertificates = new ArrayList<>();
                for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) {
                    String alias = aliases.nextElement();
                    if (keyStore.isCertificateEntry(alias)) {
                        trustedCertificates.add(keyStore.getCertificate(alias));
                    } else if (keyStore.isKeyEntry(alias) && alias.equals(keyStoreAlias)) {
                        List<X509Certificate> x509CertificateChain = new ArrayList<>();
                        Certificate[] certificateChain = keyStore.getCertificateChain(alias);
                        if (certificateChain == null || certificateChain.length == 0) {
                            LOG.error("Keystore alias must have a non-empty chain of X509Certificates.");
                            System.exit(-1);
                        }
                        for (Certificate certificate : certificateChain) {
                            if (!(certificate instanceof X509Certificate)) {
                                LOG.error("Non-X.509 certificate in alias chain is not supported: {}", certificate);
                                System.exit(-1);
                            }
                            x509CertificateChain.add((X509Certificate) certificate);
                        }
                        Key key = keyStore.getKey(alias, keyStoreAliasPass == null ? new char[0] : keyStoreAliasPass.toCharArray());
                        if (!(key instanceof PrivateKey)) {
                            LOG.error("Keystore alias must have a PrivateKey entry, was {}", key == null ? null : key.getClass().getName());
                            System.exit(-1);
                        }
                        builder.setPrivateKey((PrivateKey) key);
                        publicKey = keyStore.getCertificate(alias).getPublicKey();
                        builder.setCertificateChain(x509CertificateChain.toArray(new X509Certificate[x509CertificateChain.size()]));
                    }
                }
                builder.setTrustedCertificates(trustedCertificates.toArray(new Certificate[trustedCertificates.size()]));
            }
        } catch (KeyStoreException | IOException e) {
            LOG.error("Unable to initialize X.509.", e);
            System.exit(-1);
        }
    } else // Otherwise, set up RPK mode
    {
        try {
            // Get point values
            byte[] publicX = Hex.decodeHex("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73".toCharArray());
            byte[] publicY = Hex.decodeHex("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a".toCharArray());
            byte[] privateS = Hex.decodeHex("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400".toCharArray());
            // Get Elliptic Curve Parameter spec for secp256r1
            AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
            algoParameters.init(new ECGenParameterSpec("secp256r1"));
            ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);
            // Create key specs
            KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), parameterSpec);
            KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec);
            // Get keys
            publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
            PrivateKey privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec);
            builder.setPublicKey(publicKey);
            builder.setPrivateKey(privateKey);
        } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidParameterSpecException e) {
            LOG.error("Unable to initialize RPK.", e);
            System.exit(-1);
        }
    }
    // Define model provider
    List<ObjectModel> models = ObjectLoader.loadDefault();
    models.addAll(ObjectLoader.loadDdfResources("/models/", modelPaths));
    if (modelsFolderPath != null) {
        models.addAll(ObjectLoader.loadObjectsFromDir(new File(modelsFolderPath)));
    }
    LwM2mModelProvider modelProvider = new StaticModelProvider(models);
    builder.setObjectModelProvider(modelProvider);
    // Set securityStore & registrationStore
    EditableSecurityStore securityStore;
    if (jedis == null) {
        // use file persistence
        securityStore = new FileSecurityStore();
    } else {
        // use Redis Store
        securityStore = new RedisSecurityStore(jedis);
        builder.setRegistrationStore(new RedisRegistrationStore(jedis));
    }
    builder.setSecurityStore(securityStore);
    // Create and start LWM2M server
    LeshanServer lwServer = builder.build();
    // Now prepare Jetty
    Server server = new Server(webPort);
    WebAppContext root = new WebAppContext();
    root.setContextPath("/");
    root.setResourceBase(LeshanServerDemo.class.getClassLoader().getResource("webapp").toExternalForm());
    root.setParentLoaderPriority(true);
    server.setHandler(root);
    // Create Servlet
    EventServlet eventServlet = new EventServlet(lwServer, lwServer.getSecuredAddress().getPort());
    ServletHolder eventServletHolder = new ServletHolder(eventServlet);
    root.addServlet(eventServletHolder, "/event/*");
    ServletHolder clientServletHolder = new ServletHolder(new ClientServlet(lwServer, lwServer.getSecuredAddress().getPort()));
    root.addServlet(clientServletHolder, "/api/clients/*");
    ServletHolder securityServletHolder = new ServletHolder(new SecurityServlet(securityStore, publicKey));
    root.addServlet(securityServletHolder, "/api/security/*");
    ServletHolder objectSpecServletHolder = new ServletHolder(new ObjectSpecServlet(lwServer.getModelProvider()));
    root.addServlet(objectSpecServletHolder, "/api/objectspecs/*");
    // Register a service to DNS-SD
    if (publishDNSSdServices) {
        // Create a JmDNS instance
        JmDNS jmdns = JmDNS.create(InetAddress.getLocalHost());
        // Publish Leshan HTTP Service
        ServiceInfo httpServiceInfo = ServiceInfo.create("_http._tcp.local.", "leshan", webPort, "");
        jmdns.registerService(httpServiceInfo);
        // Publish Leshan CoAP Service
        ServiceInfo coapServiceInfo = ServiceInfo.create("_coap._udp.local.", "leshan", localPort, "");
        jmdns.registerService(coapServiceInfo);
        // Publish Leshan Secure CoAP Service
        ServiceInfo coapSecureServiceInfo = ServiceInfo.create("_coaps._udp.local.", "leshan", secureLocalPort, "");
        jmdns.registerService(coapSecureServiceInfo);
    }
    // Start Jetty & Leshan
    lwServer.start();
    server.start();
    LOG.info("Web server started at {}.", server.getURI());
}
Also used : PrivateKey(java.security.PrivateKey) ECPrivateKeySpec(java.security.spec.ECPrivateKeySpec) JmDNS(javax.jmdns.JmDNS) Server(org.eclipse.jetty.server.Server) LeshanServer(org.eclipse.leshan.server.californium.impl.LeshanServer) ECPublicKeySpec(java.security.spec.ECPublicKeySpec) KeySpec(java.security.spec.KeySpec) ECPrivateKeySpec(java.security.spec.ECPrivateKeySpec) ArrayList(java.util.ArrayList) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ECPublicKeySpec(java.security.spec.ECPublicKeySpec) FileSecurityStore(org.eclipse.leshan.server.impl.FileSecurityStore) ServiceInfo(javax.jmdns.ServiceInfo) Jedis(redis.clients.jedis.Jedis) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) LeshanServerBuilder(org.eclipse.leshan.server.californium.LeshanServerBuilder) LeshanServer(org.eclipse.leshan.server.californium.impl.LeshanServer) List(java.util.List) ArrayList(java.util.ArrayList) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SecurityServlet(org.eclipse.leshan.server.demo.servlet.SecurityServlet) PublicKey(java.security.PublicKey) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) RedisSecurityStore(org.eclipse.leshan.server.cluster.RedisSecurityStore) ObjectSpecServlet(org.eclipse.leshan.server.demo.servlet.ObjectSpecServlet) ClientServlet(org.eclipse.leshan.server.demo.servlet.ClientServlet) ECParameterSpec(java.security.spec.ECParameterSpec) LwM2mModelProvider(org.eclipse.leshan.server.model.LwM2mModelProvider) RedisRegistrationStore(org.eclipse.leshan.server.cluster.RedisRegistrationStore) BigInteger(java.math.BigInteger) JedisPool(redis.clients.jedis.JedisPool) File(java.io.File) Key(java.security.Key) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) AlgorithmParameters(java.security.AlgorithmParameters) ObjectModel(org.eclipse.leshan.core.model.ObjectModel) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) DefaultLwM2mNodeEncoder(org.eclipse.leshan.core.node.codec.DefaultLwM2mNodeEncoder) URI(java.net.URI) DefaultLwM2mNodeDecoder(org.eclipse.leshan.core.node.codec.DefaultLwM2mNodeDecoder) LwM2mNodeDecoder(org.eclipse.leshan.core.node.codec.LwM2mNodeDecoder) DefaultLwM2mNodeDecoder(org.eclipse.leshan.core.node.codec.DefaultLwM2mNodeDecoder) EventServlet(org.eclipse.leshan.server.demo.servlet.EventServlet) InvalidParameterSpecException(java.security.spec.InvalidParameterSpecException) StaticModelProvider(org.eclipse.leshan.server.model.StaticModelProvider) NetworkConfig(org.eclipse.californium.core.network.config.NetworkConfig) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) ECPoint(java.security.spec.ECPoint) EditableSecurityStore(org.eclipse.leshan.server.security.EditableSecurityStore) KeyStore(java.security.KeyStore)

Example 8 with ObjectModel

use of org.eclipse.leshan.core.model.ObjectModel in project leshan by eclipse.

the class LwM2mNodeDecoderTest method loadModel.

@BeforeClass
public static void loadModel() {
    // load default object
    List<ObjectModel> objects = ObjectLoader.loadDefault();
    // add object 65 from the LWM2M v1.0.1 specification (figure 28)
    List<ResourceModel> resForObj65 = new ArrayList<>();
    resForObj65.add(new ResourceModel(0, "res0", Operations.R, true, false, Type.OBJLNK, null, null, null));
    resForObj65.add(new ResourceModel(1, "res1", Operations.R, false, false, Type.STRING, null, null, null));
    resForObj65.add(new ResourceModel(2, "res2", Operations.R, false, false, Type.INTEGER, null, null, null));
    objects.add(new ObjectModel(65, "object link tests 65", "", ObjectModel.DEFAULT_VERSION, true, false, resForObj65));
    // add object 66 from the LWM2M v1.0.1 specification (figure 28)
    List<ResourceModel> resForObj66 = new ArrayList<>();
    resForObj66.add(new ResourceModel(0, "res0", Operations.R, true, false, Type.STRING, null, null, null));
    resForObj66.add(new ResourceModel(1, "res1", Operations.R, false, false, Type.STRING, null, null, null));
    resForObj66.add(new ResourceModel(2, "res2", Operations.R, false, false, Type.OBJLNK, null, null, null));
    objects.add(new ObjectModel(66, "object link tests 66", "", ObjectModel.DEFAULT_VERSION, true, false, resForObj66));
    model = new LwM2mModel(objects);
    decoder = new DefaultLwM2mNodeDecoder();
}
Also used : ObjectModel(org.eclipse.leshan.core.model.ObjectModel) ArrayList(java.util.ArrayList) ResourceModel(org.eclipse.leshan.core.model.ResourceModel) LwM2mModel(org.eclipse.leshan.core.model.LwM2mModel) BeforeClass(org.junit.BeforeClass)

Example 9 with ObjectModel

use of org.eclipse.leshan.core.model.ObjectModel in project leshan by eclipse.

the class LeshanBootstrapServerDemo method createAndStartServer.

public static void createAndStartServer(int webPort, String localAddress, int localPort, String secureLocalAddress, int secureLocalPort, String modelsFolderPath, String configFilename) throws Exception {
    // Create Models
    List<ObjectModel> models = ObjectLoader.loadDefault();
    if (modelsFolderPath != null) {
        models.addAll(ObjectLoader.loadObjectsFromDir(new File(modelsFolderPath)));
    }
    // Prepare and start bootstrap server
    LeshanBootstrapServerBuilder builder = new LeshanBootstrapServerBuilder();
    BootstrapStoreImpl bsStore = new BootstrapStoreImpl(configFilename);
    builder.setConfigStore(bsStore);
    builder.setSecurityStore(new BootstrapSecurityStoreImpl(bsStore));
    builder.setLocalAddress(localAddress, localPort);
    builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort);
    builder.setModel(new LwM2mModel(models));
    // Create CoAP Config
    NetworkConfig coapConfig;
    File configFile = new File(NetworkConfig.DEFAULT_FILE_NAME);
    if (configFile.isFile()) {
        coapConfig = new NetworkConfig();
        coapConfig.load(configFile);
    } else {
        coapConfig = LeshanServerBuilder.createDefaultNetworkConfig();
        coapConfig.store(configFile);
    }
    builder.setCoapConfig(coapConfig);
    LeshanBootstrapServer bsServer = builder.build();
    bsServer.start();
    // Now prepare and start jetty
    Server server = new Server(webPort);
    WebAppContext root = new WebAppContext();
    root.setContextPath("/");
    root.setResourceBase(LeshanBootstrapServerDemo.class.getClassLoader().getResource("webapp").toExternalForm());
    root.setParentLoaderPriority(true);
    ServletHolder bsServletHolder = new ServletHolder(new BootstrapServlet(bsStore));
    root.addServlet(bsServletHolder, "/api/bootstrap/*");
    ServletHolder serverServletHolder = new ServletHolder(new ServerServlet(bsServer));
    root.addServlet(serverServletHolder, "/api/server/*");
    server.setHandler(root);
    server.start();
    LOG.info("Web server started at {}.", server.getURI());
}
Also used : LeshanBootstrapServerBuilder(org.eclipse.leshan.server.californium.LeshanBootstrapServerBuilder) ObjectModel(org.eclipse.leshan.core.model.ObjectModel) LeshanBootstrapServer(org.eclipse.leshan.server.californium.impl.LeshanBootstrapServer) LeshanBootstrapServer(org.eclipse.leshan.server.californium.impl.LeshanBootstrapServer) Server(org.eclipse.jetty.server.Server) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ServerServlet(org.eclipse.leshan.server.bootstrap.demo.servlet.ServerServlet) NetworkConfig(org.eclipse.californium.core.network.config.NetworkConfig) LwM2mModel(org.eclipse.leshan.core.model.LwM2mModel) BootstrapServlet(org.eclipse.leshan.server.bootstrap.demo.servlet.BootstrapServlet) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) File(java.io.File)

Example 10 with ObjectModel

use of org.eclipse.leshan.core.model.ObjectModel in project leshan by eclipse.

the class ObjectsInitializer method setInstancesForObject.

public void setInstancesForObject(int objectId, LwM2mInstanceEnabler... instances) {
    ObjectModel objectModel = model.getObjectModel(objectId);
    if (objectModel == null) {
        throw new IllegalArgumentException("Cannot set Instances Class for Object " + objectId + " because no model is defined for this id.");
    }
    Validate.notNull(instances);
    Validate.notEmpty(instances);
    if (instances.length > 1 && !objectModel.multiple)
        throw new IllegalArgumentException("Cannot set more than one instance for the single Object " + objectId);
    this.instances.put(objectId, instances);
}
Also used : ObjectModel(org.eclipse.leshan.core.model.ObjectModel)

Aggregations

ObjectModel (org.eclipse.leshan.core.model.ObjectModel)16 Test (org.junit.Test)7 Link (org.eclipse.leshan.Link)6 File (java.io.File)4 ArrayList (java.util.ArrayList)4 NetworkConfig (org.eclipse.californium.core.network.config.NetworkConfig)3 LwM2mModel (org.eclipse.leshan.core.model.LwM2mModel)3 URI (java.net.URI)2 Server (org.eclipse.jetty.server.Server)2 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)2 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)2 ResourceModel (org.eclipse.leshan.core.model.ResourceModel)2 JsonArray (com.eclipsesource.json.JsonArray)1 JsonValue (com.eclipsesource.json.JsonValue)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 BigInteger (java.math.BigInteger)1 AlgorithmParameters (java.security.AlgorithmParameters)1