diff --git a/src/main/java/org/edgexfoundry/Application.java b/src/main/java/org/edgexfoundry/Application.java index d2149da..8a2b03f 100644 --- a/src/main/java/org/edgexfoundry/Application.java +++ b/src/main/java/org/edgexfoundry/Application.java @@ -1,22 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 Dell Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * - * @microservice: core-command + * @microservice: core-command * @author: Jim White, Dell * @version: 1.0.0 *******************************************************************************/ + package org.edgexfoundry; import org.springframework.boot.SpringApplication; @@ -30,10 +29,10 @@ @EnableDiscoveryClient public class Application { - public static void main(String[] args) { - ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args); - String welcomeMsg = ctx.getEnvironment().getProperty("app.open.msg"); - System.out.println(welcomeMsg); - } + public static void main(String[] args) { + ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args); + String welcomeMsg = ctx.getEnvironment().getProperty("app.open.msg"); + System.out.println(welcomeMsg); + } } diff --git a/src/main/java/org/edgexfoundry/HeartBeat.java b/src/main/java/org/edgexfoundry/HeartBeat.java index 5164c8b..f281cdd 100644 --- a/src/main/java/org/edgexfoundry/HeartBeat.java +++ b/src/main/java/org/edgexfoundry/HeartBeat.java @@ -1,22 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 Dell Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * - * @microservice: core-command + * @microservice: core-command * @author: Jim White, Dell * @version: 1.0.0 *******************************************************************************/ + package org.edgexfoundry; import org.springframework.beans.factory.annotation.Value; @@ -28,15 +27,14 @@ @Component public class HeartBeat { - // private static final Logger logger = Logger.getLogger(HeartBeat.class); - private final static org.edgexfoundry.support.logging.client.EdgeXLogger logger = org.edgexfoundry.support.logging.client.EdgeXLoggerFactory - .getEdgeXLogger(HeartBeat.class); + private static final org.edgexfoundry.support.logging.client.EdgeXLogger logger = + org.edgexfoundry.support.logging.client.EdgeXLoggerFactory.getEdgeXLogger(HeartBeat.class); - @Value("${heart.beat.msg}") - private String heartBeatMsg; + @Value("${heart.beat.msg}") + private String heartBeatMsg; - @Scheduled(fixedRateString = "${heart.beat.time}") - public void pulse() { - logger.info(heartBeatMsg); - } + @Scheduled(fixedRateString = "${heart.beat.time}") + public void pulse() { + logger.info(heartBeatMsg); + } } diff --git a/src/main/java/org/edgexfoundry/controller/CommandController.java b/src/main/java/org/edgexfoundry/controller/CommandController.java index a6d4c05..7f08241 100644 --- a/src/main/java/org/edgexfoundry/controller/CommandController.java +++ b/src/main/java/org/edgexfoundry/controller/CommandController.java @@ -1,22 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 Dell Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * - * @microservice: core-command + * @microservice: core-command * @author: Jim White, Dell * @version: 1.0.0 *******************************************************************************/ + package org.edgexfoundry.controller; import java.io.BufferedReader; @@ -56,349 +55,313 @@ public class CommandController { - // private static final Logger logger = - // Logger.getLogger(CommandController.class); - private final static org.edgexfoundry.support.logging.client.EdgeXLogger logger = org.edgexfoundry.support.logging.client.EdgeXLoggerFactory - .getEdgeXLogger(CommandController.class); + private static final org.edgexfoundry.support.logging.client.EdgeXLogger logger = + org.edgexfoundry.support.logging.client.EdgeXLoggerFactory + .getEdgeXLogger(CommandController.class); - @Value("${device.service.protocol}") - private String protocol; + @Value("${device.service.protocol}") + private String protocol; - @Value("${meta.db.device.url}") - private String url; + @Value("${meta.db.device.url}") + private String url; - @Autowired - DeviceClient deviceClient; + @Autowired + DeviceClient deviceClient; - @Autowired - CommandClient commandClient; + @Autowired + CommandClient commandClient; - // TODO - possibly cache some responses so they can be more quickly - // returned. + // TODO - possibly cache some responses so they can be more quickly + // returned. - /** - * Retrieve a list of (all) devices and their command offerings. Throws - * ServiceException (HTTP 503) for unanticipated or unknown issues - * encountered. - * - * @param host - * - provided by the Spring runtime via the request header, the - * host address. - * @return List of CommandResponse (containing the devices and their - * commands) - */ - @RequestMapping(method = RequestMethod.GET) - public List devices(@RequestHeader("host") String host) { - try { - return deviceClient.devices().stream().map(d -> new CommandResponse(d, host)).collect(Collectors.toList()); - } catch (Exception e) { - logger.error("Error getting command responses: " + e.getMessage()); - throw new ServiceException(e); - } - } + /** + * Retrieve a list of (all) devices and their command offerings. Throws ServiceException (HTTP + * 503) for unanticipated or unknown issues encountered. + * + * @param host - provided by the Spring runtime via the request header, the host address. + * @return List of CommandResponse (containing the devices and their commands) + */ + @RequestMapping(method = RequestMethod.GET) + public List devices(@RequestHeader("host") String host) { + try { + return deviceClient.devices().stream().map(d -> new CommandResponse(d, host)) + .collect(Collectors.toList()); + } catch (Exception e) { + logger.error("Error getting command responses: " + e.getMessage()); + throw new ServiceException(e); + } + } - /** - * Retrieve a device (by database generated id) and its command offerings. - * Throws ServiceException (HTTP 503) for unanticipated or unknown issues - * encountered. Throws NotFoundException (HTTP 404) if no device exists by - * the id provided. - * - * @param id - * - the database generated id for the device - * @param host - * - provided by the Spring runtime via the request header, the - * host address. - * @return CommandResponse containing the device and its commands - */ - @RequestMapping(value = "/{id}", method = RequestMethod.GET) - public CommandResponse device(@PathVariable String id, @RequestHeader("host") String host) { - try { - Device device = deviceClient.device(id); - return new CommandResponse(device, host); - } catch (javax.ws.rs.NotFoundException eNF) { - throw new NotFoundException(Device.class.toString(), id); - } catch (Exception e) { - logger.error("Error getting command response: " + e.getMessage()); - throw new ServiceException(e); - } - } + /** + * Retrieve a device (by database generated id) and its command offerings. Throws ServiceException + * (HTTP 503) for unanticipated or unknown issues encountered. Throws NotFoundException (HTTP 404) + * if no device exists by the id provided. + * + * @param id - the database generated id for the device + * @param host - provided by the Spring runtime via the request header, the host address. + * @return CommandResponse containing the device and its commands + */ + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + public CommandResponse device(@PathVariable String id, @RequestHeader("host") String host) { + try { + Device device = deviceClient.device(id); + return new CommandResponse(device, host); + } catch (javax.ws.rs.NotFoundException eNF) { + throw new NotFoundException(Device.class.toString(), id); + } catch (Exception e) { + logger.error("Error getting command response: " + e.getMessage()); + throw new ServiceException(e); + } + } - /** - * Retrieve a device (by name) and its command offerings. Throws - * ServiceException (HTTP 503) for unanticipated or unknown issues - * encountered. Throws NotFoundException (HTTP 404) if no device exists by - * the name provided. - * - * @param name - * - the name of the device - * @param host - * - provided by the Spring runtime via the request header, the - * host address. - * @return CommandResponse containing the device and its commands - */ - @RequestMapping(value = "/name/{name:.+}", method = RequestMethod.GET) - public CommandResponse deviceByName(@PathVariable String name, @RequestHeader("host") String host) { - try { - Device device = deviceClient.deviceForName(name); - return new CommandResponse(device, host); - } catch (javax.ws.rs.NotFoundException eNF) { - throw new NotFoundException(Device.class.toString(), name); - } catch (Exception e) { - logger.error("Error getting command response: " + e.getMessage()); - throw new ServiceException(e); - } - } + /** + * Retrieve a device (by name) and its command offerings. Throws ServiceException (HTTP 503) for + * unanticipated or unknown issues encountered. Throws NotFoundException (HTTP 404) if no device + * exists by the name provided. + * + * @param name - the name of the device + * @param host - provided by the Spring runtime via the request header, the host address. + * @return CommandResponse containing the device and its commands + */ + @RequestMapping(value = "/name/{name:.+}", method = RequestMethod.GET) + public CommandResponse deviceByName(@PathVariable String name, + @RequestHeader("host") String host) { + try { + Device device = deviceClient.deviceForName(name); + return new CommandResponse(device, host); + } catch (javax.ws.rs.NotFoundException eNF) { + throw new NotFoundException(Device.class.toString(), name); + } catch (Exception e) { + logger.error("Error getting command response: " + e.getMessage()); + throw new ServiceException(e); + } + } - /** - * Issue the put command referenced by the command id to the device/sensor - * (also referenced by database generated id) it is associated to via the - * device service. ServiceException (HTTP 503) for unanticipated or unknown - * issues encountered. Throws NotFoundException (HTTP 404) if no device - * exists by the id provided. Throws LockedException (HTTP 423) if the - * device is locked (admin state). - * - * @param id - * - the database generated id for the device to receive the put - * command request - * @param commandid - * - the id (database generated id) of the command to issue to - * the device - * @param host - * - provided by the Spring runtime via the request header, the - * host address. - * @param body - * - JSON data to send with the command request - * @return String as returned by the device/sensor via the device service. - */ - @RequestMapping(value = "/{id}/command/{commandid}", method = RequestMethod.PUT) - public ResponseEntity put(@PathVariable String id, @PathVariable String commandid, - @RequestBody String body) { - try { - Device device = deviceClient.device(id); - Command command = commandClient.command(commandid); - if (command == null) { - throw new NotFoundException(Command.class.toString(), commandid); - } - if (device.getAdminState() == AdminState.locked) { - logger.info("Request to device: " + device.getName() + " blocked because it is locked"); - throw new LockedException("Device " + device.getName() + " is in admin locked state"); - } - if (device.getOperatingState() == OperatingState.disabled) { - logger.info("Put request to device: " + device.getName() + " blocked because it is disable"); - throw new LockedException("Device " + device.getName() + " is in disabled op state"); - } - String putURL = getUrl(device, id, command, false); - logger.info("Issuing put command to: " + putURL); - logger.info("Command message body is: " + body); - return issueCommand(putURL, body, true); - } catch (javax.ws.rs.NotFoundException eNF) { - throw new NotFoundException(Device.class.toString(), id); - } catch (LockedException eL) { - throw eL; - } catch (Exception e) { - logger.error("Error calling put command: " + e.getMessage()); - throw new ServiceException(e); - } - } + /** + * Issue the put command referenced by the command id to the device/sensor (also referenced by + * database generated id) it is associated to via the device service. ServiceException (HTTP 503) + * for unanticipated or unknown issues encountered. Throws NotFoundException (HTTP 404) if no + * device exists by the id provided. Throws LockedException (HTTP 423) if the device is locked + * (admin state). + * + * @param id - the database generated id for the device to receive the put command request + * @param commandid - the id (database generated id) of the command to issue to the device + * @param host - provided by the Spring runtime via the request header, the host address. + * @param body - JSON data to send with the command request + * @return String as returned by the device/sensor via the device service. + */ + @RequestMapping(value = "/{id}/command/{commandid}", method = RequestMethod.PUT) + public ResponseEntity put(@PathVariable String id, @PathVariable String commandid, + @RequestBody String body) { + try { + Device device = deviceClient.device(id); + Command command = commandClient.command(commandid); + if (command == null) { + throw new NotFoundException(Command.class.toString(), commandid); + } + if (device.getAdminState() == AdminState.locked) { + logger.info("Request to device: " + device.getName() + " blocked because it is locked"); + throw new LockedException("Device " + device.getName() + " is in admin locked state"); + } + if (device.getOperatingState() == OperatingState.disabled) { + logger + .info("Put request to device: " + device.getName() + " blocked because it is disable"); + throw new LockedException("Device " + device.getName() + " is in disabled op state"); + } + String putURL = getUrl(device, id, command, false); + logger.info("Issuing put command to: " + putURL); + logger.info("Command message body is: " + body); + return issueCommand(putURL, body, true); + } catch (javax.ws.rs.NotFoundException eNF) { + throw new NotFoundException(Device.class.toString(), id); + } catch (LockedException eL) { + throw eL; + } catch (Exception e) { + logger.error("Error calling put command: " + e.getMessage()); + throw new ServiceException(e); + } + } - /** - * Issue the get command referenced by the command id to the device/sensor - * (also referenced by database generated id) it is associated to via the - * device service. ServiceException (HTTP 503) for unanticipated or unknown - * issues encountered. Throws NotFoundException (HTTP 404) if no device - * exists by the id provided. Throws LockedException (HTTP 423) if the - * device is locked (admin state). - * - * @param id - * - the database generated id for the device to receive the put - * command request - * @param commandid - * - the id (database generated id) of the command to issue to - * the device - * @param host - * - provided by the Spring runtime via the request header, the - * host address. - * @return String as returned by the device/sensor via the device service. - */ - @RequestMapping(value = "/{id}/command/{commandid}", method = RequestMethod.GET) - public ResponseEntity get(@PathVariable String id, @PathVariable String commandid) { - try { - Device device = deviceClient.device(id); - Command command = commandClient.command(commandid); - if (command == null) { - throw new NotFoundException(Command.class.toString(), commandid); - } - if (device.getAdminState() == AdminState.locked) { - logger.info("Request to device: " + device.getName() + " blocked because it is locked"); - throw new LockedException("Device " + device.getName() + " is in admin locked state"); - } - String getUrl = getUrl(device, id, command, true); - logger.info("Issuing get command to: " + getUrl); - return issueCommand(getUrl, null, false); - } catch (javax.ws.rs.NotFoundException eNF) { - throw new NotFoundException(Device.class.toString(), id); - } catch (LockedException eL) { - throw eL; - } catch (Exception e) { - logger.error("Error calling get command: " + e.getMessage()); - throw new ServiceException(e); - } - } + /** + * Issue the get command referenced by the command id to the device/sensor (also referenced by + * database generated id) it is associated to via the device service. ServiceException (HTTP 503) + * for unanticipated or unknown issues encountered. Throws NotFoundException (HTTP 404) if no + * device exists by the id provided. Throws LockedException (HTTP 423) if the device is locked + * (admin state). + * + * @param id - the database generated id for the device to receive the put command request + * @param commandid - the id (database generated id) of the command to issue to the device + * @param host - provided by the Spring runtime via the request header, the host address. + * @return String as returned by the device/sensor via the device service. + */ + @RequestMapping(value = "/{id}/command/{commandid}", method = RequestMethod.GET) + public ResponseEntity get(@PathVariable String id, @PathVariable String commandid) { + try { + Device device = deviceClient.device(id); + Command command = commandClient.command(commandid); + if (command == null) { + throw new NotFoundException(Command.class.toString(), commandid); + } + if (device.getAdminState() == AdminState.locked) { + logger.info("Request to device: " + device.getName() + " blocked because it is locked"); + throw new LockedException("Device " + device.getName() + " is in admin locked state"); + } + String getUrl = getUrl(device, id, command, true); + logger.info("Issuing get command to: " + getUrl); + return issueCommand(getUrl, null, false); + } catch (javax.ws.rs.NotFoundException eNF) { + throw new NotFoundException(Device.class.toString(), id); + } catch (LockedException eL) { + throw eL; + } catch (Exception e) { + logger.error("Error calling get command: " + e.getMessage()); + throw new ServiceException(e); + } + } - /** - * Set the op state of the device (as referenced by the database generated - * id of the device) to the state provided (either enabled or disabled). - * ServiceException (HTTP 503) for unanticipated or unknown issues - * encountered. Throws NotFoundException (HTTP 404) if no device exists by - * the id provided. - * - * @param id - * - the database generated id for the device to receive the put - * command request - * - * @param opState - * - either enabled or disabled as a String - * @return - boolean indicating the successful - */ - @RequestMapping(value = "/{id}/opstate/{opState}", method = RequestMethod.PUT) - public boolean putOpState(@PathVariable String id, @PathVariable String opState) { - try { - deviceClient.updateOpState(id, opState); - logger.info("Requesting op state for device: " + id + " be set to " + opState); - return true; - } catch (javax.ws.rs.NotFoundException eNF) { - throw new NotFoundException(Device.class.toString(), id); - } catch (Exception e) { - logger.error("Error calling set of op state: " + e.getMessage()); - throw new ServiceException(e); - } - } + /** + * Set the op state of the device (as referenced by the database generated id of the device) to + * the state provided (either enabled or disabled). ServiceException (HTTP 503) for unanticipated + * or unknown issues encountered. Throws NotFoundException (HTTP 404) if no device exists by the + * id provided. + * + * @param id - the database generated id for the device to receive the put command request + * + * @param opState - either enabled or disabled as a String + * @return - boolean indicating the successful + */ + @RequestMapping(value = "/{id}/opstate/{opState}", method = RequestMethod.PUT) + public boolean putOpState(@PathVariable String id, @PathVariable String opState) { + try { + deviceClient.updateOpState(id, opState); + logger.info("Requesting op state for device: " + id + " be set to " + opState); + return true; + } catch (javax.ws.rs.NotFoundException eNF) { + throw new NotFoundException(Device.class.toString(), id); + } catch (Exception e) { + logger.error("Error calling set of op state: " + e.getMessage()); + throw new ServiceException(e); + } + } - /** - * Set the op state of the device (by name of the device) to the state - * provided (either enabled or disabled). ServiceException (HTTP 503) for - * unanticipated or unknown issues encountered. Throws NotFoundException - * (HTTP 404) if no device exists by the name provided. - * - * @param name - * - the name of the device - * - * @param opState - * - either enabled or disabled as a String - * @return - boolean indicating the successful - */ - @RequestMapping(value = "/name/{name}/opstate/{opState}", method = RequestMethod.PUT) - public boolean putOpStateByName(@PathVariable String name, @PathVariable String opState) { - try { - deviceClient.updateOpStateByName(name, opState); - logger.info("Requesting op state for device: " + name + " be set to " + opState); - return true; - } catch (javax.ws.rs.NotFoundException eNF) { - throw new NotFoundException(Device.class.toString(), name); - } catch (Exception e) { - logger.error("Error calling set of op state: " + e.getMessage()); - throw new ServiceException(e); - } - } + /** + * Set the op state of the device (by name of the device) to the state provided (either enabled or + * disabled). ServiceException (HTTP 503) for unanticipated or unknown issues encountered. Throws + * NotFoundException (HTTP 404) if no device exists by the name provided. + * + * @param name - the name of the device + * + * @param opState - either enabled or disabled as a String + * @return - boolean indicating the successful + */ + @RequestMapping(value = "/name/{name}/opstate/{opState}", method = RequestMethod.PUT) + public boolean putOpStateByName(@PathVariable String name, @PathVariable String opState) { + try { + deviceClient.updateOpStateByName(name, opState); + logger.info("Requesting op state for device: " + name + " be set to " + opState); + return true; + } catch (javax.ws.rs.NotFoundException eNF) { + throw new NotFoundException(Device.class.toString(), name); + } catch (Exception e) { + logger.error("Error calling set of op state: " + e.getMessage()); + throw new ServiceException(e); + } + } - /** - * Set the admin state of the device (as referenced by the database - * generated id of the device) to the state provided (either locked or - * unlocked). ServiceException (HTTP 503) for unanticipated or unknown - * issues encountered. Throws NotFoundException (HTTP 404) if no device - * exists by the id provided. - * - * @param id - * - the database generated id for the device to receive the put - * command request - * - * @param adminState - * - either locked or unlocked as a String - * @return - boolean indicating the successful - */ - @RequestMapping(value = "/{id}/adminstate/{adminState}", method = RequestMethod.PUT) - public boolean putAdminState(@PathVariable String id, @PathVariable String adminState) { - try { - deviceClient.updateAdminState(id, adminState); - logger.info("Requesting admin state for device: " + id + " be set to " + adminState); - return true; - } catch (javax.ws.rs.NotFoundException eNF) { - throw new NotFoundException(Device.class.toString(), id); - } catch (Exception e) { - logger.error("Error calling set of admin state: " + e.getMessage()); - throw new ServiceException(e); - } - } + /** + * Set the admin state of the device (as referenced by the database generated id of the device) to + * the state provided (either locked or unlocked). ServiceException (HTTP 503) for unanticipated + * or unknown issues encountered. Throws NotFoundException (HTTP 404) if no device exists by the + * id provided. + * + * @param id - the database generated id for the device to receive the put command request + * + * @param adminState - either locked or unlocked as a String + * @return - boolean indicating the successful + */ + @RequestMapping(value = "/{id}/adminstate/{adminState}", method = RequestMethod.PUT) + public boolean putAdminState(@PathVariable String id, @PathVariable String adminState) { + try { + deviceClient.updateAdminState(id, adminState); + logger.info("Requesting admin state for device: " + id + " be set to " + adminState); + return true; + } catch (javax.ws.rs.NotFoundException eNF) { + throw new NotFoundException(Device.class.toString(), id); + } catch (Exception e) { + logger.error("Error calling set of admin state: " + e.getMessage()); + throw new ServiceException(e); + } + } - /** - * Set the admin state of the device (by name of the device) to the state - * provided (either locked or unlocked). ServiceException (HTTP 503) for - * unanticipated or unknown issues encountered. Throws NotFoundException - * (HTTP 404) if no device exists by the name provided. - * - * @param name - * - the name of the device - * - * @param opState - * - either enabled or disabled as a String - * @return - boolean indicating the successful - */ - @RequestMapping(value = "/name/{name}/adminstate/{adminState}", method = RequestMethod.PUT) - public boolean putAdminStateByName(@PathVariable String name, @PathVariable String adminState) { - try { - deviceClient.updateAdminStateByName(name, adminState); - logger.info("Requesting admin state for device: " + name + " be set to " + adminState); - return true; - } catch (javax.ws.rs.NotFoundException eNF) { - throw new NotFoundException(Device.class.toString(), name); - } catch (Exception e) { - logger.error("Error calling set of admin state: " + e.getMessage()); - throw new ServiceException(e); - } - } + /** + * Set the admin state of the device (by name of the device) to the state provided (either locked + * or unlocked). ServiceException (HTTP 503) for unanticipated or unknown issues encountered. + * Throws NotFoundException (HTTP 404) if no device exists by the name provided. + * + * @param name - the name of the device + * + * @param opState - either enabled or disabled as a String + * @return - boolean indicating the successful + */ + @RequestMapping(value = "/name/{name}/adminstate/{adminState}", method = RequestMethod.PUT) + public boolean putAdminStateByName(@PathVariable String name, @PathVariable String adminState) { + try { + deviceClient.updateAdminStateByName(name, adminState); + logger.info("Requesting admin state for device: " + name + " be set to " + adminState); + return true; + } catch (javax.ws.rs.NotFoundException eNF) { + throw new NotFoundException(Device.class.toString(), name); + } catch (Exception e) { + logger.error("Error calling set of admin state: " + e.getMessage()); + throw new ServiceException(e); + } + } - private String getUrl(Device device, String deviceId, Command command, boolean isGet) { - DeviceService service = device.getService(); - if (service != null && service.getAddressable() != null) { - // use REST for http services - if (Protocol.HTTP == service.getAddressable().getProtocol()) { - StringBuilder builder = new StringBuilder(service.getAddressable().getProtocol().toString()); - builder.append("://"); - builder.append(service.getAddressable().getAddress()); - builder.append(":"); - builder.append(service.getAddressable().getPort()); - if (isGet) - builder.append(command.getGet().getPath()); - else - builder.append(command.getPut().getPath()); - return builder.toString().replace("{deviceId}", deviceId); - } else { - // TODO - someday offer message send over bus (like 0MQ or MQTT - // for protocol = TCP - return ""; - } - } else - throw new ClientException("Device Service is not properly addressable"); - } + private String getUrl(Device device, String deviceId, Command command, boolean isGet) { + DeviceService service = device.getService(); + if (service != null && service.getAddressable() != null) { + // use REST for http services + if (Protocol.HTTP == service.getAddressable().getProtocol()) { + StringBuilder builder = + new StringBuilder(service.getAddressable().getProtocol().toString()); + builder.append("://"); + builder.append(service.getAddressable().getAddress()); + builder.append(":"); + builder.append(service.getAddressable().getPort()); + if (isGet) + builder.append(command.getGet().getPath()); + else + builder.append(command.getPut().getPath()); + return builder.toString().replace("{deviceId}", deviceId); + } else { + // TODO - someday offer message send over bus (like 0MQ or MQTT + // for protocol = TCP + return ""; + } + } else + throw new ClientException("Device Service is not properly addressable"); + } - private ResponseEntity issueCommand(String url, String body, boolean isPut) throws IOException { - URL command = new URL(url); - HttpURLConnection con = (HttpURLConnection) command.openConnection(); - if (isPut) { - con.setRequestMethod("PUT"); - con.setDoOutput(true); - con.setRequestProperty("Content-Type", "application/json"); - con.setRequestProperty("Content-Length", Integer.toString(body.length())); - OutputStream os = con.getOutputStream(); - os.write(body.getBytes()); - } - BufferedReader res = new BufferedReader(new InputStreamReader(con.getInputStream())); - StringBuilder response = new StringBuilder(); - for (String responseLine = res.readLine(); responseLine != null; responseLine = res.readLine()) { - response.append(responseLine); - } - res.close(); - return new ResponseEntity<>(response.toString(), HttpStatus.OK); - } + private ResponseEntity issueCommand(String url, String body, boolean isPut) + throws IOException { + URL command = new URL(url); + HttpURLConnection con = (HttpURLConnection) command.openConnection(); + if (isPut) { + con.setRequestMethod("PUT"); + con.setDoOutput(true); + con.setRequestProperty("Content-Type", "application/json"); + con.setRequestProperty("Content-Length", Integer.toString(body.length())); + OutputStream os = con.getOutputStream(); + os.write(body.getBytes()); + } + BufferedReader res = new BufferedReader(new InputStreamReader(con.getInputStream())); + StringBuilder response = new StringBuilder(); + for (String responseLine = res.readLine(); responseLine != null; responseLine = + res.readLine()) { + response.append(responseLine); + } + res.close(); + return new ResponseEntity<>(response.toString(), HttpStatus.OK); + } } diff --git a/src/main/java/org/edgexfoundry/controller/LocalErrorController.java b/src/main/java/org/edgexfoundry/controller/LocalErrorController.java index 31d1d99..6dea6a4 100644 --- a/src/main/java/org/edgexfoundry/controller/LocalErrorController.java +++ b/src/main/java/org/edgexfoundry/controller/LocalErrorController.java @@ -1,22 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 Dell Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * - * @microservice: core-command + * @microservice: core-command * @author: Jim White, Dell * @version: 1.0.0 *******************************************************************************/ + package org.edgexfoundry.controller; import java.util.Map; @@ -34,29 +33,30 @@ @RestController public class LocalErrorController implements ErrorController { - - private static final String PATH = "/error"; - - @Autowired - private ErrorAttributes errorAttributes; - - @RequestMapping(value = PATH) - public String error(HttpServletRequest request, HttpServletResponse response) { - // Appropriate HTTP response code (e.g. 404 or 500) is automatically set - // by Spring. - // Here we just define response body. - Map errorInfo = getErrorAttributes(request, true); - return errorInfo.get("message") + "\n\n" + errorInfo.get("trace"); - } - - @Override - public String getErrorPath() { - return PATH; - } - - private Map getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { - RequestAttributes requestAttributes = new ServletRequestAttributes(request); - return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace); - } + + private static final String PATH = "/error"; + + @Autowired + private ErrorAttributes errorAttributes; + + @RequestMapping(value = PATH) + public String error(HttpServletRequest request, HttpServletResponse response) { + // Appropriate HTTP response code (e.g. 404 or 500) is automatically set + // by Spring. + // Here we just define response body. + Map errorInfo = getErrorAttributes(request, true); + return errorInfo.get("message") + "\n\n" + errorInfo.get("trace"); + } + + @Override + public String getErrorPath() { + return PATH; + } + + private Map getErrorAttributes(HttpServletRequest request, + boolean includeStackTrace) { + RequestAttributes requestAttributes = new ServletRequestAttributes(request); + return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace); + } } diff --git a/src/main/java/org/edgexfoundry/controller/PingController.java b/src/main/java/org/edgexfoundry/controller/PingController.java index 56d8a38..0142dea 100644 --- a/src/main/java/org/edgexfoundry/controller/PingController.java +++ b/src/main/java/org/edgexfoundry/controller/PingController.java @@ -1,22 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 Dell Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * - * @microservice: core-command + * @microservice: core-command * @author: Jim White, Dell * @version: 1.0.0 *******************************************************************************/ + package org.edgexfoundry.controller; import org.edgexfoundry.exception.controller.ServiceException; @@ -28,25 +27,23 @@ @RequestMapping("/api/v1/ping") public class PingController { - // private static final Logger logger = - // Logger.getLogger(PingController.class); - private final static org.edgexfoundry.support.logging.client.EdgeXLogger logger = org.edgexfoundry.support.logging.client.EdgeXLoggerFactory - .getEdgeXLogger(PingController.class); + private static final org.edgexfoundry.support.logging.client.EdgeXLogger logger = + org.edgexfoundry.support.logging.client.EdgeXLoggerFactory + .getEdgeXLogger(PingController.class); - /** - * Test service providing an indication that the service is available. - * - * @throws ServcieException - * (HTTP 503) for unknown or unanticipated issues - * @return - pong as a string - */ - @RequestMapping(method = RequestMethod.GET) - public String ping() { - try { - return "pong"; - } catch (Exception e) { - logger.error("Error on ping: " + e.getMessage()); - throw new ServiceException(e); - } - } -} \ No newline at end of file + /** + * Test service providing an indication that the service is available. + * + * @throws ServcieException (HTTP 503) for unknown or unanticipated issues + * @return - pong as a string + */ + @RequestMapping(method = RequestMethod.GET) + public String ping() { + try { + return "pong"; + } catch (Exception e) { + logger.error("Error on ping: " + e.getMessage()); + throw new ServiceException(e); + } + } +} diff --git a/src/main/java/org/edgexfoundry/domain/CommandResponse.java b/src/main/java/org/edgexfoundry/domain/CommandResponse.java index 63a46a8..b691630 100644 --- a/src/main/java/org/edgexfoundry/domain/CommandResponse.java +++ b/src/main/java/org/edgexfoundry/domain/CommandResponse.java @@ -1,22 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 Dell Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * - * @microservice: core-command + * @microservice: core-command * @author: Jim White, Dell * @version: 1.0.0 *******************************************************************************/ + package org.edgexfoundry.domain; import org.edgexfoundry.domain.meta.Device; @@ -27,28 +26,28 @@ @JsonSerialize(using = CommandResponseSerializer.class) public class CommandResponse { - private Device device; - private String host; + private Device device; + private String host; - public CommandResponse(Device device, String host) { - this.device = device; - this.host = host; - } + public CommandResponse(Device device, String host) { + this.device = device; + this.host = host; + } - public Device getDevice() { - return device; - } + public Device getDevice() { + return device; + } - public void setDevice(Device device) { - this.device = device; - } + public void setDevice(Device device) { + this.device = device; + } - public String getHost() { - return host; - } + public String getHost() { + return host; + } - public void setHost(String host) { - this.host = host; - } + public void setHost(String host) { + this.host = host; + } } diff --git a/src/main/java/org/edgexfoundry/domain/serializer/CommandResponseSerializer.java b/src/main/java/org/edgexfoundry/domain/serializer/CommandResponseSerializer.java index f6e02fc..4e5cfb8 100644 --- a/src/main/java/org/edgexfoundry/domain/serializer/CommandResponseSerializer.java +++ b/src/main/java/org/edgexfoundry/domain/serializer/CommandResponseSerializer.java @@ -1,22 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 Dell Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * - * @microservice: core-command + * @microservice: core-command * @author: Jim White, Dell * @version: 1.0.0 *******************************************************************************/ + package org.edgexfoundry.domain.serializer; import java.io.IOException; @@ -36,117 +35,118 @@ public class CommandResponseSerializer extends JsonSerializer { - @Value("${url.protocol}") - private String urlProtocol; + @Value("${url.protocol}") + private String urlProtocol; - @Value("${url.cmd.path}") - private String urlCmdPath; + @Value("${url.cmd.path}") + private String urlCmdPath; - @Value("${url.device.path}") - private String urlDevicePath; + @Value("${url.device.path}") + private String urlDevicePath; - @Override - public void serialize(CommandResponse cmdResp, JsonGenerator jgen, SerializerProvider provider) - throws IOException, JsonProcessingException { - Device device = cmdResp.getDevice(); - String host = cmdResp.getHost(); - // write the device to Json - jgen.writeStartObject(); - jgen.writeStringField("name", device.getName()); - jgen.writeStringField("id", device.getId()); + @Override + public void serialize(CommandResponse cmdResp, JsonGenerator jgen, SerializerProvider provider) + throws IOException { + Device device = cmdResp.getDevice(); + String host = cmdResp.getHost(); + // write the device to Json + jgen.writeStartObject(); + jgen.writeStringField("name", device.getName()); + jgen.writeStringField("id", device.getId()); - if (device.getDescription() != null) - jgen.writeStringField("description", device.getDescription()); - else - jgen.writeNullField("description"); - if (device.getLabels() != null) { - jgen.writeArrayFieldStart("labels"); - for (String label : device.getLabels()) { - jgen.writeString(label); - } - jgen.writeEndArray(); - } else - jgen.writeNullField("labels"); - jgen.writeStringField("adminState", device.getAdminState().toString()); - jgen.writeStringField("operatingState", device.getOperatingState().toString()); - jgen.writeNumberField("lastConnected", device.getLastConnected()); - jgen.writeNumberField("lastReported", device.getLastReported()); - if (device.getLocation() != null) - jgen.writeObjectField("location", device.getLocation()); - else - jgen.writeNullField("location"); - if (device.getProfile() != null && device.getProfile().getCommands() != null - && !device.getProfile().getCommands().isEmpty()) { - jgen.writeArrayFieldStart("commands"); - for (Command command : device.getProfile().getCommands()) { - serializeCommand(command, jgen, host, device.getId()); - } - jgen.writeEndArray(); - } else { - jgen.writeNullField("commands"); - } - jgen.writeEndObject(); - } + if (device.getDescription() != null) + jgen.writeStringField("description", device.getDescription()); + else + jgen.writeNullField("description"); + if (device.getLabels() != null) { + jgen.writeArrayFieldStart("labels"); + for (String label : device.getLabels()) { + jgen.writeString(label); + } + jgen.writeEndArray(); + } else + jgen.writeNullField("labels"); + jgen.writeStringField("adminState", device.getAdminState().toString()); + jgen.writeStringField("operatingState", device.getOperatingState().toString()); + jgen.writeNumberField("lastConnected", device.getLastConnected()); + jgen.writeNumberField("lastReported", device.getLastReported()); + if (device.getLocation() != null) + jgen.writeObjectField("location", device.getLocation()); + else + jgen.writeNullField("location"); + if (device.getProfile() != null && device.getProfile().getCommands() != null + && !device.getProfile().getCommands().isEmpty()) { + jgen.writeArrayFieldStart("commands"); + for (Command command : device.getProfile().getCommands()) { + serializeCommand(command, jgen, host, device.getId()); + } + jgen.writeEndArray(); + } else { + jgen.writeNullField("commands"); + } + jgen.writeEndObject(); + } - public void serializeCommand(Command command, JsonGenerator jgen, String host, String deviceId) - throws IOException, JsonProcessingException { - jgen.writeStartObject(); - jgen.writeStringField("id", command.getId()); - jgen.writeStringField("name", command.getName()); - if (command.getGet() != null) { - jgen.writeObjectFieldStart("get"); - serializeAction(command.getGet(), jgen, host, deviceId, command.getId(), true); - jgen.writeEndObject(); - } else - jgen.writeNullField("get"); - if (command.getPut() != null) { - jgen.writeObjectFieldStart("put"); - serializeAction(command.getPut(), jgen, host, deviceId, command.getId(), false); - jgen.writeEndObject(); - } else - jgen.writeNullField("put"); - jgen.writeEndObject(); + public void serializeCommand(Command command, JsonGenerator jgen, String host, String deviceId) + throws IOException { + jgen.writeStartObject(); + jgen.writeStringField("id", command.getId()); + jgen.writeStringField("name", command.getName()); + if (command.getGet() != null) { + jgen.writeObjectFieldStart("get"); + serializeAction(command.getGet(), jgen, host, deviceId, command.getId(), true); + jgen.writeEndObject(); + } else + jgen.writeNullField("get"); + if (command.getPut() != null) { + jgen.writeObjectFieldStart("put"); + serializeAction(command.getPut(), jgen, host, deviceId, command.getId(), false); + jgen.writeEndObject(); + } else + jgen.writeNullField("put"); + jgen.writeEndObject(); - } + } - public void serializeAction(Action action, JsonGenerator jgen, String host, String deviceId, String cmdId, - boolean isGet) throws IOException, JsonProcessingException { - jgen.writeStringField("url", urlProtocol + host + urlDevicePath + deviceId + urlCmdPath + cmdId); - if (action instanceof Put) { - jgen.writeArrayFieldStart("parameternames"); - for (String param : ((Put) action).getParameterNames()) { - jgen.writeString(param); - } - jgen.writeEndArray(); - } - if (action.getResponses() != null) { - jgen.writeArrayFieldStart("responses"); - for (Response resp : action.getResponses()) { - serializeResponse(resp, jgen); - } - jgen.writeEndArray(); - } else - jgen.writeNullField("responses"); - } + public void serializeAction(Action action, JsonGenerator jgen, String host, String deviceId, + String cmdId, boolean isGet) throws IOException { + jgen.writeStringField("url", + urlProtocol + host + urlDevicePath + deviceId + urlCmdPath + cmdId); + if (action instanceof Put) { + jgen.writeArrayFieldStart("parameternames"); + for (String param : ((Put) action).getParameterNames()) { + jgen.writeString(param); + } + jgen.writeEndArray(); + } + if (action.getResponses() != null) { + jgen.writeArrayFieldStart("responses"); + for (Response resp : action.getResponses()) { + serializeResponse(resp, jgen); + } + jgen.writeEndArray(); + } else + jgen.writeNullField("responses"); + } - public void serializeResponse(Response resp, JsonGenerator jgen) throws IOException { - jgen.writeStartObject(); - if (resp.getCode() != null) - jgen.writeStringField("code", resp.getCode()); - else - jgen.writeNullField("code"); - if (resp.getDescription() != null) - jgen.writeStringField("description", resp.getDescription()); - else - jgen.writeNullField("description"); - if (resp.getExpectedValues() != null) { - jgen.writeArrayFieldStart("expectedValues"); - for (String expected : resp.getExpectedValues()) { - jgen.writeString(expected); - } - jgen.writeEndArray(); - } else - jgen.writeNullField("expectedValues"); - jgen.writeEndObject(); - } + public void serializeResponse(Response resp, JsonGenerator jgen) throws IOException { + jgen.writeStartObject(); + if (resp.getCode() != null) + jgen.writeStringField("code", resp.getCode()); + else + jgen.writeNullField("code"); + if (resp.getDescription() != null) + jgen.writeStringField("description", resp.getDescription()); + else + jgen.writeNullField("description"); + if (resp.getExpectedValues() != null) { + jgen.writeArrayFieldStart("expectedValues"); + for (String expected : resp.getExpectedValues()) { + jgen.writeString(expected); + } + jgen.writeEndArray(); + } else + jgen.writeNullField("expectedValues"); + jgen.writeEndObject(); + } } diff --git a/src/test/java/org/edgexfoundry/controller/integration/web/CommandControllerTest.java b/src/test/java/org/edgexfoundry/controller/integration/web/CommandControllerTest.java index 1f51d11..14636e8 100644 --- a/src/test/java/org/edgexfoundry/controller/integration/web/CommandControllerTest.java +++ b/src/test/java/org/edgexfoundry/controller/integration/web/CommandControllerTest.java @@ -1,22 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 Dell Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * - * @microservice: core-command + * @microservice: core-command * @author: Jim White, Dell * @version: 1.0.0 *******************************************************************************/ + package org.edgexfoundry.controller.integration.web; import static org.edgexfoundry.test.data.CommandResponseData.TEST_HOST; @@ -81,296 +80,300 @@ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration("src/test/resources") -@Category({ RequiresMongoDB.class, RequiresMetaDataRunning.class, RequiresSpring.class, RequiresWeb.class }) +@Category({RequiresMongoDB.class, RequiresMetaDataRunning.class, RequiresSpring.class, + RequiresWeb.class}) public class CommandControllerTest { - private static final String CLIENT_FIELD = "deviceClient"; - private static int TEST_PORT = 48089; - - private static final String ENDPT = "http://localhost:48081/api/v1/device"; - private static final String SRV_ENDPT = "http://localhost:48081/api/v1/deviceservice"; - private static final String PRO_ENDPT = "http://localhost:48081/api/v1/deviceprofile"; - private static final String ADDR_ENDPT = "http://localhost:48081/api/v1/addressable"; - private static final String CMD_ENDPT = "http://localhost:48081/api/v1/command"; - - @Autowired - private CommandController controller; - - private DeviceClient client; - private DeviceServiceClient srvClient; - private DeviceProfileClient proClient; - private AddressableClient addrClient; - private CommandClient cmdClient; - private String id; - private String pId; - - @Before - public void setup() throws Exception { - client = new DeviceClientImpl(); - srvClient = new DeviceServiceClientImpl(); - proClient = new DeviceProfileClientImpl(); - addrClient = new AddressableClientImpl(); - cmdClient = new CommandClientImpl(); - setURL(); - Addressable a = AddressableData.newTestInstance(); - addrClient.add(a); - DeviceService s = ServiceData.newTestInstance(); - s.setAddressable(a); - srvClient.add(s); - DeviceProfile p = ProfileData.newTestInstance(); - Command command = CommandData.newTestInstance(); - p.addCommand(command); - pId = proClient.add(p); - Device device = DeviceData.newTestInstance(); - device.setAddressable(a); - device.setProfile(p); - device.setService(s); - id = client.add(device); - assertNotNull("Device did not get created correctly", id); - } - - private void setURL() throws Exception { - Class clientClass = client.getClass(); - Field temp = clientClass.getDeclaredField("url"); - temp.setAccessible(true); - temp.set(client, ENDPT); - Class clientClass2 = proClient.getClass(); - Field temp2 = clientClass2.getDeclaredField("url"); - temp2.setAccessible(true); - temp2.set(proClient, PRO_ENDPT); - Class clientClass3 = srvClient.getClass(); - Field temp3 = clientClass3.getDeclaredField("url"); - temp3.setAccessible(true); - temp3.set(srvClient, SRV_ENDPT); - Class clientClass4 = addrClient.getClass(); - Field temp4 = clientClass4.getDeclaredField("url"); - temp4.setAccessible(true); - temp4.set(addrClient, ADDR_ENDPT); - Class clientClass5 = cmdClient.getClass(); - Field temp5 = clientClass5.getDeclaredField("url"); - temp5.setAccessible(true); - temp5.set(cmdClient, CMD_ENDPT); - } - - @After - public void cleanup() throws Exception { - resetClient(); - List devices = client.devices(); - devices.forEach((d) -> client.delete(d.getId())); - List ps = proClient.deviceProfiles(); - ps.forEach((p) -> proClient.delete(p.getId())); - List ds = srvClient.deviceServices(); - ds.forEach((d) -> srvClient.delete(d.getId())); - List as = addrClient.addressables(); - as.forEach((a) -> addrClient.delete(a.getId())); - List cmds = cmdClient.commands(); - cmds.forEach((c) -> cmdClient.delete(c.getId())); - } - - @Test - public void testDevices() { - List responses = controller.devices(TEST_HOST); - assertEquals("Find all device command responses not returning a list with one device", 1, responses.size()); - checkTestData(responses.get(0)); - } - - @Test(expected = ServiceException.class) - public void testDevicesWithNoClient() throws Exception { - unsetClient(); - controller.devices(TEST_HOST); - } - - @Test - public void testDevice() { - checkTestData(controller.device(id, TEST_HOST)); - } - - @Test(expected = ServiceException.class) - public void testDeviceWithNoClient() throws Exception { - unsetClient(); - controller.device(id, TEST_HOST); - } - - @Test(expected = NotFoundException.class) - public void testDeviceWithBadId() { - controller.device("baddeviceid", TEST_HOST); - } - - @Test - public void testDeviceByName() { - checkTestData(controller.deviceByName(DeviceData.TEST_NAME, TEST_HOST)); - } - - @Test(expected = NotFoundException.class) - public void testDeviceWithBadName() { - controller.deviceByName("baddevicename", TEST_HOST); - } - - @Test(expected = ServiceException.class) - public void testDeviceByNameWithNoClient() throws Exception { - unsetClient(); - controller.deviceByName(DeviceData.TEST_NAME, TEST_HOST); - } - - @Test - public void testGet() throws IOException { - HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); - server.createContext("/", new TestHandler()); - server.setExecutor(null); - server.start(); - DeviceProfile p = proClient.deviceProfile(pId); - assertEquals("get response not ok", HttpStatus.OK, - controller.get(id, p.getCommands().get(0).getId()).getStatusCode()); - server.stop(0); - } - - @Test(expected = ServiceException.class) - public void testGetWithNoClient() throws Exception { - unsetClient(); - DeviceProfile p = proClient.deviceProfile(pId); - controller.get(id, p.getCommands().get(0).getId()).toString(); - } - - @Test(expected = NotFoundException.class) - public void testGetWithBadId() { - controller.get("badid", "badcommandid").toString(); - } - - @Test - public void testPut() throws IOException { - HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); - server.createContext("/", new TestHandler()); - server.setExecutor(null); - server.start(); - DeviceProfile p = proClient.deviceProfile(pId); - assertEquals("put response not ok", HttpStatus.OK, - controller.put(id, p.getCommands().get(0).getId(), TEST_PARAMS).getStatusCode()); - server.stop(0); - } - - @Test(expected = ServiceException.class) - public void testPutWithNoClient() throws Exception { - unsetClient(); - DeviceProfile p = proClient.deviceProfile(pId); - controller.put(id, p.getCommands().get(0).getId(), TEST_PARAMS).toString(); - } - - @Test(expected = NotFoundException.class) - public void testPutWithBadId() { - controller.put("badid", "badcommandid", TEST_PARAMS).toString(); - } - - @Test(expected = NotFoundException.class) - public void testPutOpStateWithBadId() throws IOException { - controller.putOpState("badid", OperatingState.disabled.toString()); - } - - @Test(expected = ServiceException.class) - public void testPutOpStateWithNoClient() throws Exception { - unsetClient(); - controller.putOpState("badid", OperatingState.disabled.toString()); - } - - @Test - public void testPutOpState() throws IOException { - HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); - server.createContext("/", new TestHandler()); - server.setExecutor(null); - server.start(); - assertTrue("OpState change not accepted", controller.putOpState(id, OperatingState.disabled.toString())); - server.stop(0); - } - - @Test - public void testPutOpStateByName() throws IOException { - HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); - server.createContext("/", new TestHandler()); - server.setExecutor(null); - server.start(); - assertTrue("OpState change by name not accepted", - controller.putOpStateByName(DeviceData.TEST_NAME, OperatingState.disabled.toString())); - server.stop(0); - } - - @Test(expected = NotFoundException.class) - public void testPutOpStateByNameWithBadId() throws IOException { - controller.putOpStateByName("badname", OperatingState.disabled.toString()); - } - - @Test(expected = ServiceException.class) - public void testPutOpStateByNameWithNoClient() throws Exception { - unsetClient(); - controller.putOpStateByName("badname", OperatingState.disabled.toString()); - } - - @Test - public void testPutAdminState() throws IOException { - HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); - server.createContext("/", new TestHandler()); - server.setExecutor(null); - server.start(); - assertTrue("Admin state change not accepted", controller.putAdminState(id, AdminState.locked.toString())); - server.stop(0); - } - - @Test(expected = NotFoundException.class) - public void testPutAdminStateWithBadId() throws IOException { - controller.putAdminState("badid", AdminState.locked.toString()); - } - - @Test(expected = ServiceException.class) - public void testPutAdminStateWithNoClient() throws Exception { - unsetClient(); - controller.putAdminState("badid", AdminState.locked.toString()); - } - - @Test - public void testPutAdminStateByName() throws IOException { - HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); - server.createContext("/", new TestHandler()); - server.setExecutor(null); - server.start(); - assertTrue("Admin state change by name not accepted", - controller.putAdminStateByName(DeviceData.TEST_NAME, AdminState.locked.toString())); - server.stop(0); - } - - @Test(expected = NotFoundException.class) - public void testPutAdminStateByNameWithBadId() throws IOException { - controller.putAdminStateByName("badname", AdminState.locked.toString()); - } - - @Test(expected = ServiceException.class) - public void testPutAdminStateByNameWithNoClient() throws Exception { - unsetClient(); - controller.putAdminStateByName("badname", AdminState.locked.toString()); - } - - private void unsetClient() throws Exception { - Class controllerClass = controller.getClass(); - Field temp = controllerClass.getDeclaredField(CLIENT_FIELD); - temp.setAccessible(true); - temp.set(controller, null); - } - - private void resetClient() throws Exception { - Class controllerClass = controller.getClass(); - Field temp = controllerClass.getDeclaredField(CLIENT_FIELD); - temp.setAccessible(true); - temp.set(controller, client); - } - - public class TestHandler implements HttpHandler { - - @Override - - public void handle(HttpExchange he) throws IOException { - String response = "ok"; - he.sendResponseHeaders(200, response.length()); - OutputStream os = he.getResponseBody(); - os.write(response.getBytes()); - os.close(); - } - } + private static final String CLIENT_FIELD = "deviceClient"; + private static int TEST_PORT = 48089; + + private static final String ENDPT = "http://localhost:48081/api/v1/device"; + private static final String SRV_ENDPT = "http://localhost:48081/api/v1/deviceservice"; + private static final String PRO_ENDPT = "http://localhost:48081/api/v1/deviceprofile"; + private static final String ADDR_ENDPT = "http://localhost:48081/api/v1/addressable"; + private static final String CMD_ENDPT = "http://localhost:48081/api/v1/command"; + + @Autowired + private CommandController controller; + + private DeviceClient client; + private DeviceServiceClient srvClient; + private DeviceProfileClient proClient; + private AddressableClient addrClient; + private CommandClient cmdClient; + private String id; + private String pId; + + @Before + public void setup() throws Exception { + client = new DeviceClientImpl(); + srvClient = new DeviceServiceClientImpl(); + proClient = new DeviceProfileClientImpl(); + addrClient = new AddressableClientImpl(); + cmdClient = new CommandClientImpl(); + setURL(); + Addressable a = AddressableData.newTestInstance(); + addrClient.add(a); + DeviceService s = ServiceData.newTestInstance(); + s.setAddressable(a); + srvClient.add(s); + DeviceProfile p = ProfileData.newTestInstance(); + Command command = CommandData.newTestInstance(); + p.addCommand(command); + pId = proClient.add(p); + Device device = DeviceData.newTestInstance(); + device.setAddressable(a); + device.setProfile(p); + device.setService(s); + id = client.add(device); + assertNotNull("Device did not get created correctly", id); + } + + private void setURL() throws Exception { + Class clientClass = client.getClass(); + Field temp = clientClass.getDeclaredField("url"); + temp.setAccessible(true); + temp.set(client, ENDPT); + Class clientClass2 = proClient.getClass(); + Field temp2 = clientClass2.getDeclaredField("url"); + temp2.setAccessible(true); + temp2.set(proClient, PRO_ENDPT); + Class clientClass3 = srvClient.getClass(); + Field temp3 = clientClass3.getDeclaredField("url"); + temp3.setAccessible(true); + temp3.set(srvClient, SRV_ENDPT); + Class clientClass4 = addrClient.getClass(); + Field temp4 = clientClass4.getDeclaredField("url"); + temp4.setAccessible(true); + temp4.set(addrClient, ADDR_ENDPT); + Class clientClass5 = cmdClient.getClass(); + Field temp5 = clientClass5.getDeclaredField("url"); + temp5.setAccessible(true); + temp5.set(cmdClient, CMD_ENDPT); + } + + @After + public void cleanup() throws Exception { + resetClient(); + List devices = client.devices(); + devices.forEach((d) -> client.delete(d.getId())); + List ps = proClient.deviceProfiles(); + ps.forEach((p) -> proClient.delete(p.getId())); + List ds = srvClient.deviceServices(); + ds.forEach((d) -> srvClient.delete(d.getId())); + List as = addrClient.addressables(); + as.forEach((a) -> addrClient.delete(a.getId())); + List cmds = cmdClient.commands(); + cmds.forEach((c) -> cmdClient.delete(c.getId())); + } + + @Test + public void testDevices() { + List responses = controller.devices(TEST_HOST); + assertEquals("Find all device command responses not returning a list with one device", 1, + responses.size()); + checkTestData(responses.get(0)); + } + + @Test(expected = ServiceException.class) + public void testDevicesWithNoClient() throws Exception { + unsetClient(); + controller.devices(TEST_HOST); + } + + @Test + public void testDevice() { + checkTestData(controller.device(id, TEST_HOST)); + } + + @Test(expected = ServiceException.class) + public void testDeviceWithNoClient() throws Exception { + unsetClient(); + controller.device(id, TEST_HOST); + } + + @Test(expected = NotFoundException.class) + public void testDeviceWithBadId() { + controller.device("baddeviceid", TEST_HOST); + } + + @Test + public void testDeviceByName() { + checkTestData(controller.deviceByName(DeviceData.TEST_NAME, TEST_HOST)); + } + + @Test(expected = NotFoundException.class) + public void testDeviceWithBadName() { + controller.deviceByName("baddevicename", TEST_HOST); + } + + @Test(expected = ServiceException.class) + public void testDeviceByNameWithNoClient() throws Exception { + unsetClient(); + controller.deviceByName(DeviceData.TEST_NAME, TEST_HOST); + } + + @Test + public void testGet() throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); + server.createContext("/", new TestHandler()); + server.setExecutor(null); + server.start(); + DeviceProfile p = proClient.deviceProfile(pId); + assertEquals("get response not ok", HttpStatus.OK, + controller.get(id, p.getCommands().get(0).getId()).getStatusCode()); + server.stop(0); + } + + @Test(expected = ServiceException.class) + public void testGetWithNoClient() throws Exception { + unsetClient(); + DeviceProfile p = proClient.deviceProfile(pId); + controller.get(id, p.getCommands().get(0).getId()).toString(); + } + + @Test(expected = NotFoundException.class) + public void testGetWithBadId() { + controller.get("badid", "badcommandid").toString(); + } + + @Test + public void testPut() throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); + server.createContext("/", new TestHandler()); + server.setExecutor(null); + server.start(); + DeviceProfile p = proClient.deviceProfile(pId); + assertEquals("put response not ok", HttpStatus.OK, + controller.put(id, p.getCommands().get(0).getId(), TEST_PARAMS).getStatusCode()); + server.stop(0); + } + + @Test(expected = ServiceException.class) + public void testPutWithNoClient() throws Exception { + unsetClient(); + DeviceProfile p = proClient.deviceProfile(pId); + controller.put(id, p.getCommands().get(0).getId(), TEST_PARAMS).toString(); + } + + @Test(expected = NotFoundException.class) + public void testPutWithBadId() { + controller.put("badid", "badcommandid", TEST_PARAMS).toString(); + } + + @Test(expected = NotFoundException.class) + public void testPutOpStateWithBadId() throws IOException { + controller.putOpState("badid", OperatingState.disabled.toString()); + } + + @Test(expected = ServiceException.class) + public void testPutOpStateWithNoClient() throws Exception { + unsetClient(); + controller.putOpState("badid", OperatingState.disabled.toString()); + } + + @Test + public void testPutOpState() throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); + server.createContext("/", new TestHandler()); + server.setExecutor(null); + server.start(); + assertTrue("OpState change not accepted", + controller.putOpState(id, OperatingState.disabled.toString())); + server.stop(0); + } + + @Test + public void testPutOpStateByName() throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); + server.createContext("/", new TestHandler()); + server.setExecutor(null); + server.start(); + assertTrue("OpState change by name not accepted", + controller.putOpStateByName(DeviceData.TEST_NAME, OperatingState.disabled.toString())); + server.stop(0); + } + + @Test(expected = NotFoundException.class) + public void testPutOpStateByNameWithBadId() throws IOException { + controller.putOpStateByName("badname", OperatingState.disabled.toString()); + } + + @Test(expected = ServiceException.class) + public void testPutOpStateByNameWithNoClient() throws Exception { + unsetClient(); + controller.putOpStateByName("badname", OperatingState.disabled.toString()); + } + + @Test + public void testPutAdminState() throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); + server.createContext("/", new TestHandler()); + server.setExecutor(null); + server.start(); + assertTrue("Admin state change not accepted", + controller.putAdminState(id, AdminState.locked.toString())); + server.stop(0); + } + + @Test(expected = NotFoundException.class) + public void testPutAdminStateWithBadId() throws IOException { + controller.putAdminState("badid", AdminState.locked.toString()); + } + + @Test(expected = ServiceException.class) + public void testPutAdminStateWithNoClient() throws Exception { + unsetClient(); + controller.putAdminState("badid", AdminState.locked.toString()); + } + + @Test + public void testPutAdminStateByName() throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress(TEST_PORT), 0); + server.createContext("/", new TestHandler()); + server.setExecutor(null); + server.start(); + assertTrue("Admin state change by name not accepted", + controller.putAdminStateByName(DeviceData.TEST_NAME, AdminState.locked.toString())); + server.stop(0); + } + + @Test(expected = NotFoundException.class) + public void testPutAdminStateByNameWithBadId() throws IOException { + controller.putAdminStateByName("badname", AdminState.locked.toString()); + } + + @Test(expected = ServiceException.class) + public void testPutAdminStateByNameWithNoClient() throws Exception { + unsetClient(); + controller.putAdminStateByName("badname", AdminState.locked.toString()); + } + + private void unsetClient() throws Exception { + Class controllerClass = controller.getClass(); + Field temp = controllerClass.getDeclaredField(CLIENT_FIELD); + temp.setAccessible(true); + temp.set(controller, null); + } + + private void resetClient() throws Exception { + Class controllerClass = controller.getClass(); + Field temp = controllerClass.getDeclaredField(CLIENT_FIELD); + temp.setAccessible(true); + temp.set(controller, client); + } + + public class TestHandler implements HttpHandler { + + @Override + + public void handle(HttpExchange he) throws IOException { + String response = "ok"; + he.sendResponseHeaders(200, response.length()); + OutputStream os = he.getResponseBody(); + os.write(response.getBytes()); + os.close(); + } + } } diff --git a/src/test/java/org/edgexfoundry/domain/serializer/CommandResponseSerializerTest.java b/src/test/java/org/edgexfoundry/domain/serializer/CommandResponseSerializerTest.java index cdaea9e..467af26 100644 --- a/src/test/java/org/edgexfoundry/domain/serializer/CommandResponseSerializerTest.java +++ b/src/test/java/org/edgexfoundry/domain/serializer/CommandResponseSerializerTest.java @@ -1,22 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 Dell Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * - * @microservice: core-command + * @microservice: core-command * @author: Jim White, Dell * @version: 1.0.0 *******************************************************************************/ + package org.edgexfoundry.domain.serializer; import static org.edgexfoundry.test.data.CommandResponseData.TEST_HOST; @@ -46,69 +45,72 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; -@Category({ RequiresNone.class }) +@Category({RequiresNone.class}) public class CommandResponseSerializerTest { - private static final String RESULT_JSON1 = "{\"name\":\"TEST_DEVICE.NAME\",\"id\":null,\"description\":\"TEST_DESCRIPTION\",\"labels\":[\"MODBUS\",\"TEMP\"],\"adminState\":\"unlocked\",\"operatingState\":\"enabled\",\"lastConnected\":1000000,\"lastReported\":1000000,\"location\":\"{40lat;45long}\",\"commands\":[{\"id\":null,\"name\":\"setTemp\",\"get\":{\"url\":\"nulllocalhostnullnullnullnull\",\"responses\":[{\"code\":\"200\",\"description\":\"ok\",\"expectedValues\":[\"temperature\",\"humidity\"]}]},\"put\":{\"url\":\"nulllocalhostnullnullnullnull\",\"parameternames\":[\"Temperature\",\"Humidity\"],\"responses\":[{\"code\":\"200\",\"description\":\"ok\",\"expectedValues\":[\"temperature\",\"humidity\"]}]}}]}"; - private static final String RESULT_JSON2 = "{\"name\":\"TEST_DEVICE.NAME\",\"id\":null,\"description\":null,\"labels\":null,\"adminState\":\"unlocked\",\"operatingState\":\"enabled\",\"lastConnected\":1000000,\"lastReported\":1000000,\"location\":null,\"commands\":null}"; + private static final String RESULT_JSON1 = + "{\"name\":\"TEST_DEVICE.NAME\",\"id\":null,\"description\":\"TEST_DESCRIPTION\",\"labels\":[\"MODBUS\",\"TEMP\"],\"adminState\":\"UNLOCKED\",\"operatingState\":\"ENABLED\",\"lastConnected\":1000000,\"lastReported\":1000000,\"location\":\"{40lat;45long}\",\"commands\":[{\"id\":null,\"name\":\"setTemp\",\"get\":{\"url\":\"nulllocalhostnullnullnullnull\",\"responses\":[{\"code\":\"200\",\"description\":\"ok\",\"expectedValues\":[\"temperature\",\"humidity\"]}]},\"put\":{\"url\":\"nulllocalhostnullnullnullnull\",\"parameternames\":[\"Temperature\",\"Humidity\"],\"responses\":[{\"code\":\"200\",\"description\":\"ok\",\"expectedValues\":[\"temperature\",\"humidity\"]}]}}]}"; + private static final String RESULT_JSON2 = + "{\"name\":\"TEST_DEVICE.NAME\",\"id\":null,\"description\":null,\"labels\":null,\"adminState\":\"UNLOCKED\",\"operatingState\":\"ENABLED\",\"lastConnected\":1000000,\"lastReported\":1000000,\"location\":null,\"commands\":null}"; + + CommandResponseSerializer serializer; + JsonGenerator jgen; + SerializerProvider provider; + StringWriter stringJson; + + @Before + public void setup() throws IOException { + serializer = new CommandResponseSerializer(); + stringJson = new StringWriter(); + jgen = new JsonFactory().createGenerator(stringJson); + provider = new ObjectMapper().getSerializerProvider(); + } - CommandResponseSerializer serializer; - JsonGenerator jgen; - SerializerProvider provider; - StringWriter stringJson; + @After + public void cleanup() {} - @Before - public void setup() throws IOException { - serializer = new CommandResponseSerializer(); - stringJson = new StringWriter(); - jgen = new JsonFactory().createGenerator(stringJson); - provider = new ObjectMapper().getSerializerProvider(); - } + @Test + public void testSerialize() throws IOException { + Addressable a = AddressableData.newTestInstance(); + DeviceProfile p = ProfileData.newTestInstance(); + Command command = CommandData.newTestInstance(); + p.addCommand(command); + Device device = DeviceData.newTestInstance(); + device.setAddressable(a); + device.setProfile(p); + CommandResponse resp = new CommandResponse(device, TEST_HOST); + serializer.serialize(resp, jgen, provider); + jgen.flush(); + jgen.close(); + assertEquals("Serialized response does not match expected", RESULT_JSON1, + stringJson.toString()); + } - @After - public void cleanup() { - } + @Test + public void testProblematicNullFieldSerialization() throws IOException { + Addressable a = AddressableData.newTestInstance(); + DeviceProfile p = ProfileData.newTestInstance(); + Command command = CommandData.newTestInstance(); + p.addCommand(command); + Device device = DeviceData.newTestInstance(); + device.setAddressable(a); + device.setProfile(p); + CommandResponse resp = new CommandResponse(device, TEST_HOST); + // labels should be empty + device.setLabels(null); + // description should be empty + device.setDescription(null); + // location should be empty + device.setLocation(null); + // command should be empty + device.getProfile().setCommands(null); + serializer.serialize(resp, jgen, provider); + jgen.flush(); + jgen.close(); + System.out.println(stringJson.toString()); + assertEquals("Serialized response does not match expected", RESULT_JSON2, + stringJson.toString()); - @Test - public void testSerialize() throws IOException { - Addressable a = AddressableData.newTestInstance(); - DeviceProfile p = ProfileData.newTestInstance(); - Command command = CommandData.newTestInstance(); - p.addCommand(command); - Device device = DeviceData.newTestInstance(); - device.setAddressable(a); - device.setProfile(p); - CommandResponse resp = new CommandResponse(device, TEST_HOST); - serializer.serialize(resp, jgen, provider); - jgen.flush(); - jgen.close(); - assertEquals("Serialized response does not match expected", RESULT_JSON1, stringJson.toString()); - } - - @Test - public void testProblematicNullFieldSerialization() throws IOException { - Addressable a = AddressableData.newTestInstance(); - DeviceProfile p = ProfileData.newTestInstance(); - Command command = CommandData.newTestInstance(); - p.addCommand(command); - Device device = DeviceData.newTestInstance(); - device.setAddressable(a); - device.setProfile(p); - CommandResponse resp = new CommandResponse(device, TEST_HOST); - // labels should be empty - device.setLabels(null); - // description should be empty - device.setDescription(null); - // location should be empty - device.setLocation(null); - // command should be empty - device.getProfile().setCommands(null); - serializer.serialize(resp, jgen, provider); - jgen.flush(); - jgen.close(); - System.out.println(stringJson.toString()); - assertEquals("Serialized response does not match expected", RESULT_JSON2, stringJson.toString()); - - } + } } diff --git a/src/test/java/org/edgexfoundry/test/data/CommandResponseData.java b/src/test/java/org/edgexfoundry/test/data/CommandResponseData.java index c8ceb20..fbe80d2 100644 --- a/src/test/java/org/edgexfoundry/test/data/CommandResponseData.java +++ b/src/test/java/org/edgexfoundry/test/data/CommandResponseData.java @@ -1,22 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 Dell Inc. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * - * @microservice: core-command + * @microservice: core-command * @author: Jim White, Dell * @version: 1.0.0 *******************************************************************************/ + package org.edgexfoundry.test.data; import static org.edgexfoundry.test.data.DeviceData.TEST_ADMIN; @@ -34,25 +33,26 @@ public interface CommandResponseData { - static final String TEST_HOST = "localhost"; - static final String TEST_PARAMS = "{abc}"; + static final String TEST_HOST = "localhost"; + static final String TEST_PARAMS = "{abc}"; - static void checkTestData(CommandResponse response) { - assertEquals("Command response Host does not match expected", TEST_HOST, response.getHost()); - assertEquals("Command response device description does not match expected", TEST_DESCRIPTION, - response.getDevice().getDescription()); - assertEquals("Command response device name does not match expected", TEST_NAME, response.getDevice().getName()); - assertArrayEquals("Command response device labels does not match expected", TEST_LABELS, - response.getDevice().getLabels()); - assertEquals("Command response device last connected does not match expected", TEST_LAST_CONNECTED, - response.getDevice().getLastConnected()); - assertEquals("Command response device last reported does not match expected", TEST_LAST_REPORTED, - response.getDevice().getLastReported()); - assertEquals("Command response device location does not match expected", TEST_LOCATION, - response.getDevice().getLocation()); - assertEquals("Command response device operating state does not match expected", TEST_OP, - response.getDevice().getOperatingState()); - assertEquals("Command response device admin state does not match expected", TEST_ADMIN, - response.getDevice().getAdminState()); - } + static void checkTestData(CommandResponse response) { + assertEquals("Command response Host does not match expected", TEST_HOST, response.getHost()); + assertEquals("Command response device description does not match expected", TEST_DESCRIPTION, + response.getDevice().getDescription()); + assertEquals("Command response device name does not match expected", TEST_NAME, + response.getDevice().getName()); + assertArrayEquals("Command response device labels does not match expected", TEST_LABELS, + response.getDevice().getLabels()); + assertEquals("Command response device last connected does not match expected", + TEST_LAST_CONNECTED, response.getDevice().getLastConnected()); + assertEquals("Command response device last reported does not match expected", + TEST_LAST_REPORTED, response.getDevice().getLastReported()); + assertEquals("Command response device location does not match expected", TEST_LOCATION, + response.getDevice().getLocation()); + assertEquals("Command response device operating state does not match expected", TEST_OP, + response.getDevice().getOperatingState()); + assertEquals("Command response device admin state does not match expected", TEST_ADMIN, + response.getDevice().getAdminState()); + } }