use of org.eclipse.smarthome.config.core.Configuration in project smarthome by eclipse.
the class PersistentInbox method approve.
@Override
public Thing approve(ThingUID thingUID, String label) {
if (thingUID == null) {
throw new IllegalArgumentException("Thing UID must not be null");
}
List<DiscoveryResult> results = stream().filter(forThingUID(thingUID)).collect(Collectors.toList());
if (results.isEmpty()) {
throw new IllegalArgumentException("No Thing with UID " + thingUID.getAsString() + " in inbox");
}
DiscoveryResult result = results.get(0);
final Map<String, String> properties = new HashMap<>();
final Map<String, Object> configParams = new HashMap<>();
getPropsAndConfigParams(result, properties, configParams);
final Configuration config = new Configuration(configParams);
ThingTypeUID thingTypeUID = result.getThingTypeUID();
Thing newThing = ThingFactory.createThing(thingUID, config, properties, result.getBridgeUID(), thingTypeUID, this.thingHandlerFactories);
if (newThing == null) {
logger.warn("Cannot create thing. No binding found that supports creating a thing" + " of type {}.", thingTypeUID);
return null;
}
if (label != null && !label.isEmpty()) {
newThing.setLabel(label);
} else {
newThing.setLabel(result.getLabel());
}
addThingSafely(newThing);
return newThing;
}
use of org.eclipse.smarthome.config.core.Configuration in project smarthome by eclipse.
the class ConfigurableServiceResource method deleteConfiguration.
@DELETE
@Path("/{serviceId}/config")
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Deletes a service configuration for given service ID and returns the old configuration.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = String.class), @ApiResponse(code = 204, message = "No old configuration"), @ApiResponse(code = 500, message = "Configuration can not be deleted due to internal error") })
public Response deleteConfiguration(@PathParam("serviceId") @ApiParam(value = "service ID", required = true) String serviceId) {
try {
Configuration oldConfiguration = configurationService.get(serviceId);
configurationService.delete(serviceId);
return oldConfiguration != null ? Response.ok(oldConfiguration).build() : Response.noContent().build();
} catch (IOException ex) {
logger.error("Cannot delete configuration for service {}: {}", serviceId, ex.getMessage(), ex);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
}
use of org.eclipse.smarthome.config.core.Configuration in project smarthome by eclipse.
the class ConfigurableServiceResource method updateConfiguration.
@PUT
@Path("/{serviceId}/config")
@Consumes(MediaType.APPLICATION_JSON)
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Updates a service configuration for given service ID and returns the old configuration.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = String.class), @ApiResponse(code = 204, message = "No old configuration"), @ApiResponse(code = 500, message = "Configuration can not be updated due to internal error") })
public Response updateConfiguration(@PathParam("serviceId") @ApiParam(value = "service ID", required = true) String serviceId, Map<String, Object> configuration) {
try {
Configuration oldConfiguration = configurationService.get(serviceId);
configurationService.update(serviceId, new Configuration(normalizeConfiguration(configuration, serviceId)));
return oldConfiguration != null ? Response.ok(oldConfiguration.getProperties()).build() : Response.noContent().build();
} catch (IOException ex) {
logger.error("Cannot update configuration for service {}: {}", serviceId, ex.getMessage(), ex);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
}
use of org.eclipse.smarthome.config.core.Configuration in project smarthome by eclipse.
the class ThingResource method create.
/**
* create a new Thing
*
* @param thingBean
* @return Response holding the newly created Thing or error information
*/
@POST
@RolesAllowed({ Role.ADMIN })
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Creates a new thing and adds it to the registry.")
@ApiResponses(value = { @ApiResponse(code = 201, message = "Created", response = String.class), @ApiResponse(code = 400, message = "A uid must be provided, if no binding can create a thing of this type."), @ApiResponse(code = 409, message = "A thing with the same uid already exists.") })
public Response create(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language, @ApiParam(value = "thing data", required = true) ThingDTO thingBean) {
final Locale locale = LocaleUtil.getLocale(language);
ThingUID thingUID = thingBean.UID == null ? null : new ThingUID(thingBean.UID);
ThingTypeUID thingTypeUID = new ThingTypeUID(thingBean.thingTypeUID);
if (thingUID != null) {
// check if a thing with this UID already exists
Thing thing = thingRegistry.get(thingUID);
if (thing != null) {
// report a conflict
return getThingResponse(Status.CONFLICT, thing, locale, "Thing " + thingUID.toString() + " already exists!");
}
}
ThingUID bridgeUID = null;
if (thingBean.bridgeUID != null) {
bridgeUID = new ThingUID(thingBean.bridgeUID);
}
// turn the ThingDTO's configuration into a Configuration
Configuration configuration = new Configuration(normalizeConfiguration(thingBean.configuration, thingTypeUID, thingUID));
normalizeChannels(thingBean, thingUID);
Thing thing = thingRegistry.createThingOfType(thingTypeUID, thingUID, bridgeUID, thingBean.label, configuration);
if (thing != null) {
if (thingBean.properties != null) {
for (Entry<String, String> entry : thingBean.properties.entrySet()) {
thing.setProperty(entry.getKey(), entry.getValue());
}
}
if (thingBean.channels != null) {
List<Channel> channels = new ArrayList<>();
for (ChannelDTO channelDTO : thingBean.channels) {
channels.add(ChannelDTOMapper.map(channelDTO));
}
ThingHelper.addChannelsToThing(thing, channels);
}
if (thingBean.location != null) {
thing.setLocation(thingBean.location);
}
} else if (thingUID != null) {
// if there wasn't any ThingFactory capable of creating the thing,
// we create the Thing exactly the way we received it, i.e. we
// cannot take its thing type into account for automatically
// populating channels and properties.
thing = ThingDTOMapper.map(thingBean);
} else {
return getThingResponse(Status.BAD_REQUEST, thing, locale, "A UID must be provided, since no binding can create the thing!");
}
thingRegistry.add(thing);
return getThingResponse(Status.CREATED, thing, locale, null);
}
use of org.eclipse.smarthome.config.core.Configuration in project smarthome by eclipse.
the class TradfriGatewayHandler method obtainIdentityAndPreSharedKey.
/**
* Authenticates against the gateway with the security code in order to receive a pre-shared key for a newly
* generated identity.
* As this requires a remote request, this method might be long-running.
*
* @return true, if credentials were successfully obtained, false otherwise
*/
protected boolean obtainIdentityAndPreSharedKey() {
TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
String identity = UUID.randomUUID().toString().replace("-", "");
String preSharedKey = null;
CoapResponse gatewayResponse;
String authUrl = null;
String responseText = null;
try {
DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(0));
builder.setPskStore(new StaticPskStore("Client_identity", configuration.code.getBytes()));
DTLSConnector dtlsConnector = new DTLSConnector(builder.build());
CoapEndpoint authEndpoint = new CoapEndpoint(dtlsConnector, NetworkConfig.getStandard());
authUrl = "coaps://" + configuration.host + ":" + configuration.port + "/15011/9063";
CoapClient deviceClient = new CoapClient(new URI(authUrl));
deviceClient.setTimeout(TimeUnit.SECONDS.toMillis(10));
deviceClient.setEndpoint(authEndpoint);
JsonObject json = new JsonObject();
json.addProperty(CLIENT_IDENTITY_PROPOSED, identity);
gatewayResponse = deviceClient.post(json.toString(), 0);
authEndpoint.destroy();
deviceClient.shutdown();
if (gatewayResponse == null) {
// seems we ran in a timeout, which potentially also happens
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "No response from gateway. Might be due to an invalid security code.");
return false;
}
if (gatewayResponse.isSuccess()) {
responseText = gatewayResponse.getResponseText();
json = new JsonParser().parse(responseText).getAsJsonObject();
preSharedKey = json.get(NEW_PSK_BY_GW).getAsString();
if (isNullOrEmpty(preSharedKey)) {
logger.error("Received pre-shared key is empty for thing {} on gateway at {}", getThing().getUID(), configuration.host);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Pre-shared key was not obtain successfully");
return false;
} else {
logger.info("Received pre-shared key for gateway '{}'", configuration.host);
logger.debug("Using identity '{}' with pre-shared key '{}'.", identity, preSharedKey);
Configuration editedConfig = editConfiguration();
editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_CODE, null);
editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_IDENTITY, identity);
editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_PRE_SHARED_KEY, preSharedKey);
updateConfiguration(editedConfig);
return true;
}
} else {
logger.warn("Failed obtaining pre-shared key for identity '{}' (response code '{}', response text '{}')", identity, gatewayResponse.getCode(), isNullOrEmpty(gatewayResponse.getResponseText()) ? "<empty>" : gatewayResponse.getResponseText());
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format("Failed obtaining pre-shared key with status code '%s'", gatewayResponse.getCode()));
}
} catch (URISyntaxException e) {
logger.error("Illegal gateway URI '{}'", authUrl, e);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
} catch (JsonParseException e) {
logger.warn("Invalid response recieved from gateway '{}'", responseText, e);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String.format("Invalid response recieved from gateway '%s'", responseText));
}
return false;
}
Aggregations