use of org.eclipse.californium.core.network.config.NetworkConfig in project camel by apache.
the class CoAPComponent method getServer.
public synchronized CoapServer getServer(int port) {
CoapServer server = servers.get(port);
if (server == null && port == -1) {
server = defaultServer;
}
if (server == null && port == -1) {
server = servers.get(5684);
}
if (server == null) {
NetworkConfig config = new NetworkConfig();
//FIXME- configure the network stuff
server = new CoapServer(config, port);
servers.put(port, server);
if (this.isStarted()) {
server.start();
}
}
return server;
}
use of org.eclipse.californium.core.network.config.NetworkConfig in project leshan by eclipse.
the class LeshanClientDemo method createAndStartClient.
public static void createAndStartClient(String endpoint, String localAddress, int localPort, String secureLocalAddress, int secureLocalPort, boolean needBootstrap, String serverURI, byte[] pskIdentity, byte[] pskKey, Float latitude, Float longitude, float scaleFactor) {
locationInstance = new MyLocation(latitude, longitude, scaleFactor);
// Initialize model
List<ObjectModel> models = ObjectLoader.loadDefault();
models.addAll(ObjectLoader.loadDdfResources("/models", modelPaths));
// Initialize object list
ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(models));
if (needBootstrap) {
if (pskIdentity == null)
initializer.setInstancesForObject(SECURITY, noSecBootstap(serverURI));
else
initializer.setInstancesForObject(SECURITY, pskBootstrap(serverURI, pskIdentity, pskKey));
} else {
if (pskIdentity == null) {
initializer.setInstancesForObject(SECURITY, noSec(serverURI, 123));
initializer.setInstancesForObject(SERVER, new Server(123, 30, BindingMode.U, false));
} else {
initializer.setInstancesForObject(SECURITY, psk(serverURI, 123, pskIdentity, pskKey));
initializer.setInstancesForObject(SERVER, new Server(123, 30, BindingMode.U, false));
}
}
initializer.setClassForObject(DEVICE, MyDevice.class);
initializer.setInstancesForObject(LOCATION, locationInstance);
initializer.setInstancesForObject(OBJECT_ID_TEMPERATURE_SENSOR, new RandomTemperatureSensor());
List<LwM2mObjectEnabler> enablers = initializer.create(SECURITY, SERVER, DEVICE, LOCATION, OBJECT_ID_TEMPERATURE_SENSOR);
// Create CoAP Config
NetworkConfig coapConfig;
File configFile = new File(NetworkConfig.DEFAULT_FILE_NAME);
if (configFile.isFile()) {
coapConfig = new NetworkConfig();
coapConfig.load(configFile);
} else {
coapConfig = LeshanClientBuilder.createDefaultNetworkConfig();
coapConfig.store(configFile);
}
// Create client
LeshanClientBuilder builder = new LeshanClientBuilder(endpoint);
builder.setLocalAddress(localAddress, localPort);
builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort);
builder.setObjects(enablers);
builder.setCoapConfig(coapConfig);
// so we can disable the other one.
if (!needBootstrap) {
if (pskIdentity == null)
builder.disableSecuredEndpoint();
else
builder.disableUnsecuredEndpoint();
}
final LeshanClient client = builder.build();
LOG.info("Press 'w','a','s','d' to change reported Location ({},{}).", locationInstance.getLatitude(), locationInstance.getLongitude());
// Start the client
client.start();
// De-register on shutdown and stop client.
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// send de-registration request before destroy
client.destroy(true);
}
});
// Change the location through the Console
try (Scanner scanner = new Scanner(System.in)) {
while (scanner.hasNext()) {
String nextMove = scanner.next();
locationInstance.moveLocation(nextMove);
}
}
}
use of org.eclipse.californium.core.network.config.NetworkConfig 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());
}
use of org.eclipse.californium.core.network.config.NetworkConfig in project leshan by eclipse.
the class LeshanBootstrapServerBuilder method createDefaultNetworkConfig.
/**
* The default Californium/CoAP {@link NetworkConfig} used by the builder.
*/
public static NetworkConfig createDefaultNetworkConfig() {
NetworkConfig networkConfig = new NetworkConfig();
networkConfig.set(Keys.MID_TRACKER, "NULL");
return networkConfig;
}
use of org.eclipse.californium.core.network.config.NetworkConfig in project hono by eclipse.
the class ConfigBasedCoapEndpointFactory method getInsecureNetworkConfig.
/**
* Gets the CoAP network configuration for the insecure endpoint.
* <ol>
* <li>Creates a default CoAP network configuration based on {@link CoapAdapterProperties}.</li>
* <li>Merge in network configuration loaded from {@link CoapAdapterProperties#getNetworkConfig()}.</li>
* <li>Merge in network configuration loaded from {@link CoapAdapterProperties#getInsecureNetworkConfig()}.</li>
* </ol>
*
* @return The network configuration for the insecure endpoint.
*/
protected Future<NetworkConfig> getInsecureNetworkConfig() {
final NetworkConfig networkConfig = newDefaultNetworkConfig();
networkConfig.setInt(Keys.BLOCKWISE_STATUS_LIFETIME, config.getBlockwiseStatusLifetime());
return loadNetworkConfig(config.getNetworkConfig(), networkConfig).compose(c -> loadNetworkConfig(config.getInsecureNetworkConfig(), c));
}
Aggregations