Example usage for com.amazonaws.services.iotdata.model GetThingShadowRequest GetThingShadowRequest

List of usage examples for com.amazonaws.services.iotdata.model GetThingShadowRequest GetThingShadowRequest

Introduction

In this page you can find the example usage for com.amazonaws.services.iotdata.model GetThingShadowRequest GetThingShadowRequest.

Prototype

GetThingShadowRequest

Source Link

Usage

From source file:com.erudika.para.iot.AWSIoTService.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public Map<String, Object> readThing(Thing thing) {
    if (thing == null || StringUtils.isBlank(thing.getId())) {
        return Collections.emptyMap();
    }// w  ww.j  a  v  a  2s.  c o m
    String id = cloudIDForThing(thing);
    ByteBuffer bb = getDataClient().getThingShadow(new GetThingShadowRequest().withThingName(id)).getPayload();
    if (bb != null) {
        ByteArrayInputStream bais = new ByteArrayInputStream(bb.array());
        try {
            Map<String, Object> payload = ParaObjectUtils.getJsonReader(Map.class).readValue(bais);
            if (payload != null && payload.containsKey("state")) {
                return (Map<String, Object>) ((Map<String, Object>) payload.get("state")).get("desired");
            }
        } catch (Exception ex) {
            logger.warn("Failed to connect to IoT device {}: {}", id, ex.getMessage());
        } finally {
            IOUtils.closeQuietly(bais);
        }
    }
    return Collections.emptyMap();
}

From source file:io.klerch.alexa.state.handler.AWSIotStateHandler.java

License:Open Source License

private String getState(final AlexaScope scope) throws AlexaStateException {
    final String thingName = getThingName(scope);

    createThingIfNotExisting(scope);// w w w .j  av  a  2  s. co  m

    final GetThingShadowRequest awsRequest = new GetThingShadowRequest().withThingName(thingName);
    try {
        final GetThingShadowResult response = awsDataClient.getThingShadow(awsRequest);
        final ByteBuffer buffer = response.getPayload();

        try {
            return (buffer != null && buffer.hasArray()) ? new String(buffer.array(), "UTF-8") : "{}";
        } catch (UnsupportedEncodingException e) {
            final String error = format("Could not handle received contents of thing-shadow '%1$s'", thingName);
            log.error(error, e);
            throw AlexaStateException.create(error).withCause(e).withHandler(this).build();
        }
    }
    // if a thing does not have a shadow this is a usual exception
    catch (com.amazonaws.services.iotdata.model.ResourceNotFoundException e) {
        log.info(e);
        // we are fine with a thing having no shadow what just means there's nothing to read out for the model
        // return an empty JSON to indicate nothing is in the thing shadow
        return "{}";
    }
}