From 9b21127106659de668a041ebc54b4a92968f6616 Mon Sep 17 00:00:00 2001 From: Predix Robot Date: Thu, 1 Feb 2018 15:05:12 -0800 Subject: [PATCH] Release 1.0.26 --- config/application-template.properties | 6 +- config/application.properties | 6 +- manifest.yml | 2 +- manifest.yml.template | 2 +- pom.xml | 6 +- .../solsvc/kitservice/boot/Application.java | 407 +++---- .../kitservice/boot/AuthenticationFilter.java | 226 ++-- .../boot/ErrorResponseController.java | 58 +- .../solsvc/kitservice/boot/EventError.java | 213 ++-- .../kitservice/boot/SwaggerConfiguration.java | 29 +- .../kitservice/boot/utils/CSVWriter.java | 153 +-- .../kitservice/boot/utils/FdhUtils.java | 434 +++---- .../controller/HelloController.java | 58 +- .../kitservice/controller/KitController.java | 822 ++++++------- .../error/DeviceRegistrationError.java | 105 +- .../kitservice/manager/BaseManager.java | 148 ++- .../kitservice/manager/DeviceManager.java | 945 ++++++++------- .../manager/GroupManagementService.java | 318 ++--- .../solsvc/kitservice/model/DeviceGroup.java | 88 +- .../solsvc/kitservice/model/GeoLocation.java | 88 +- .../kitservice/model/RegisterDevice.java | 603 +++++----- .../solsvc/kitservice/model/UserGroup.java | 190 +-- .../validator/RegisterDeviceValidation.java | 170 +-- .../service/AbstractBaseControllerIT.java | 7 +- .../solsvc/service/HelloControllerIT.java | 76 +- .../solsvc/service/KitControllerIT.java | 1068 +++++++++-------- 26 files changed, 3112 insertions(+), 3116 deletions(-) diff --git a/config/application-template.properties b/config/application-template.properties index da7aa72..012b425 100644 --- a/config/application-template.properties +++ b/config/application-template.properties @@ -9,8 +9,10 @@ server.port=9092 spring.profiles.active=local,asset #if you are behind a corporate proxy/firewall and want to access Predix Cloud -#predix.oauth.proxyHost =put.your.proxyHost.here -#predix.oauth.proxyPort=put.your.proxyPort.here +#predix.rest.proxyHost=put.your.proxyHost.here +#predix.rest.proxyPort=put.your.proxyPort.here +#predix.rest.proxyUser=put.your.proxyUser.here.if.needed +#predix.rest.proxyPassword=put.your.proxyPassword.here.if.needed #OAuth - please see predix-rest-client src/main/java/com/ge/predix/solsvc/restclient/config/OauthRestConfig.java for more info on oauth properties predix.oauth.issuerId.url=put.your.uaa.issuerId.here diff --git a/config/application.properties b/config/application.properties index da7aa72..012b425 100644 --- a/config/application.properties +++ b/config/application.properties @@ -9,8 +9,10 @@ server.port=9092 spring.profiles.active=local,asset #if you are behind a corporate proxy/firewall and want to access Predix Cloud -#predix.oauth.proxyHost =put.your.proxyHost.here -#predix.oauth.proxyPort=put.your.proxyPort.here +#predix.rest.proxyHost=put.your.proxyHost.here +#predix.rest.proxyPort=put.your.proxyPort.here +#predix.rest.proxyUser=put.your.proxyUser.here.if.needed +#predix.rest.proxyPassword=put.your.proxyPassword.here.if.needed #OAuth - please see predix-rest-client src/main/java/com/ge/predix/solsvc/restclient/config/OauthRestConfig.java for more info on oauth properties predix.oauth.issuerId.url=put.your.uaa.issuerId.here diff --git a/manifest.yml b/manifest.yml index d6fdd86..bd420f3 100644 --- a/manifest.yml +++ b/manifest.yml @@ -2,7 +2,7 @@ applications: - name: {your-name}-kit-service buildpack: java_buildpack - path: target/kit-service-1.0.23.jar + path: target/kit-service-1.0.26.jar memory: 512M timeout : 180 services: diff --git a/manifest.yml.template b/manifest.yml.template index d6fdd86..bd420f3 100644 --- a/manifest.yml.template +++ b/manifest.yml.template @@ -2,7 +2,7 @@ applications: - name: {your-name}-kit-service buildpack: java_buildpack - path: target/kit-service-1.0.23.jar + path: target/kit-service-1.0.26.jar memory: 512M timeout : 180 services: diff --git a/pom.xml b/pom.xml index 4acec2a..7b7550c 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ com.ge.predix.solsvc kit-service - 1.0.23 + 1.0.26 org.springframework.boot @@ -15,8 +15,8 @@ - 2.0.33 - 2.1.32 + 2.0.35 + 2.1.34 3.2.2 8.1.7.v20120910 diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/boot/Application.java b/src/main/java/com/ge/predix/solsvc/kitservice/boot/Application.java index f56cefe..9d74fdd 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/boot/Application.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/boot/Application.java @@ -53,238 +53,217 @@ @SpringBootApplication @EnableSwagger2 @Configuration -@EnableAutoConfiguration(exclude = -{ - DataSourceAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, - PersistenceExceptionTranslationAutoConfiguration.class -}) -@ComponentScan(basePackages = {"com.ge.predix.solsvc.kitservice"}) -@ImportResource( -{ - "classpath*:META-INF/application-security.xml", - "classpath*:META-INF/spring/predix-rest-client-scan-context.xml", - "classpath*:META-INF/spring/ext-util-scan-context.xml", - "classpath*:META-INF/spring/fdh-asset-handler-scan-context.xml", - "classpath*:META-INF/spring/timeseries-bootstrap-scan-context.xml" - }) +@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, + PersistenceExceptionTranslationAutoConfiguration.class }) +@ComponentScan(basePackages = { "com.ge.predix.solsvc.kitservice" }) +@ImportResource({ "classpath*:META-INF/application-security.xml", + "classpath*:META-INF/spring/predix-rest-client-scan-context.xml", + "classpath*:META-INF/spring/ext-util-scan-context.xml", + "classpath*:META-INF/spring/fdh-asset-handler-scan-context.xml", + "classpath*:META-INF/spring/timeseries-bootstrap-scan-context.xml" }) @Controller -public class Application -{ - private static final Logger log = LoggerFactory.getLogger(Application.class); - @SuppressWarnings("unused") - private static ApplicationContext context; - - /** - * - */ - static String[] profiles ; +public class Application { + private static final Logger log = LoggerFactory.getLogger(Application.class); + @SuppressWarnings("unused") + private static ApplicationContext context; - @SuppressWarnings("javadoc") - @Value("${java.docs.url:null}") - String docsUrl ; - - /** - * @param args - * - - */ - @SuppressWarnings({}) - public static void main(String[] args) - { - SpringApplication springApplication = new SpringApplication(Application.class); - ApplicationContext ctx = springApplication.run(args); - context = ctx; - log.debug("Let's inspect the beans provided by Spring Boot:"); //$NON-NLS-1$ - String[] beanNames = ctx.getBeanDefinitionNames(); - Arrays.sort(beanNames); - for (String beanName : beanNames) - { - log.debug(beanName); - } + /** + * + */ + static String[] profiles; - log.debug("Let's inspect the profiles provided by Spring Boot:"); //$NON-NLS-1$ - profiles = ctx.getEnvironment().getActiveProfiles(); - for (int i = 0; i < profiles.length; i++) - log.debug("profile****=" + profiles[i]); //$NON-NLS-1$ + @Value("${java.docs.url:null}") + private String docsUrl; - log.info("Let's inspect the properties provided by Spring Boot:"); //$NON-NLS-1$ - MutablePropertySources propertySources = ((StandardServletEnvironment) ctx.getEnvironment()) - .getPropertySources(); - Iterator> iterator = propertySources.iterator(); - while (iterator.hasNext()) - { - Object propertySourceObject = iterator.next(); - if ( propertySourceObject instanceof org.springframework.core.env.PropertySource ) - { - org.springframework.core.env.PropertySource propertySource = (org.springframework.core.env.PropertySource) propertySourceObject; - log.info("propertySource=" + propertySource.getName() + " values=" + propertySource.getSource() //$NON-NLS-1$ //$NON-NLS-2$ - + "class=" + propertySource.getClass()); //$NON-NLS-1$ - } - } - } + /** + * @param args + * - + */ + public static void main(String[] args) { + SpringApplication springApplication = new SpringApplication(Application.class); + ApplicationContext ctx = springApplication.run(args); + context = ctx; + log.debug("Let's inspect the beans provided by Spring Boot:"); //$NON-NLS-1$ + String[] beanNames = ctx.getBeanDefinitionNames(); + Arrays.sort(beanNames); + for (String beanName : beanNames) { + log.debug(beanName); + } - + log.debug("Let's inspect the profiles provided by Spring Boot:"); //$NON-NLS-1$ + profiles = ctx.getEnvironment().getActiveProfiles(); + for (int i = 0; i < profiles.length; i++) + log.debug("profile****=" + profiles[i]); //$NON-NLS-1$ - /** - * @param filter - - * @return - - */ - @Bean - public FilterRegistrationBean registration(AuthenticationFilter filter) - { - FilterRegistrationBean registration = new FilterRegistrationBean(filter); - registration.setEnabled(false); - return registration; - } + log.info("Let's inspect the properties provided by Spring Boot:"); //$NON-NLS-1$ + MutablePropertySources propertySources = ((StandardServletEnvironment) ctx.getEnvironment()) + .getPropertySources(); + Iterator> iterator = propertySources.iterator(); + while (iterator.hasNext()) { + Object propertySourceObject = iterator.next(); + if (propertySourceObject instanceof org.springframework.core.env.PropertySource) { + org.springframework.core.env.PropertySource propertySource = (org.springframework.core.env.PropertySource) propertySourceObject; + log.info("propertySource=" + propertySource.getName() + " values=" + propertySource.getSource() //$NON-NLS-1$ //$NON-NLS-2$ + + "class=" + propertySource.getClass()); //$NON-NLS-1$ + } + } + } - /** - * @param filter - - * @return - - */ - @Bean - public FilterRegistrationBean registration2(OAuth2AuthenticationProcessingFilter filter) - { - FilterRegistrationBean registration = new FilterRegistrationBean(filter); - registration.setEnabled(false); - return registration; - } - - /** - * @return - - */ - @Bean - public Docket documentation() - { - return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(paths()) - .build().pathMapping("/") //$NON-NLS-1$ - .apiInfo(metadata()); - } + /** + * @param filter + * - + * @return - + */ + @Bean + public FilterRegistrationBean registration(AuthenticationFilter filter) { + FilterRegistrationBean registration = new FilterRegistrationBean(filter); + registration.setEnabled(false); + return registration; + } - /** - * - * @return - - */ + /** + * @param filter + * - + * @return - + */ + @Bean + public FilterRegistrationBean registration2(OAuth2AuthenticationProcessingFilter filter) { + FilterRegistrationBean registration = new FilterRegistrationBean(filter); + registration.setEnabled(false); + return registration; + } - @SuppressWarnings("unchecked") - private Predicate paths() - { - return or( - regex("/device.*")); //$NON-NLS-1$ - - } + /** + * @return - + */ + @Bean + public Docket documentation() { + return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(paths()) + .build().pathMapping("/") //$NON-NLS-1$ + .apiInfo(metadata()); + } - /** - * @return - - */ - @Bean - UiConfiguration uiConfig() - { - return new UiConfiguration("validatorUrl", // url //$NON-NLS-1$ - "none", // docExpansion => none | list //$NON-NLS-1$ - "alpha", // apiSorter => alpha //$NON-NLS-1$ - "schema", // defaultModelRendering => schema //$NON-NLS-1$ - UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, true, // enableJsonEditor - // => - // true - // | - // false - true); // showRequestHeaders => true | false - } + /** + * + * @return - + */ - /** - * Ensure the Tomcat container comes up, not the Jetty one. - * - * @return - the factory - */ - @Bean - public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() - { - return new TomcatEmbeddedServletContainerFactory(); - } + @SuppressWarnings("unchecked") + private Predicate paths() { + return or(regex("/device.*")); //$NON-NLS-1$ - private ApiInfo metadata() - { - return new ApiInfoBuilder().title("Kit Service") //$NON-NLS-1$ - .description("Kit Service") //$NON-NLS-1$ - .version("1.1.6") //$NON-NLS-1$ - .build(); - } + } - /** - * @param request - - * @param name - - * @param model - - * @return - - */ - @RequestMapping("/") - public String greetings(HttpServletRequest request ,@RequestParam(value = "name", required = false, defaultValue = "Predix") String name, - Model model) - { StringBuffer requesturi = request.getRequestURL(); - String applicationURl = requesturi.toString().replaceAll("http", "https");//$NON-NLS-1$ //$NON-NLS-2$ - if(checkProfile("local")) { //$NON-NLS-1$ - applicationURl = requesturi.toString(); - } - - model.addAttribute("api",applicationURl.toString()+"api");//$NON-NLS-1$ //$NON-NLS-2$ - model.addAttribute("health",applicationURl.toString()+"health");//$NON-NLS-1$ //$NON-NLS-2$ - model.addAttribute("docs",this.docsUrl);//$NON-NLS-1$ - return "index"; //$NON-NLS-1$ - } + /** + * @return - + */ + @Bean + UiConfiguration uiConfig() { + return new UiConfiguration("validatorUrl", // url //$NON-NLS-1$ + "none", // docExpansion => none | list //$NON-NLS-1$ + "alpha", // apiSorter => alpha //$NON-NLS-1$ + "schema", // defaultModelRendering => schema //$NON-NLS-1$ + UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, true, // enableJsonEditor + // => + // true + // | + // false + true); // showRequestHeaders => true | false + } - /** - * @param profile - local - * @return - - */ - private boolean checkProfile(String profile) - { - return Arrays.asList(profiles).contains(profile); - } + /** + * Ensure the Tomcat container comes up, not the Jetty one. + * + * @return - the factory + */ + @Bean + public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() { + return new TomcatEmbeddedServletContainerFactory(); + } + private ApiInfo metadata() { + return new ApiInfoBuilder().title("Kit Service") //$NON-NLS-1$ + .description("Kit Service") //$NON-NLS-1$ + .version("1.1.6") //$NON-NLS-1$ + .build(); + } + /** + * @param request + * - + * @param name + * - + * @param model + * - + * @return - + */ + @RequestMapping("/") + public String greetings(HttpServletRequest request, + @RequestParam(value = "name", required = false, defaultValue = "Predix") String name, Model model) { + StringBuffer requesturi = request.getRequestURL(); + String applicationURl = requesturi.toString().replaceAll("http", "https");//$NON-NLS-1$ //$NON-NLS-2$ + if (checkProfile("local")) { //$NON-NLS-1$ + applicationURl = requesturi.toString(); + } - /** - * - * @param request - * - HttpServletRequest - * @param response - * - HttpServletResponse - * @return - Model View - * @throws Exception - * - Exception - */ - @RequestMapping("/docs") - protected ModelAndView docs(HttpServletRequest request, HttpServletResponse response) - throws Exception - { - return new ModelAndView("redirect:/javadoc/index.html"); //$NON-NLS-1$ + model.addAttribute("api", applicationURl.toString() + "api");//$NON-NLS-1$ //$NON-NLS-2$ + model.addAttribute("health", applicationURl.toString() + "health");//$NON-NLS-1$ //$NON-NLS-2$ + model.addAttribute("docs", this.docsUrl);//$NON-NLS-1$ + return "index"; //$NON-NLS-1$ + } - } - - - /** - * @param request - - * @param response - - * @throws IOException - - */ - @RequestMapping("/api") - public @ResponseBody void api(HttpServletRequest request ,HttpServletResponse response ) throws IOException - { String applicationURl = getApplicationUrl(request); - response.sendRedirect(applicationURl.replace("/api", "/swagger-ui.html")); //$NON-NLS-1$//$NON-NLS-2$ + /** + * @param profile + * - local + * @return - + */ + private boolean checkProfile(String profile) { + return Arrays.asList(profiles).contains(profile); + } - } - - /** - * - * @param request - * @return - Application URL - */ - private String getApplicationUrl (final HttpServletRequest request){ - - String applicationURl = request.getRequestURL().toString().replaceAll("http", "https");//$NON-NLS-1$ //$NON-NLS-2$ - if(checkProfile("local")) { //$NON-NLS-1$ - applicationURl = request.getRequestURL().toString(); // localhost support for http - } - return applicationURl; - } - + /** + * + * @param request + * - HttpServletRequest + * @param response + * - HttpServletResponse + * @return - Model View + */ + @RequestMapping("/docs") + protected ModelAndView docs(HttpServletRequest request, HttpServletResponse response) { + return new ModelAndView("redirect:/javadoc/index.html"); //$NON-NLS-1$ + + } + + /** + * @param request + * - + * @param response + * - + * @throws IOException + * - + */ + @RequestMapping("/api") + public @ResponseBody void api(HttpServletRequest request, HttpServletResponse response) throws IOException { + String applicationURl = getApplicationUrl(request); + response.sendRedirect(applicationURl.replace("/api", "/swagger-ui.html")); //$NON-NLS-1$//$NON-NLS-2$ + + } + + /** + * + * @param request + * @return - Application URL + */ + private String getApplicationUrl(final HttpServletRequest request) { + + String applicationURl = request.getRequestURL().toString().replaceAll("http", "https");//$NON-NLS-1$ //$NON-NLS-2$ + if (checkProfile("local")) { //$NON-NLS-1$ + applicationURl = request.getRequestURL().toString(); // localhost + // support + // for http + } + return applicationURl; + } } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/boot/AuthenticationFilter.java b/src/main/java/com/ge/predix/solsvc/kitservice/boot/AuthenticationFilter.java index 208a03c..2965f52 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/boot/AuthenticationFilter.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/boot/AuthenticationFilter.java @@ -37,122 +37,114 @@ * * @author 212421693 - */ -public class AuthenticationFilter - implements Filter -{ - private String tokenScope = "application-read"; //$NON-NLS-1$ - - /** - * @return the tokenScope - */ - public String getTokenScope() - { - return this.tokenScope; - } - - /** - * @param tokenScope the tokenScope to set - */ - public void setTokenScope(String tokenScope) - { - this.tokenScope = tokenScope; - } - - private static final String SECURITY_TOKEN_HEADER = "Authorization"; //$NON-NLS-1$ - private static final String authorizationSchema = "Bearer"; //$NON-NLS-1$ - - /* - * (non-Javadoc) - * @see javax.servlet.Filter#destroy() - */ - @Override - public void destroy() - { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) - */ - @Override - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) - throws IOException, ServletException - { - HttpServletRequest request = (HttpServletRequest) req; - HttpServletResponse response = (HttpServletResponse) res; - String stringToken = request.getHeader(SECURITY_TOKEN_HEADER); - - if ( StringUtils.isEmpty(stringToken) ) - { - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - throw new InsufficientAuthenticationException("Authorization header not found"); //$NON-NLS-1$ - } - - if ( !StringUtils.startsWithIgnoreCase(stringToken, authorizationSchema) ) - { - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - throw new InsufficientAuthenticationException("Authorization schema " + authorizationSchema + " not found"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - stringToken = stringToken.trim().substring(authorizationSchema.length()); - - Jwt accessToken = JwtHelper.decode(stringToken); - Map claims = JsonUtils.readValue(accessToken.getClaims(), - new TypeReference>() - {// - }); - if ( claims == null ) - { - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - throw new InsufficientAuthenticationException( - "Authorization header does not have the required scope to access the resource claims are not set"); //$NON-NLS-1$ - } - Set scopes = new HashSet<>(); - if ( claims.containsKey("scope") ) //$NON-NLS-1$ - { - @SuppressWarnings("unchecked") - Collection values = (Collection) claims.get("scope");//$NON-NLS-1$ - scopes.addAll(values); - } - // check for the right scope - Boolean foundScope = Boolean.FALSE; - for (String scope : scopes) - { - if ( org.apache.commons.lang.StringUtils.equalsIgnoreCase(scope, this.tokenScope) ) - { - foundScope = Boolean.TRUE; - } - - } - - request.setAttribute("userToken", accessToken); //$NON-NLS-1$ - request.setAttribute("isAdmin", foundScope); //$NON-NLS-1$ - - /* if ( !foundScope ) - { - - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - throw new InsufficientAuthenticationException( - "Authorization header does not have the required scope to access the resource"); //$NON-NLS-1$ - }*/ - // setting security Context - - chain.doFilter(req, res); - - } - - /* - * (non-Javadoc) - * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) - */ - @Override - public void init(FilterConfig arg0) - throws ServletException - { - // TODO Auto-generated method stub - - } +public class AuthenticationFilter implements Filter { + private String tokenScope = "application-read"; //$NON-NLS-1$ + + /** + * @return the tokenScope + */ + public String getTokenScope() { + return this.tokenScope; + } + + /** + * @param tokenScope + * the tokenScope to set + */ + public void setTokenScope(String tokenScope) { + this.tokenScope = tokenScope; + } + + private static final String SECURITY_TOKEN_HEADER = "Authorization"; //$NON-NLS-1$ + private static final String authorizationSchema = "Bearer"; //$NON-NLS-1$ + + /* + * (non-Javadoc) + * + * @see javax.servlet.Filter#destroy() + */ + @Override + public void destroy() { + // TODO Auto-generated method stub + + } + + /* + * (non-Javadoc) + * + * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, + * javax.servlet.ServletResponse, javax.servlet.FilterChain) + */ + @Override + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest request = (HttpServletRequest) req; + HttpServletResponse response = (HttpServletResponse) res; + String stringToken = request.getHeader(SECURITY_TOKEN_HEADER); + + if (StringUtils.isEmpty(stringToken)) { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + throw new InsufficientAuthenticationException("Authorization header not found"); //$NON-NLS-1$ + } + + if (!StringUtils.startsWithIgnoreCase(stringToken, authorizationSchema)) { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + throw new InsufficientAuthenticationException("Authorization schema " + authorizationSchema + " not found"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + stringToken = stringToken.trim().substring(authorizationSchema.length()); + + Jwt accessToken = JwtHelper.decode(stringToken); + Map claims = JsonUtils.readValue(accessToken.getClaims(), + new TypeReference>() {// + }); + if (claims == null) { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + throw new InsufficientAuthenticationException( + "Authorization header does not have the required scope to access the resource claims are not set"); //$NON-NLS-1$ + } + Set scopes = new HashSet<>(); + if (claims.containsKey("scope")) //$NON-NLS-1$ + { + @SuppressWarnings("unchecked") + Collection values = (Collection) claims.get("scope");//$NON-NLS-1$ + scopes.addAll(values); + } + // check for the right scope + Boolean foundScope = Boolean.FALSE; + for (String scope : scopes) { + if (org.apache.commons.lang.StringUtils.equalsIgnoreCase(scope, this.tokenScope)) { + foundScope = Boolean.TRUE; + } + + } + + request.setAttribute("userToken", accessToken); //$NON-NLS-1$ + request.setAttribute("isAdmin", foundScope); //$NON-NLS-1$ + + /* + * if ( !foundScope ) { + * + * response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); throw new + * InsufficientAuthenticationException( + * "Authorization header does not have the required scope to access the resource" + * ); //$NON-NLS-1$ } + */ + // setting security Context + + chain.doFilter(req, res); + + } + + /* + * (non-Javadoc) + * + * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) + */ + @Override + public void init(FilterConfig arg0) throws ServletException { + // TODO Auto-generated method stub + + } } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/boot/ErrorResponseController.java b/src/main/java/com/ge/predix/solsvc/kitservice/boot/ErrorResponseController.java index 6b3911a..00cdd8d 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/boot/ErrorResponseController.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/boot/ErrorResponseController.java @@ -29,39 +29,37 @@ * @author 212421693 - */ @RestController -public class ErrorResponseController - implements ErrorController -{ - private static final String PATH = "/error"; //$NON-NLS-1$ +public class ErrorResponseController implements ErrorController { + private static final String PATH = "/error"; //$NON-NLS-1$ - @Value("${debug:false}") - private boolean debug; + @Value("${debug:false}") + private boolean debug; - @Autowired - private ErrorAttributes errorAttributes; + @Autowired + private ErrorAttributes errorAttributes; - /** - * @param request - - * @param response - - * @return - - */ - @RequestMapping(value = PATH) - EventError 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. - return new EventError(response.getStatus(), getErrorAttributes(request, this.debug)); - } + /** + * @param request + * - + * @param response + * - + * @return - + */ + @RequestMapping(value = PATH) + EventError 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. + return new EventError(response.getStatus(), getErrorAttributes(request, this.debug)); + } - @Override - public String getErrorPath() - { - return PATH; - } + @Override + public String getErrorPath() { + return PATH; + } - private Map getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) - { - RequestAttributes requestAttributes = new ServletRequestAttributes(request); - return this.errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace); - } + private Map getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { + RequestAttributes requestAttributes = new ServletRequestAttributes(request); + return this.errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace); + } } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/boot/EventError.java b/src/main/java/com/ge/predix/solsvc/kitservice/boot/EventError.java index b6d84ac..03beba8 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/boot/EventError.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/boot/EventError.java @@ -14,120 +14,109 @@ import org.springframework.util.StringUtils; - - /** * * @author 212421693 - */ -public class EventError -{ - /** - * status - */ - Integer status; - /** - * error - */ - String error; - - /** - * message - */ - String message; - /** - * timeStamp - */ - String timeStamp; - - /** - * code - */ - String code; - - /** - * @param status - * - - * @param errorAttributes - * - - */ - public EventError(int status, Map errorAttributes) - { - this.status = status; - this.error = (String) errorAttributes.get("error"); //$NON-NLS-1$ - this.message = (String) errorAttributes.get("message"); //$NON-NLS-1$ - this.code = (String) errorAttributes.get("code"); //$NON-NLS-1$ - if(! StringUtils.isEmpty(errorAttributes.get("timestamp"))) {//$NON-NLS-1$ - this.timeStamp = errorAttributes.get("timestamp").toString(); //$NON-NLS-1$ - } - - } - - /** - * @return the status - */ - public Integer getStatus() - { - return this.status; - } - - /** - * @param status the status to set - */ - public void setStatus(Integer status) - { - this.status = status; - } - - /** - * @return the error - */ - public String getError() - { - return this.error; - } - - /** - * @param error the error to set - */ - public void setError(String error) - { - this.error = error; - } - - /** - * @return the message - */ - public String getMessage() - { - return this.message; - } - - /** - * @param message the message to set - */ - public void setMessage(String message) - { - this.message = message; - } - - /** - * @return the timeStamp - */ - public String getTimeStamp() - { - return this.timeStamp; - } - - /** - * @param timeStamp the timeStamp to set - */ - public void setTimeStamp(String timeStamp) - { - this.timeStamp = timeStamp; - } - - - - +public class EventError { + /** + * status + */ + Integer status; + /** + * error + */ + String error; + + /** + * message + */ + String message; + /** + * timeStamp + */ + String timeStamp; + + /** + * code + */ + String code; + + /** + * @param status + * - + * @param errorAttributes + * - + */ + public EventError(int status, Map errorAttributes) { + this.status = status; + this.error = (String) errorAttributes.get("error"); //$NON-NLS-1$ + this.message = (String) errorAttributes.get("message"); //$NON-NLS-1$ + this.code = (String) errorAttributes.get("code"); //$NON-NLS-1$ + if (!StringUtils.isEmpty(errorAttributes.get("timestamp"))) {//$NON-NLS-1$ + this.timeStamp = errorAttributes.get("timestamp").toString(); //$NON-NLS-1$ + } + + } + + /** + * @return the status + */ + public Integer getStatus() { + return this.status; + } + + /** + * @param status + * the status to set + */ + public void setStatus(Integer status) { + this.status = status; + } + + /** + * @return the error + */ + public String getError() { + return this.error; + } + + /** + * @param error + * the error to set + */ + public void setError(String error) { + this.error = error; + } + + /** + * @return the message + */ + public String getMessage() { + return this.message; + } + + /** + * @param message + * the message to set + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * @return the timeStamp + */ + public String getTimeStamp() { + return this.timeStamp; + } + + /** + * @param timeStamp + * the timeStamp to set + */ + public void setTimeStamp(String timeStamp) { + this.timeStamp = timeStamp; + } + } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/boot/SwaggerConfiguration.java b/src/main/java/com/ge/predix/solsvc/kitservice/boot/SwaggerConfiguration.java index 5ab6226..af761f3 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/boot/SwaggerConfiguration.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/boot/SwaggerConfiguration.java @@ -20,21 +20,18 @@ * @author 212421693 - */ @Configuration -public class SwaggerConfiguration extends WebMvcConfigurerAdapter -{ - @Override - public void addViewControllers(ViewControllerRegistry registry) - { - registry.addRedirectViewController("/api/v2/api-docs", "/v2/api-docs"); //$NON-NLS-1$ //$NON-NLS-2$ - registry.addRedirectViewController("/api/configuration/ui", "/configuration/ui"); //$NON-NLS-1$ //$NON-NLS-2$ - registry.addRedirectViewController("/api/configuration/security", "/configuration/security"); //$NON-NLS-1$ //$NON-NLS-2$ - registry.addRedirectViewController("/api/swagger-resources", "/swagger-resources"); //$NON-NLS-1$ //$NON-NLS-2$ - - } +public class SwaggerConfiguration extends WebMvcConfigurerAdapter { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addRedirectViewController("/api/v2/api-docs", "/v2/api-docs"); //$NON-NLS-1$ //$NON-NLS-2$ + registry.addRedirectViewController("/api/configuration/ui", "/configuration/ui"); //$NON-NLS-1$ //$NON-NLS-2$ + registry.addRedirectViewController("/api/configuration/security", "/configuration/security"); //$NON-NLS-1$ //$NON-NLS-2$ + registry.addRedirectViewController("/api/swagger-resources", "/swagger-resources"); //$NON-NLS-1$ //$NON-NLS-2$ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) - { - registry.addResourceHandler("/api/**").addResourceLocations("classpath:/META-INF/resources/"); //$NON-NLS-1$ //$NON-NLS-2$ - } + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/api/**").addResourceLocations("classpath:/META-INF/resources/"); //$NON-NLS-1$ //$NON-NLS-2$ + } } \ No newline at end of file diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/boot/utils/CSVWriter.java b/src/main/java/com/ge/predix/solsvc/kitservice/boot/utils/CSVWriter.java index 7c8f076..7a721d8 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/boot/utils/CSVWriter.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/boot/utils/CSVWriter.java @@ -31,166 +31,171 @@ */ @Component public class CSVWriter { - - + @Autowired - private - ResourceLoader resourceLoader; - + private ResourceLoader resourceLoader; + /** - * Free marker Configuration + * Free marker Configuration */ Configuration cfg = null; - - + /** - * - + * - */ @PostConstruct public void activate() { - - // Create your Configuration instance, and specify if up to what FreeMarker - // version (here 2.3.25) do you want to apply the fixes that are not 100% - // backward-compatible. See the Configuration JavaDoc for details. - this.cfg = new Configuration(Configuration.VERSION_2_3_25); - - // Specify the source where the template files come from. Here I set a - // plain directory for it, but non-file-system sources are possible too: - Resource resource = this.resourceLoader.getResource("classpath:export"); //$NON-NLS-1$ - try { - File dbAsFile = resource.getFile(); - - this.cfg.setDirectoryForTemplateLoading(dbAsFile); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - // Set the preferred charset template files are stored in. UTF-8 is - // a good choice in most applications: - this.cfg.setDefaultEncoding("UTF-8"); //$NON-NLS-1$ - - // Sets how errors will appear. - // During web page *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER is better. - this.cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); - - // Don't log exceptions inside FreeMarker that it will thrown at you anyway: - this.cfg.setLogTemplateExceptions(false); - - this.cfg.setDateTimeFormat("MM/dd/yyyy hh:mm:ss a"); //$NON-NLS-1$ - + + // Create your Configuration instance, and specify if up to what + // FreeMarker + // version (here 2.3.25) do you want to apply the fixes that are not + // 100% + // backward-compatible. See the Configuration JavaDoc for details. + this.cfg = new Configuration(Configuration.VERSION_2_3_25); + + // Specify the source where the template files come from. Here I set a + // plain directory for it, but non-file-system sources are possible too: + Resource resource = this.resourceLoader.getResource("classpath:export"); //$NON-NLS-1$ + try { + File dbAsFile = resource.getFile(); + + this.cfg.setDirectoryForTemplateLoading(dbAsFile); + } catch (IOException e) { + throw new RuntimeException(e); + } + + // Set the preferred charset template files are stored in. UTF-8 is + // a good choice in most applications: + this.cfg.setDefaultEncoding("UTF-8"); //$NON-NLS-1$ + + // Sets how errors will appear. + // During web page *development* + // TemplateExceptionHandler.HTML_DEBUG_HANDLER is better. + this.cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); + + // Don't log exceptions inside FreeMarker that it will thrown at you + // anyway: + this.cfg.setLogTemplateExceptions(false); + + this.cfg.setDateTimeFormat("MM/dd/yyyy hh:mm:ss a"); //$NON-NLS-1$ + } + /** - * @param device - + * @param device + * - * @return - - * @throws IOException - + * @throws IOException + * - */ public String getAssetCSV(RegisterDevice device) { Map root = new HashMap<>(); List devices = new ArrayList(); devices.add(device); root.put("devices", devices); //$NON-NLS-1$ - + StringWriter deviceWriter = new StringWriter(); try { Template temp = this.cfg.getTemplate("export_asset.csv"); //$NON-NLS-1$ temp.process(root, deviceWriter); } catch (IOException | TemplateException e) { - throw new RuntimeException("Exception when exporting Asset",e); //$NON-NLS-1$ + throw new RuntimeException("Exception when exporting Asset", e); //$NON-NLS-1$ } StringWriter tagWriter = new StringWriter(); try { Template temp = this.cfg.getTemplate("export_assettag.csv"); //$NON-NLS-1$ temp.process(root, tagWriter); } catch (IOException | TemplateException e) { - throw new RuntimeException("Exception when exporting Asset",e); //$NON-NLS-1$ + throw new RuntimeException("Exception when exporting Asset", e); //$NON-NLS-1$ } - + StringWriter locationWriter = new StringWriter(); try { Template temp = this.cfg.getTemplate("export_asset_location.csv"); //$NON-NLS-1$ temp.process(root, locationWriter); } catch (IOException | TemplateException e) { - throw new RuntimeException("Exception when exporting Asset Locations",e); //$NON-NLS-1$ + throw new RuntimeException("Exception when exporting Asset Locations", e); //$NON-NLS-1$ } - - String zipFileName = device.getDeviceName()+"_Device.zip"; //$NON-NLS-1$ - try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFileName));){ - - zos.putNextEntry(new ZipEntry(device.getDeviceAddress()+"_Device.csv")); //$NON-NLS-1$ + + String zipFileName = device.getDeviceName() + "_Device.zip"; //$NON-NLS-1$ + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFileName));) { + + zos.putNextEntry(new ZipEntry(device.getDeviceAddress() + "_Device.csv")); //$NON-NLS-1$ byte[] data = deviceWriter.toString().getBytes(); zos.write(data, 0, data.length); zos.closeEntry(); - - zos.putNextEntry(new ZipEntry(device.getDeviceAddress()+"_DeviceTag.csv")); //$NON-NLS-1$ + + zos.putNextEntry(new ZipEntry(device.getDeviceAddress() + "_DeviceTag.csv")); //$NON-NLS-1$ data = tagWriter.toString().getBytes(); zos.write(data, 0, data.length); zos.closeEntry(); - - zos.putNextEntry(new ZipEntry(device.getDeviceAddress()+"_Airport.csv")); //$NON-NLS-1$ + + zos.putNextEntry(new ZipEntry(device.getDeviceAddress() + "_Airport.csv")); //$NON-NLS-1$ data = locationWriter.toString().getBytes(); zos.write(data, 0, data.length); zos.closeEntry(); - + } catch (IOException e) { - throw new RuntimeException("Exception when creating Zip file",e); //$NON-NLS-1$ + throw new RuntimeException("Exception when creating Zip file", e); //$NON-NLS-1$ } return zipFileName; } - + /** - * @param devices - + * @param devices + * - * @return - - * @throws IOException - + * @throws IOException + * - */ public String getAssetCSV(List devices) { Map root = new HashMap<>(); - + root.put("devices", devices); //$NON-NLS-1$ - + StringWriter deviceWriter = new StringWriter(); try { Template temp = this.cfg.getTemplate("export_asset.csv"); //$NON-NLS-1$ temp.process(root, deviceWriter); } catch (IOException | TemplateException e) { - throw new RuntimeException("Exception when exporting Asset",e); //$NON-NLS-1$ + throw new RuntimeException("Exception when exporting Asset", e); //$NON-NLS-1$ } StringWriter tagWriter = new StringWriter(); try { Template temp = this.cfg.getTemplate("export_assettag.csv"); //$NON-NLS-1$ temp.process(root, tagWriter); } catch (IOException | TemplateException e) { - throw new RuntimeException("Exception when exporting Asset",e); //$NON-NLS-1$ + throw new RuntimeException("Exception when exporting Asset", e); //$NON-NLS-1$ } - + StringWriter locationWriter = new StringWriter(); try { Template temp = this.cfg.getTemplate("export_asset_location.csv"); //$NON-NLS-1$ temp.process(root, locationWriter); } catch (IOException | TemplateException e) { - throw new RuntimeException("Exception when exporting Asset Locations",e); //$NON-NLS-1$ + throw new RuntimeException("Exception when exporting Asset Locations", e); //$NON-NLS-1$ } - + String zipFileName = "Devices.zip"; //$NON-NLS-1$ - try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFileName));){ - + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFileName));) { + zos.putNextEntry(new ZipEntry("Device.csv")); //$NON-NLS-1$ byte[] data = deviceWriter.toString().getBytes(); zos.write(data, 0, data.length); zos.closeEntry(); - + zos.putNextEntry(new ZipEntry("DeviceTag.csv")); //$NON-NLS-1$ data = tagWriter.toString().getBytes(); zos.write(data, 0, data.length); zos.closeEntry(); - + zos.putNextEntry(new ZipEntry("Airport.csv")); //$NON-NLS-1$ data = locationWriter.toString().getBytes(); zos.write(data, 0, data.length); zos.closeEntry(); - + } catch (IOException e) { - throw new RuntimeException("Exception when creating Zip file",e); //$NON-NLS-1$ + throw new RuntimeException("Exception when creating Zip file", e); //$NON-NLS-1$ } return zipFileName; } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/boot/utils/FdhUtils.java b/src/main/java/com/ge/predix/solsvc/kitservice/boot/utils/FdhUtils.java index 344ceae..33e52b9 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/boot/utils/FdhUtils.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/boot/utils/FdhUtils.java @@ -7,7 +7,7 @@ * with the terms and conditions stipulated in the agreement/contract * under which the software has been supplied. */ - + package com.ge.predix.solsvc.kitservice.boot.utils; import java.io.UnsupportedEncodingException; @@ -30,216 +30,226 @@ * * @author 212421693 - */ -public class FdhUtils -{ - - private static final int DEFAULT_ASSET_PAGESIZE = 1000; - - - /** - * - * @param device - - * @param group - - * @param userGroup - - * @return - - */ - public static PutFieldDataRequest createRegisterPutRequest(String device, String group, String userGroup) - { - - - // Request - PutFieldDataRequest putFieldDataRequest = new PutFieldDataRequest(); - putFieldDataRequest.setCorrelationId("string"); //$NON-NLS-1$ - putFieldDataRequest.getPutFieldDataCriteria().add( getFieldCriteria(device)); - if(StringUtils.isNotEmpty(group)) - putFieldDataRequest.getPutFieldDataCriteria().add( getFieldCriteria(group)); - if(StringUtils.isNotEmpty(userGroup)) - putFieldDataRequest.getPutFieldDataCriteria().add( getFieldCriteria(userGroup)); - - return putFieldDataRequest; - } - - - /** - * @param device - * @return - - */ - private static PutFieldDataCriteria getFieldCriteria(String dataString) - { - FieldData fieldData = new FieldData(); - Field field = new Field(); - FieldIdentifier fieldIdentifier = new FieldIdentifier(); - field.setFieldIdentifier(fieldIdentifier); - fieldData.getField().add(field); - - //device - PredixString data = new PredixString(); - data.setString(dataString); - fieldData.setData(data); - - // Criteria - PutFieldDataCriteria fieldDataCriteria = new PutFieldDataCriteria(); - fieldDataCriteria.setFieldData(fieldData); - return fieldDataCriteria; - } - - - /** - * @param filterFieldValue - - * @param expectedDataType - - * @param deviceIdentifier - - * @param string - - * @param userId - - * @param deviceAddress - - * @return - - * @throws UnsupportedEncodingException - - */ - public static GetFieldDataRequest createGetUserDeviceRequest(String filterFieldValue, String expectedDataType, String userId, - String deviceAddress) throws UnsupportedEncodingException - { - GetFieldDataRequest getFieldDataRequest = new GetFieldDataRequest(); - - FieldDataCriteria fieldDataCriteria = new FieldDataCriteria(); - - // SELECT - FieldSelection fieldSelection = new FieldSelection(); - FieldIdentifier fieldIdentifier = new FieldIdentifier(); - fieldIdentifier.setId("/PredixString"); //$NON-NLS-1$ default needed by the system - fieldSelection.setFieldIdentifier(fieldIdentifier); - fieldSelection.setExpectedDataType(expectedDataType); - - // FILTER - AssetFilter assetFilter = new AssetFilter(); - assetFilter.setUri(filterFieldValue); - - if(StringUtils.isEmpty(userId) && !StringUtils.isEmpty(deviceAddress)) { - assetFilter.setFilterString("deviceAddress="+deviceAddress); //$NON-NLS-1$ - } - else if(StringUtils.isEmpty(deviceAddress)) { - String encodedUrl = URLEncoder.encode("uaaUsers="+userId+" getDevices(HttpServletRequest request,@SuppressWarnings({ - "javadoc" - }) @RequestHeader("Authorization") String authorization) - { - List devices = null; - String userId = getUserId(request); - Boolean isAdmin = (Boolean) request.getAttribute("isAdmin"); //$NON-NLS-1$ - - if(isAdmin) { - devices = this.getDeviceManager().getAllAdminDevices(); - }else { - devices = this.getDeviceManager().getDevices(userId); - } - String contentType = request.getHeader("Content-Type"); //$NON-NLS-1$ - - if (contentType != null && MediaType.APPLICATION_OCTET_STREAM_VALUE.equals(contentType)) { - String fileName = this.csvWriter.getAssetCSV(devices); - File file = new File(fileName); - InputStreamResource resource; +public class KitController { + + private static final Logger log = LoggerFactory.getLogger(KitController.class); + private static int DEVICE_REGISTRATION_ERROR = 1001; + private static int DEVICE_EXPIRY_ERROR = 1002; + private static int DEVICE_RESET_ERROR = 1003; + @Autowired + private DeviceManager deviceManager; + + @Autowired + private CSVWriter csvWriter; + + /** + * + */ + public KitController() { + super(); + } + + /** + * Sample End point which returns a Welcome Message + * + * @param request + * - + * @param authorization + * - + * + * @param echo + * - the string to echo back + * @return - + */ + @SuppressWarnings({ "resource" }) + @RequestMapping(value = "/device", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, + MediaType.APPLICATION_XHTML_XML_VALUE }) + public ResponseEntity getDevices(HttpServletRequest request, + @RequestHeader("Authorization") String authorization) { + List devices = null; + String userId = getUserId(request); + Boolean isAdmin = (Boolean) request.getAttribute("isAdmin"); //$NON-NLS-1$ + + if (isAdmin) { + devices = this.deviceManager.getAllAdminDevices(); + } else { + devices = this.deviceManager.getDevices(userId); + } + String contentType = request.getHeader("Content-Type"); //$NON-NLS-1$ + + if (contentType != null && MediaType.APPLICATION_OCTET_STREAM_VALUE.equals(contentType)) { + String fileName = this.csvWriter.getAssetCSV(devices); + File file = new File(fileName); + InputStreamResource resource; try { resource = new InputStreamResource(new FileInputStream(file)); - return ResponseEntity.ok() - .contentLength(file.length()) - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .header("Content-Disposition", "attachment;filename="+fileName) //$NON-NLS-1$ //$NON-NLS-2$ - .body(resource); + return ResponseEntity.ok().contentLength(file.length()).contentType(MediaType.APPLICATION_OCTET_STREAM) + .header("Content-Disposition", "attachment;filename=" + fileName) //$NON-NLS-1$ //$NON-NLS-2$ + .body(resource); } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + throw new RuntimeException(e); } - return null; - } - return new ResponseEntity>(devices, HttpStatus.OK); - } - - /** - * Method that registers a device - * - * @param device - - * @param request - - * @param result - - * @return - - */ - @SuppressWarnings("unused") + } + return new ResponseEntity>(devices, HttpStatus.OK); + } + + /** + * Method that registers a device + * + * @param device + * - + * @param request + * - + * @param result + * - + * @param authorization + * - + * @return - + */ @RequestMapping(value = "/device/register", method = RequestMethod.POST) - public ResponseEntity registerDevice(@RequestBody RegisterDevice device, HttpServletRequest request, - BindingResult result,@SuppressWarnings("javadoc") @RequestHeader("Authorization") String authorization) - { - String userId = getUserId(request); - log.info("Calling registerKit for user " + userId); //$NON-NLS-1$ - - - // validation - RegisterDeviceValidation validation = new RegisterDeviceValidation(); - validation.validate(device, result); - if ( result.hasErrors() ) - { - List errors = setErrors(result.getFieldErrors(), HttpStatus.BAD_REQUEST.value()); - return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); - } - // continue to register device - // RegisterDevice originalDevice = this.getDeviceManager().getDevice("device", userId, device.getDeviceAddress());//$NON-NLS-1$ - // removing the user check adding check per deviceIdentifer - RegisterDevice originalDevice = this.getDeviceManager().getDevice("device", null, device.getDeviceAddress());//$NON-NLS-1$ - try - { - if ( originalDevice == null ) - { - // device not found. register it. - log.info("Registrating device with address " + device.getDeviceAddress()); //$NON-NLS-1$ - this.getDeviceManager().registerDevice(device,userId); - } - else - { - log.info("This is a registered device with address " + device.getDeviceAddress()); //$NON-NLS-1$ - // this try-catch to check expire - try { - // check device expire - this.getDeviceManager().checkDeviceExpiry(originalDevice); - } - catch (DeviceRegistrationError e) - { - List errors = setErrors(e, HttpStatus.BAD_REQUEST.value(),DEVICE_EXPIRY_ERROR); - return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); - } - this.getDeviceManager().updateDevice(device, originalDevice,userId); - - } - } - catch (DeviceRegistrationError e) - { - List errors = setErrors(e, HttpStatus.BAD_REQUEST.value(),DEVICE_REGISTRATION_ERROR); - return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); - } - // setting config - device.setDeviceConfig(this.getDeviceManager().getDeviceConfig()); - return new ResponseEntity(device, HttpStatus.OK); - } - - /** - * - - * - * @param list - * @param status - */ - private List setErrors(List errors, int status) - { - List eventErrors = new ArrayList(); - - if ( CollectionUtils.isNotEmpty(errors) ) - { - for (FieldError error : errors) - { - Map errorAttributes = new HashMap(); - errorAttributes.put("error", error.getField()); //$NON-NLS-1$ - errorAttributes.put("message", error.getField() + "reject for value "+error.getRejectedValue() + error.getDefaultMessage());//$NON-NLS-1$ //$NON-NLS-2$ - EventError eventError = new EventError(status, errorAttributes); - eventErrors.add(eventError); - - } - } - return eventErrors; - - } - - /** - * @param allErrors - * @param value - * @return - - */ - private List setObjectErrors(List errors, int status) - { - List eventErrors = new ArrayList(); - if ( CollectionUtils.isNotEmpty(errors) ) - { - for (ObjectError error : errors) - { - Map errorAttributes = new HashMap(); - errorAttributes.put("error", error.getObjectName()); //$NON-NLS-1$ - errorAttributes.put("message", error.getDefaultMessage());//$NON-NLS-1$ - EventError eventError = new EventError(status, errorAttributes); - eventErrors.add(eventError); - - } - } - return eventErrors; - } - - /** - * Method that updated the device - * @param deviceId - - * - * @param device - - * @param request - - * @param result - - * @param authorization - - * @return - - */ - - @RequestMapping(value = "/device/{deviceId}", method = RequestMethod.PUT) - public ResponseEntity updateRegisterDevice(@PathVariable String deviceId,@RequestBody RegisterDevice device, HttpServletRequest request, - BindingResult result, @RequestHeader("Authorization") String authorization) - { - String userId = getUserId(request); - log.info("Calling registerKit for user " + userId); //$NON-NLS-1$ - - List errors = new ArrayList(); - if(!RegisterDeviceValidation.validate(deviceId, Pattern.compile(RegisterDeviceValidation.DEVICE_NAME_PATTERN))) { - ObjectError error = new ObjectError("deviceId", "Device id should match ^[A-Za-z0-9-]*"); //$NON-NLS-1$//$NON-NLS-2$ - errors.add(error); - } - - if( RegisterDeviceValidation.DEVICE_ADDRESS_LENGTH <= deviceId.length()){ - ObjectError error = new ObjectError("deviceId", "DeviceId is limited to max 75"); //$NON-NLS-1$//$NON-NLS-2$ - errors.add(error); - } - - if ( CollectionUtils.isNotEmpty(errors)) - { - List eventErrors = setObjectErrors(errors, HttpStatus.BAD_REQUEST.value()); - return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); - } - - device.setDeviceAddress(deviceId); - - - RegisterDeviceValidation validation = new RegisterDeviceValidation(); - validation.validate(device, result); - if ( result.hasErrors() ) - { - List eventErrors = setErrors(result.getFieldErrors(), HttpStatus.BAD_REQUEST.value()); - return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); - } - // check if the device exists - RegisterDevice originalDevice = this.getDeviceManager().getDevice("device", userId, device.getDeviceAddress());//$NON-NLS-1$ - if ( originalDevice == null ) - { - // device not found. - log.info("device not found for the user " + device.getDeviceAddress()); //$NON-NLS-1$ - ObjectError error = new ObjectError("deviceAddress", "Device with not registerted"); //$NON-NLS-1$//$NON-NLS-2$ - result.addError(error); - List eventErrors = setErrors(result.getFieldErrors(), HttpStatus.BAD_REQUEST.value()); - return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); - - } - try - { - this.getDeviceManager().updateDevice(device, originalDevice,userId); - - } - catch (DeviceRegistrationError e) - { - List eventErrors = setErrors(e, HttpStatus.BAD_REQUEST.value(),DEVICE_REGISTRATION_ERROR); - return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); - } - return this.getDevice(deviceId, request, authorization); - - } - - /** - * @param e - * @param badRequest - * @return - - */ - @SuppressWarnings("unused") - private List setErrors(DeviceRegistrationError e, int status , int errorCode) - { - List eventErrors = new ArrayList(); - Map errorAttributes = new HashMap(); - errorAttributes.put("error", e.getMessage()); //$NON-NLS-1$ - errorAttributes.put("message", e.getMessage());//$NON-NLS-1$ - errorAttributes.put("code",String.valueOf(errorCode));//$NON-NLS-1$ - EventError eventError = new EventError(errorCode, errorAttributes); - eventErrors.add(eventError); - - return eventErrors; - } - - - /** - * @param request - * @return - - */ - private String getUserId(HttpServletRequest request) - { - Jwt accessToken = (Jwt) request.getAttribute("userToken"); //$NON-NLS-1$ - if ( accessToken == null ) return null; - Map claims = JsonUtils.readValue(accessToken.getClaims(), - new TypeReference>() - {// - }); - if ( claims == null ) return null; - return (String) claims.get("user_id"); //$NON-NLS-1$ - } - - /** - * Details about each Device - * - * @param deviceId - - * @param model - - * @param request - - * @param authorization - - * @param result - - * @param echo - - * @return - - */ - @SuppressWarnings("resource") + public ResponseEntity registerDevice(@RequestBody RegisterDevice device, HttpServletRequest request, + BindingResult result, @RequestHeader("Authorization") String authorization) { + String userId = getUserId(request); + log.info("Calling registerKit for user " + userId); //$NON-NLS-1$ + + // validation + RegisterDeviceValidation validation = new RegisterDeviceValidation(); + validation.validate(device, result); + if (result.hasErrors()) { + List errors = setErrors(result.getFieldErrors(), HttpStatus.BAD_REQUEST.value()); + return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); + } + // continue to register device + // RegisterDevice originalDevice = this.deviceManager.getDevice("device", userId, device.getDeviceAddress());//$NON-NLS-1$ + // removing the user check adding check per deviceIdentifer + RegisterDevice originalDevice = this.deviceManager.getDevice("device", null, device.getDeviceAddress());//$NON-NLS-1$ + try { + if (originalDevice == null) { + // device not found. register it. + log.info("Registrating device with address " + device.getDeviceAddress()); //$NON-NLS-1$ + this.deviceManager.registerDevice(device, userId); + } else { + log.info("This is a registered device with address " + device.getDeviceAddress()); //$NON-NLS-1$ + // this try-catch to check expire + try { + // check device expire + this.deviceManager.checkDeviceExpiry(originalDevice); + } catch (DeviceRegistrationError e) { + List errors = setErrors(e, HttpStatus.BAD_REQUEST.value(), DEVICE_EXPIRY_ERROR); + return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); + } + this.deviceManager.updateDevice(device, originalDevice, userId); + + } + } catch (DeviceRegistrationError e) { + List errors = setErrors(e, HttpStatus.BAD_REQUEST.value(), DEVICE_REGISTRATION_ERROR); + return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); + } + // setting config + device.setDeviceConfig(this.deviceManager.getDeviceConfig()); + return new ResponseEntity(device, HttpStatus.OK); + } + + /** + * - + * + * @param list + * @param status + */ + private List setErrors(List errors, int status) { + List eventErrors = new ArrayList(); + + if (CollectionUtils.isNotEmpty(errors)) { + for (FieldError error : errors) { + Map errorAttributes = new HashMap(); + errorAttributes.put("error", error.getField()); //$NON-NLS-1$ + errorAttributes.put("message", //$NON-NLS-1$ + error.getField() + "reject for value " + error.getRejectedValue() + error.getDefaultMessage());//$NON-NLS-1$ + EventError eventError = new EventError(status, errorAttributes); + eventErrors.add(eventError); + + } + } + return eventErrors; + + } + + /** + * @param allErrors + * @param value + * @return - + */ + private List setObjectErrors(List errors, int status) { + List eventErrors = new ArrayList(); + if (CollectionUtils.isNotEmpty(errors)) { + for (ObjectError error : errors) { + Map errorAttributes = new HashMap(); + errorAttributes.put("error", error.getObjectName()); //$NON-NLS-1$ + errorAttributes.put("message", error.getDefaultMessage());//$NON-NLS-1$ + EventError eventError = new EventError(status, errorAttributes); + eventErrors.add(eventError); + + } + } + return eventErrors; + } + + /** + * Method that updated the device + * + * @param deviceId + * - + * + * @param device + * - + * @param request + * - + * @param result + * - + * @param authorization + * - + * @return - + */ + + @RequestMapping(value = "/device/{deviceId}", method = RequestMethod.PUT) + public ResponseEntity updateRegisterDevice(@PathVariable String deviceId, @RequestBody RegisterDevice device, + HttpServletRequest request, BindingResult result, @RequestHeader("Authorization") String authorization) { + String userId = getUserId(request); + log.info("Calling registerKit for user " + userId); //$NON-NLS-1$ + + List errors = new ArrayList(); + if (!RegisterDeviceValidation.validate(deviceId, + Pattern.compile(RegisterDeviceValidation.DEVICE_NAME_PATTERN))) { + ObjectError error = new ObjectError("deviceId", "Device id should match ^[A-Za-z0-9-]*"); //$NON-NLS-1$//$NON-NLS-2$ + errors.add(error); + } + + if (RegisterDeviceValidation.DEVICE_ADDRESS_LENGTH <= deviceId.length()) { + ObjectError error = new ObjectError("deviceId", "DeviceId is limited to max 75"); //$NON-NLS-1$//$NON-NLS-2$ + errors.add(error); + } + + if (CollectionUtils.isNotEmpty(errors)) { + List eventErrors = setObjectErrors(errors, HttpStatus.BAD_REQUEST.value()); + return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); + } + + device.setDeviceAddress(deviceId); + + RegisterDeviceValidation validation = new RegisterDeviceValidation(); + validation.validate(device, result); + if (result.hasErrors()) { + List eventErrors = setErrors(result.getFieldErrors(), HttpStatus.BAD_REQUEST.value()); + return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); + } + // check if the device exists + RegisterDevice originalDevice = this.deviceManager.getDevice("device", userId, device.getDeviceAddress());//$NON-NLS-1$ + if (originalDevice == null) { + // device not found. + log.info("device not found for the user " + device.getDeviceAddress()); //$NON-NLS-1$ + ObjectError error = new ObjectError("deviceAddress", "Device with not registerted"); //$NON-NLS-1$//$NON-NLS-2$ + result.addError(error); + List eventErrors = setErrors(result.getFieldErrors(), HttpStatus.BAD_REQUEST.value()); + return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); + + } + try { + this.deviceManager.updateDevice(device, originalDevice, userId); + + } catch (DeviceRegistrationError e) { + List eventErrors = setErrors(e, HttpStatus.BAD_REQUEST.value(), DEVICE_REGISTRATION_ERROR); + return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); + } + return this.getDevice(deviceId, request, authorization); + + } + + /** + * @param e + * @param badRequest + * @return - + */ + @SuppressWarnings("unused") + private List setErrors(DeviceRegistrationError e, int status, int errorCode) { + List eventErrors = new ArrayList(); + Map errorAttributes = new HashMap(); + errorAttributes.put("error", e.getMessage()); //$NON-NLS-1$ + errorAttributes.put("message", e.getMessage());//$NON-NLS-1$ + errorAttributes.put("code", String.valueOf(errorCode));//$NON-NLS-1$ + EventError eventError = new EventError(errorCode, errorAttributes); + eventErrors.add(eventError); + + return eventErrors; + } + + /** + * @param request + * @return - + */ + private String getUserId(HttpServletRequest request) { + Jwt accessToken = (Jwt) request.getAttribute("userToken"); //$NON-NLS-1$ + return this.deviceManager.getUserId(accessToken); + } + + + + /** + * Details about each Device + * + * @param deviceId + * - + * @param model + * - + * @param request + * - + * @param authorization + * - + * @param result + * - + * @param echo + * - + * @return - + */ @RequestMapping(value = "/device/{deviceId}", method = RequestMethod.GET) - public ResponseEntity getDevice(@PathVariable String deviceId, HttpServletRequest request, - @RequestHeader("Authorization") String authorization) - { - String userId = getUserId(request); - - List errors = new ArrayList(); - if(!RegisterDeviceValidation.validate(deviceId, Pattern.compile(RegisterDeviceValidation.DEVICE_NAME_PATTERN))) { - ObjectError error = new ObjectError("deviceId", "Device id should match ^[A-Za-z0-9-]*"); //$NON-NLS-1$//$NON-NLS-2$ - errors.add(error); - } - - if( RegisterDeviceValidation.DEVICE_ADDRESS_LENGTH <= deviceId.length()){ - ObjectError error = new ObjectError("deviceId", "DeviceId is limited to max 75"); //$NON-NLS-1$//$NON-NLS-2$ - errors.add(error); - } - - if ( CollectionUtils.isNotEmpty(errors)) - { - List eventErrors = setObjectErrors(errors, HttpStatus.BAD_REQUEST.value()); - return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); - } - // continue with get - - RegisterDevice device = this.getDeviceManager().getDevice(deviceId, userId); - - if ( device == null ) - { - return new ResponseEntity<>(device, HttpStatus.NOT_FOUND); - } - // check device activation - try - { - this.getDeviceManager().checkDeviceExpiry(device); - } - catch (DeviceRegistrationError e) - { - List eventErrors = setErrors(e, HttpStatus.BAD_REQUEST.value(),DEVICE_EXPIRY_ERROR); - return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); - } - String contentType = request.getHeader("Content-Type"); //$NON-NLS-1$ - if (contentType == null - || (!MediaType.APPLICATION_OCTET_STREAM_VALUE.equals(contentType) - && !MediaType.APPLICATION_ATOM_XML_VALUE.equals(contentType))) { - device.setDeviceConfig(this.getDeviceManager().getDeviceConfig()); - } - - if (contentType != null && MediaType.APPLICATION_OCTET_STREAM_VALUE.equalsIgnoreCase(contentType)) { - String fileName = this.csvWriter.getAssetCSV(device); - File file = new File(fileName); - InputStreamResource resource; + public ResponseEntity getDevice(@PathVariable String deviceId, HttpServletRequest request, + @RequestHeader("Authorization") String authorization) { + String userId = getUserId(request); + + List errors = new ArrayList(); + if (!RegisterDeviceValidation.validate(deviceId, + Pattern.compile(RegisterDeviceValidation.DEVICE_NAME_PATTERN))) { + ObjectError error = new ObjectError("deviceId", "Device id should match ^[A-Za-z0-9-]*"); //$NON-NLS-1$//$NON-NLS-2$ + errors.add(error); + } + + if (RegisterDeviceValidation.DEVICE_ADDRESS_LENGTH <= deviceId.length()) { + ObjectError error = new ObjectError("deviceId", "DeviceId is limited to max 75"); //$NON-NLS-1$//$NON-NLS-2$ + errors.add(error); + } + + if (CollectionUtils.isNotEmpty(errors)) { + List eventErrors = setObjectErrors(errors, HttpStatus.BAD_REQUEST.value()); + return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); + } + // continue with get + + RegisterDevice device = this.deviceManager.getDevice(deviceId, userId); + + if (device == null) { + return new ResponseEntity<>(device, HttpStatus.NOT_FOUND); + } + // check device activation + try { + this.deviceManager.checkDeviceExpiry(device); + } catch (DeviceRegistrationError e) { + List eventErrors = setErrors(e, HttpStatus.BAD_REQUEST.value(), DEVICE_EXPIRY_ERROR); + return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); + } + String contentType = request.getHeader("Content-Type"); //$NON-NLS-1$ + if (contentType == null || (!MediaType.APPLICATION_OCTET_STREAM_VALUE.equals(contentType) + && !MediaType.APPLICATION_ATOM_XML_VALUE.equals(contentType))) { + device.setDeviceConfig(this.deviceManager.getDeviceConfig()); + } + + if (contentType != null && MediaType.APPLICATION_OCTET_STREAM_VALUE.equalsIgnoreCase(contentType)) { + String fileName = this.csvWriter.getAssetCSV(device); + File file = new File(fileName); + InputStreamResource resource; try { resource = new InputStreamResource(new FileInputStream(file)); - return ResponseEntity.ok() - .contentLength(file.length()) - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .header("Content-Disposition", "attachment;filename=\""+fileName+"\"") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - .body(resource); + return ResponseEntity.ok().contentLength(file.length()).contentType(MediaType.APPLICATION_OCTET_STREAM) + .header("Content-Disposition", "attachment;filename=\"" + fileName + "\"") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + .body(resource); } catch (FileNotFoundException e) { throw new RuntimeException("Exception when Processing zip file"); //$NON-NLS-1$ - }finally { + } finally { file.delete(); } - } - return new ResponseEntity(device, HttpStatus.OK); - } - - - /** - * This method resets the Device settings. - * @param deviceId - - * @param device - - * @param request - - * @param result - - * @param authorization - - * @return - - */ - @RequestMapping(value = "/device/reset/{deviceId}", method = RequestMethod.PUT) - public ResponseEntity resetRegisterDevice(@PathVariable String deviceId, HttpServletRequest request, - @RequestHeader("Authorization") String authorization) - { - String userId = getUserId(request); - - List errors = new ArrayList(); - if(!RegisterDeviceValidation.validate(deviceId, Pattern.compile(RegisterDeviceValidation.DEVICE_NAME_PATTERN))) { - ObjectError error = new ObjectError("deviceId", "Device id should match ^[A-Za-z0-9-]*"); //$NON-NLS-1$//$NON-NLS-2$ - errors.add(error); - } - - if( RegisterDeviceValidation.DEVICE_ADDRESS_LENGTH <= deviceId.length()){ - ObjectError error = new ObjectError("deviceId", "DeviceId is limited to max 75"); //$NON-NLS-1$//$NON-NLS-2$ - errors.add(error); - } - - if ( CollectionUtils.isNotEmpty(errors)) - { - List eventErrors = setObjectErrors(errors, HttpStatus.BAD_REQUEST.value()); - return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); - } - - try - { - // continue with get device without user - RegisterDevice device = this.getDeviceManager().getDevice(deviceId,null); - if(device != null ){ - Boolean isAdmin = (Boolean) request.getAttribute("isAdmin"); //$NON-NLS-1$ - this.getDeviceManager().resetDevice(device,isAdmin,userId); - } - - } - catch (DeviceRegistrationError e) - { - List eventErrors = setErrors(e, HttpStatus.BAD_REQUEST.value(),DEVICE_RESET_ERROR); - return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); - } - - return new ResponseEntity<>(null, HttpStatus.OK); - - } - - - - /** - * @return the deviceManager - */ - public DeviceManager getDeviceManager() - { - return this.deviceManager; - } - - /** - * @param deviceManager the deviceManager to set - */ - public void setDeviceManager(DeviceManager deviceManager) - { - this.deviceManager = deviceManager; - } + } + return new ResponseEntity(device, HttpStatus.OK); } + + + + /** + * This method resets the Device settings. + * + * @param deviceId + * - + * @param device + * - + * @param request + * - + * @param result + * - + * @param authorization + * - + * @return - + */ + @RequestMapping(value = "/device/reset/{deviceId}", method = RequestMethod.PUT) + public ResponseEntity resetRegisterDevice(@PathVariable String deviceId, HttpServletRequest request, + @RequestHeader("Authorization") String authorization) { + String userId = getUserId(request); + + List errors = new ArrayList(); + if (!RegisterDeviceValidation.validate(deviceId, + Pattern.compile(RegisterDeviceValidation.DEVICE_NAME_PATTERN))) { + ObjectError error = new ObjectError("deviceId", "Device id should match ^[A-Za-z0-9-]*"); //$NON-NLS-1$//$NON-NLS-2$ + errors.add(error); + } + + if (RegisterDeviceValidation.DEVICE_ADDRESS_LENGTH <= deviceId.length()) { + ObjectError error = new ObjectError("deviceId", "DeviceId is limited to max 75"); //$NON-NLS-1$//$NON-NLS-2$ + errors.add(error); + } + + if (CollectionUtils.isNotEmpty(errors)) { + List eventErrors = setObjectErrors(errors, HttpStatus.BAD_REQUEST.value()); + return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); + } + + try { + // continue with get device without user + RegisterDevice device = this.deviceManager.getDevice(deviceId, null); + if (device != null) { + Boolean isAdmin = (Boolean) request.getAttribute("isAdmin"); //$NON-NLS-1$ + this.deviceManager.resetDeviceActivation(device, isAdmin, userId); + } + + } catch (DeviceRegistrationError e) { + List eventErrors = setErrors(e, HttpStatus.BAD_REQUEST.value(), DEVICE_RESET_ERROR); + return new ResponseEntity<>(eventErrors, HttpStatus.BAD_REQUEST); + } + + return new ResponseEntity<>(null, HttpStatus.OK); + + } + + /** + * @return the deviceManager + */ + public DeviceManager getDeviceManager() { + return this.deviceManager; + } + + /** + * @param deviceManager + * the deviceManager to set + */ + public void setDeviceManager(DeviceManager deviceManager) { + this.deviceManager = deviceManager; + } } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/error/DeviceRegistrationError.java b/src/main/java/com/ge/predix/solsvc/kitservice/error/DeviceRegistrationError.java index 6124ea0..ce9bc90 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/error/DeviceRegistrationError.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/error/DeviceRegistrationError.java @@ -7,7 +7,7 @@ * with the terms and conditions stipulated in the agreement/contract * under which the software has been supplied. */ - + package com.ge.predix.solsvc.kitservice.error; /** @@ -15,61 +15,62 @@ * @author 212421693 - */ -public class DeviceRegistrationError extends Exception -{ +public class DeviceRegistrationError extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * - + */ + public DeviceRegistrationError() { + // TODO Auto-generated constructor stub + } + + /** + * @param message + * - + * @param cause + * - + * @param enableSuppression + * - + * @param writableStackTrace + * - + */ + public DeviceRegistrationError(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + /** + * @param message + * - + * @param cause + * - + */ + public DeviceRegistrationError(String message, Throwable cause) { + super(message, cause); - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * - - */ - public DeviceRegistrationError() - { - // TODO Auto-generated constructor stub - } + } - /** - * @param message - - * @param cause - - * @param enableSuppression - - * @param writableStackTrace - - */ - public DeviceRegistrationError(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) - { - super(message, cause, enableSuppression, writableStackTrace); - } + /** + * @param message + * - + */ + public DeviceRegistrationError(String message) { + super(message); - /** - * @param message - - * @param cause - - */ - public DeviceRegistrationError(String message, Throwable cause) - { - super(message, cause); - - } + } - /** - * @param message - - */ - public DeviceRegistrationError(String message) - { - super(message); - - } + /** + * @param cause + * - + */ + public DeviceRegistrationError(Throwable cause) { + super(cause); - /** - * @param cause - - */ - public DeviceRegistrationError(Throwable cause) - { - super(cause); - - } - + } } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/manager/BaseManager.java b/src/main/java/com/ge/predix/solsvc/kitservice/manager/BaseManager.java index f6682bd..7b12ad5 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/manager/BaseManager.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/manager/BaseManager.java @@ -7,7 +7,7 @@ * with the terms and conditions stipulated in the agreement/contract * under which the software has been supplied. */ - + package com.ge.predix.solsvc.kitservice.manager; import java.util.List; @@ -28,85 +28,71 @@ * * @author 212421693 - */ -public abstract class BaseManager -{ - private static final Logger log = LoggerFactory.getLogger(BaseManager.class); - - /** - * - */ - @Autowired - protected JsonMapper jsonMapper; - - @Autowired - private GetDataHandler assetGetFieldDataHandler; - - - - /** - * @param request - - * @param headers - - * @return - - */ - protected List getFieldDataResult(GetFieldDataRequest request, List
headers) - { - GetFieldDataResult getResult = this.assetGetFieldDataHandler.getData(request, null, headers); - log.debug(this.jsonMapper.toJson(getResult)); - if ( !CollectionUtils.isEmpty(getResult.getErrorEvent()) ) - { - log.info("Error: fetching data"+this.jsonMapper.toJson(getResult)); //$NON-NLS-1$ - return null; - // TBD do something - } - if ( CollectionUtils.isEmpty(getResult.getFieldData()) || ( CollectionUtils.isNotEmpty(getResult.getFieldData()) && getResult.getFieldData().get(0).getData() == null) ) - { - log.info("Data Not found for "+this.jsonMapper.toJson(getResult)); //$NON-NLS-1$ - return null; - - } - return getResult.getFieldData(); - - } - - - - /** - * @return the jsonMapper - */ - public JsonMapper getJsonMapper() - { - return this.jsonMapper; - } - - - - /** - * @param jsonMapper the jsonMapper to set - */ - public void setJsonMapper(JsonMapper jsonMapper) - { - this.jsonMapper = jsonMapper; - } - - - - /** - * @return the assetGetFieldDataHandler - */ - public GetDataHandler getAssetGetFieldDataHandler() - { - return this.assetGetFieldDataHandler; - } - - - - /** - * @param assetGetFieldDataHandler the assetGetFieldDataHandler to set - */ - public void setAssetGetFieldDataHandler(GetDataHandler assetGetFieldDataHandler) - { - this.assetGetFieldDataHandler = assetGetFieldDataHandler; - } - +public abstract class BaseManager { + private static final Logger log = LoggerFactory.getLogger(BaseManager.class); + + /** + * + */ + @Autowired + protected JsonMapper jsonMapper; + + @Autowired + private GetDataHandler assetGetFieldDataHandler; + + /** + * @param request + * - + * @param headers + * - + * @return - + */ + protected List getFieldDataResult(GetFieldDataRequest request, List
headers) { + GetFieldDataResult getResult = this.assetGetFieldDataHandler.getData(request, null, headers); + log.debug(this.jsonMapper.toJson(getResult)); + if (!CollectionUtils.isEmpty(getResult.getErrorEvent())) { + log.info("Error: fetching data" + this.jsonMapper.toJson(getResult)); //$NON-NLS-1$ + return null; + // TBD do something + } + if (CollectionUtils.isEmpty(getResult.getFieldData()) || (CollectionUtils.isNotEmpty(getResult.getFieldData()) + && getResult.getFieldData().get(0).getData() == null)) { + log.info("Data Not found for " + this.jsonMapper.toJson(getResult)); //$NON-NLS-1$ + return null; + + } + return getResult.getFieldData(); + + } + + /** + * @return the jsonMapper + */ + public JsonMapper getJsonMapper() { + return this.jsonMapper; + } + + /** + * @param jsonMapper + * the jsonMapper to set + */ + public void setJsonMapper(JsonMapper jsonMapper) { + this.jsonMapper = jsonMapper; + } + + /** + * @return the assetGetFieldDataHandler + */ + public GetDataHandler getAssetGetFieldDataHandler() { + return this.assetGetFieldDataHandler; + } + + /** + * @param assetGetFieldDataHandler + * the assetGetFieldDataHandler to set + */ + public void setAssetGetFieldDataHandler(GetDataHandler assetGetFieldDataHandler) { + this.assetGetFieldDataHandler = assetGetFieldDataHandler; + } } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/manager/DeviceManager.java b/src/main/java/com/ge/predix/solsvc/kitservice/manager/DeviceManager.java index 24c5fa3..6e79a8c 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/manager/DeviceManager.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/manager/DeviceManager.java @@ -40,8 +40,10 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; +import org.springframework.security.jwt.Jwt; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.core.type.TypeReference; import com.ge.predix.entity.asset.AssetTag; import com.ge.predix.entity.fielddata.Data; import com.ge.predix.entity.fielddata.FieldData; @@ -58,476 +60,487 @@ import com.ge.predix.solsvc.restclient.config.IOauthRestConfig; import com.ge.predix.solsvc.restclient.impl.RestClient; import com.ge.predix.solsvc.timeseries.bootstrap.config.ITimeseriesConfig; +import com.ge.predix.uaa.token.lib.JsonUtils; /** * * @author 212421693 - */ @Component -public class DeviceManager extends BaseManager -{ - private static final Logger log = LoggerFactory.getLogger(DeviceManager.class); - private static final String DEVICE = "device"; //$NON-NLS-1$ - private static final String DEVICEGROUP = "deviceGroup"; //$NON-NLS-1$ - - - @Autowired - @Qualifier("defaultOauthRestConfig") - private IOauthRestConfig restConfig; - - @Autowired - private PutDataHandler assetPutFieldDataHandler; - - @Autowired - private RestClient restClient; - - @Autowired - private - ResourceLoader resourceLoader; - - @Autowired - @Qualifier("defaultTimeseriesConfig") - private ITimeseriesConfig timeseriesConfig; - - @Autowired - private GroupManagementService groupManagementService; - - // this number will be in days - @Value("${register.device.deactivation:#{60}}") - private String deactivationPeriod; - - @SuppressWarnings("javadoc") - @Value("${kit.webapp.url:null}") - String kitApplicationUrl; - - @SuppressWarnings("javadoc") - @Value("${kit.device.credentials:null}") - String deviceCredentials; - - @SuppressWarnings("javadoc") - @Value("${kit.device.artifactory.url:null}") - String artifactoryConfigUrl; - - - - - /** - * - * @param deviceIdentifier - - * @param userId - - * @return - - */ - public RegisterDevice getDevice(String deviceIdentifier, String userId) - { - log.info("Calling getDevice"); //$NON-NLS-1$ - return getDevice("/"+DEVICE,userId, deviceIdentifier); //$NON-NLS-1$ - - } - - /** - * Registers a device - * @param device - - * @param userId - - * @return RegisterDevice - * @throws DeviceRegistrationError - - */ - public RegisterDevice registerDevice(RegisterDevice device, String userId) throws DeviceRegistrationError - { - // reactivation TBD - log.info("Calling registerDevice for device="+device.getUri()+" User = "+userId); //$NON-NLS-1$ //$NON-NLS-2$ - return createorUpdateDevice(device,userId); - } - - - /** - * @param device - - * @return RegisterDevice - * @throws DeviceRegistrationError - */ - private RegisterDevice createorUpdateDevice(RegisterDevice device, String userId) throws DeviceRegistrationError - { - - List
headers = getServiceHeaders(); - // log.debug("In here to get Service Headers "+this.jsonMapper.toJson(device)); - if(StringUtils.isEmpty(device.getUri())){ - device.setUri("/"+DEVICE+"/"+device.getDeviceAddress()); //$NON-NLS-1$ //$NON-NLS-2$ - } - - if(device.getCreatedDate() == null ) { - device.setCreatedDate(String.valueOf(Instant.now().toEpochMilli())); - } - if(device.getUpdateDate() == null ) { - device.setUpdateDate(String.valueOf(Instant.now().toEpochMilli())); - } - - if(device.getActivationDate() == null ) { - device.setActivationDate(String.valueOf(Instant.now().toEpochMilli())); - } - - if(!StringUtils.isEmpty(device.getDeviceGroup()) && !device.getDeviceGroup().toLowerCase().startsWith("/devicegroup")){ //$NON-NLS-1$ - String groupRef= device.getDeviceGroup(); - device.setDeviceGroup("/"+DEVICEGROUP+"/"+groupRef); //$NON-NLS-1$ //$NON-NLS-2$ - } else if (!StringUtils.isEmpty(device.getDeviceGroup()) && device.getDeviceGroup().contains("group")) { //$NON-NLS-1$ - device.getDeviceGroup().replaceFirst("group", DEVICEGROUP); //$NON-NLS-1$ - } - - - // add default Asset tags - List tags = getDefaultTags(device.getDeviceAddress()); - device.setTags(new HashSet(tags)); - - // User and user group , device group - //1. Check if the userGroup exists for the device - //2. if userGroup, then add userId to users only, if not both places owner and users - //3. add this new userGroup to list of device-group. userGroup list. - //4. check if the deviceGroup name exists if yes use it add userGroup to the list - //5 .update the device with deviceGroup and userGroup. - - UserGroup userGroup = null; - if(!StringUtils.isEmpty(device.getUserGroup())) { - userGroup = this.groupManagementService.getUserGroup(device.getUserGroup(),headers); - } - if( userGroup !=null ) { - // this means that user group found adding the user to this user group - userGroup.getUaaUsers().add(userId); - userGroup.setUpdatedDate(String.valueOf(Instant.now().toEpochMilli())); - } else { - // user group not found creating a new userGroup adding user as a owner - userGroup = this.groupManagementService.createUserGroup(userId); - } - device.setUserGroup(userGroup.getUri()); - //****END user group setup - - DeviceGroup deviceGroup = null; - if(!StringUtils.isEmpty(device.getDeviceGroup())) { - deviceGroup = this.groupManagementService.getDeviceGroup(headers,device.getDeviceGroup()); - } - if( deviceGroup == null ){ - // this means that device group not ** found adding the user to this user group - deviceGroup = this.groupManagementService.createDeviceGroup(device.getDeviceGroup(),userGroup.getUri()); - } - - - String userGroupString = this.groupManagementService.getUserGroupString(userGroup); - String group = this.groupManagementService.getDeviceGroupString(deviceGroup); - log.debug("With devicegroup"+deviceGroup.getUri() + "userGroup" + userGroupString); //$NON-NLS-1$ //$NON-NLS-2$ - - List kitModels = new ArrayList<>(); - kitModels.add(device); - String deviceString = this.jsonMapper.toJson(kitModels); - PutFieldDataRequest putFieldDataRequest = FdhUtils.createRegisterPutRequest(deviceString,group,userGroupString); - PutFieldDataResult result = this.assetPutFieldDataHandler.putData(putFieldDataRequest, null, headers, - HttpPost.METHOD_NAME); - log.debug(this.jsonMapper.toJson(result)); - if ( !CollectionUtils.isEmpty(result.getErrorEvent()) ) - { - log.error("Error: registering/Updating Device for With devicegroup"+deviceGroup.getUri() + "userGroup" + userGroupString +" for User with Id" + userId); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - throw new DeviceRegistrationError(result.getErrorEvent().get(0)); - } - return device; - - } - - /** - * @param data - * @return - - */ - private RegisterDevice getDeviceInfoFromData(Data predixString) - { - RegisterDevice device = null; - PredixString data = (PredixString) predixString; - String deviceString = StringEscapeUtils.unescapeJava(data.getString()); - deviceString = deviceString.substring(1, deviceString.length() - 1); - deviceString = deviceString.substring(0, deviceString.length()); - List registeredDevice = this.jsonMapper.fromJsonArray("["+deviceString+"]", RegisterDevice.class); //$NON-NLS-1$ //$NON-NLS-2$ - if(CollectionUtils.isNotEmpty(registeredDevice)) { - device = registeredDevice.get(0); - if(device.getActivationDate() == null ) { - device.setExpirationDate(calculateExpiryDate(String.valueOf(Instant.now().toEpochMilli()))); - } else { - device.setExpirationDate(calculateExpiryDate(device.getActivationDate())); - } - } - - return device; - } - - /** - * - * @param activatationDate - * @return - - */ - private String calculateExpiryDate(String activatationDate) { - Date date = new Date(); - date.setTime(Long.valueOf(activatationDate)); - Date expiry = DateUtils.addDays(date, Integer.valueOf(this.deactivationPeriod)); - return String.valueOf(expiry.getTime()); - } - - - /** - * @return - - */ - private List getDefaultTags(String deviceAddress) - { - Map valuesMap = new HashMap(); - valuesMap.put("DEVICE_ADDRESS", deviceAddress);//$NON-NLS-1$ - StrSubstitutor sub = new StrSubstitutor(valuesMap); - String jsonTemplate = sub.replace(jsonTagTemplate()); - - //log.info("read Json is " +jsonTemplate ); //$NON-NLS-1$ - return this.jsonMapper.fromJsonArray(jsonTemplate, AssetTag.class); - - } - - /** - * TBD either cache this or use the vault service - * - * @return - - */ - private List
getServiceHeaders() - { - List
headers = this.restClient.getSecureTokenForClientId(); - headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$//$NON-NLS-2$ - return headers; - } - - /** - * @param userId - - * @return - - */ - public List getDevices(String userId) - { - log.info("Calling get All Device for"); //$NON-NLS-1$ - - return getDevice(userId); - } - - /** - * @param deviceIdentifier - - * @param userId - - * @param deviceAddress - - * @param deviceName - - * @return - - */ - public List getDevice(String userId) - { - log.info("Calling getDevice"); //$NON-NLS-1$ - List devices= new ArrayList (); - List
headers = getServiceHeaders(); - GetFieldDataRequest request; - try - { - request = FdhUtils.createGetUserDeviceRequest("/"+DEVICE, "PredixString",userId,null); //$NON-NLS-1$//$NON-NLS-2$ - List fieldDatas= getFieldDataResult(request,headers); - - if(CollectionUtils.isNotEmpty(fieldDatas)) { - for(FieldData fieldData:fieldDatas){ - devices.add( getDeviceInfoFromData(fieldData.getData())); - } - } - - } - catch (UnsupportedEncodingException e) - { - log.info("Error with decoding the String Asset filter "+e.toString(),e); //$NON-NLS-1$ - } - - return devices; - } - - - - /** - * @param deviceIdentifier - - * @param userId - - * @param deviceAddress - - * @param deviceName - - * @return - - */ - public RegisterDevice getDevice(String deviceIdentifier, String userId, String deviceAddress) - { - - log.info("Calling getDevice by user and device address"); //$NON-NLS-1$ - RegisterDevice device =null; - List
headers = getServiceHeaders(); - GetFieldDataRequest request; - try - { - request = FdhUtils.createGetUserDeviceRequest(deviceIdentifier, "PredixString",userId,deviceAddress);//$NON-NLS-1$ - List fieldData = getFieldDataResult(request,headers); - if(CollectionUtils.isNotEmpty(fieldData)) { - device = getDeviceInfoFromData(fieldData.get(0).getData()); - } - } - catch (UnsupportedEncodingException e) - { - - log.info("Error with decoding the String Asset filter "+e.toString(),e); //$NON-NLS-1$ - - } - - return device; - - } - - - /** - * - * @return - - */ - private String jsonTagTemplate() { - String tagModelTemplate = null ; - try { - log.info("DeviceManager: Loading asset-model..."); //$NON-NLS-1$ - Resource resource = getResourceLoader().getResource("classpath:asset-model/device-asset-tags.json"); //$NON-NLS-1$ - File dbAsFile = resource.getFile(); - tagModelTemplate = FileUtils.readFileToString(dbAsFile, "UTF-8"); //$NON-NLS-1$ - return tagModelTemplate; - } catch (IOException | NullPointerException e) { - log.error("DeviceManager: Asset model could not be initialized. ", e); //$NON-NLS-1$ - } - return tagModelTemplate; - } - - /** - * @return the resourceLoader - */ - public ResourceLoader getResourceLoader() - { - return this.resourceLoader; - } - - /** - * @param resourceLoader the resourceLoader to set - */ - public void setResourceLoader(ResourceLoader resourceLoader) - { - this.resourceLoader = resourceLoader; - } - - /** - * - * @return - - */ - @SuppressWarnings({ - "unchecked", "nls" - }) - public Map getDeviceConfig() - { - @SuppressWarnings("rawtypes") - Map deviceConfig = new LinkedHashMap(); - deviceConfig.put("predixUaaIssuer", this.restConfig.getOauthIssuerId()); //$NON-NLS-1$ - - deviceConfig.put("client",this.deviceCredentials); - deviceConfig.put("predixTimeSeriesIngestUri", this.timeseriesConfig.getWsUri()); //$NON-NLS-1$ - deviceConfig.put("predixTimeSeriesZoneid", this.timeseriesConfig.getZoneId()); - deviceConfig.put("deviceDeactivationPeriod", this.deactivationPeriod); - deviceConfig.put("cloudApplicationUrl", this.kitApplicationUrl); - deviceConfig.put("artifactoryConfigUrl", this.artifactoryConfigUrl); - return deviceConfig; - - } - - - /** - * @param device - - * @param originalDevice - - * @param userId - - * @throws DeviceRegistrationError - - */ - public void updateDevice(RegisterDevice device, RegisterDevice originalDevice , String userId) throws DeviceRegistrationError - { - log.info("Calling updateDevice for device="+originalDevice.getUri()+" User = "+userId); //$NON-NLS-1$ //$NON-NLS-2$ - - if(StringUtils.isNotEmpty(device.getDeviceName()) && ! originalDevice.getDeviceName().equalsIgnoreCase(device.getDeviceName())) { - originalDevice.setDeviceName(device.getDeviceName()); - } - if(StringUtils.isNotEmpty(device.getDeviceGroup()) && ! originalDevice.getDeviceGroup().equalsIgnoreCase(device.getDeviceGroup())) { - originalDevice.setDeviceGroup(device.getDeviceGroup()); - } - if(CollectionUtils.isNotEmpty(device.getTags())) { - originalDevice.getTags().addAll(device.getTags()); - } - if(device.getGeoLocation() !=null && StringUtils.isNotEmpty(device.getGeoLocation().getLatitude())) { - originalDevice.getGeoLocation().setLatitude(device.getGeoLocation().getLatitude()); - } - if(device.getGeoLocation() !=null && StringUtils.isNotEmpty(device.getGeoLocation().getLongitude())) { - originalDevice.getGeoLocation().setLongitude(device.getGeoLocation().getLongitude()); - } - - - originalDevice.setUpdateDate(String.valueOf(Instant.now().toEpochMilli())); - this.createorUpdateDevice(originalDevice,userId); - } - - /** - * @param device - - * @throws DeviceRegistrationError - - */ - public void checkDeviceExpiry(RegisterDevice device) throws DeviceRegistrationError - { - Long currentTime = Instant.now().toEpochMilli(); - //Date currentDate = new Date(currentTime); - Long activationTime = Long.valueOf(device.getActivationDate()); - // Date activationDate = new Date(activationTime); - - DateTime currentDate = new DateTime(currentTime); - DateTime activationDate = new DateTime(activationTime); - - int days = Days.daysBetween(currentDate, activationDate).getDays(); - - - if(Math.abs(days) > Integer.valueOf(this.deactivationPeriod)){ - throw new DeviceRegistrationError("Device has past its activation period."); //$NON-NLS-1$ - } - } - - /** - * @param device - - * @param isAdmin - - * @param userid - - * @throws DeviceRegistrationError - - */ - public void resetDevice(RegisterDevice device, Boolean isAdmin, String userid) throws DeviceRegistrationError - { - if(isAdmin) { - log.info("DeviceManager: admin access... resetting device"+device.getUri()); //$NON-NLS-1$ - device.setUpdateDate(String.valueOf(Instant.now().toEpochMilli())); - device.setActivationDate(device.getUpdateDate()); - createorUpdateDevice(device,userid); - } - - } - - /** - * - - * @return - - */ - public List getAllAdminDevices() - { - log.info("Calling getAdminDevice"); //$NON-NLS-1$ - List devices= new ArrayList (); - List
headers = getServiceHeaders(); - GetFieldDataRequest request; - try - { - request = FdhUtils.createGetAdminDeviceRequest("/"+DEVICE, "PredixString"); //$NON-NLS-1$//$NON-NLS-2$ - List fieldDatas= getFieldDataResult(request,headers); - - if(CollectionUtils.isNotEmpty(fieldDatas)) { - for(FieldData fieldData:fieldDatas){ - devices.add( getDeviceInfoFromData(fieldData.getData())); - } - } - - } - catch (UnsupportedEncodingException e) - { - log.info("Error with decoding the String Asset filter "+e.toString(),e); //$NON-NLS-1$ - } - - return devices; - - } +public class DeviceManager extends BaseManager { + private static final Logger log = LoggerFactory.getLogger(DeviceManager.class); + private static final String DEVICE = "device"; //$NON-NLS-1$ + private static final String DEVICEGROUP = "deviceGroup"; //$NON-NLS-1$ + + @Autowired + @Qualifier("defaultOauthRestConfig") + private IOauthRestConfig restConfig; + + @Autowired + private PutDataHandler assetPutFieldDataHandler; + + @Autowired + private RestClient restClient; + + @Autowired + private ResourceLoader resourceLoader; + + @Autowired + @Qualifier("defaultTimeseriesConfig") + private ITimeseriesConfig timeseriesConfig; + + @Autowired + private GroupManagementService groupManagementService; + + // this number will be in days + @Value("${register.device.deactivation:#{60}}") + private String deactivationPeriod; + + @Value("${kit.webapp.url:null}") + private String kitApplicationUrl; + + @Value("${kit.device.credentials:null}") + private String deviceCredentials; + + @Value("${kit.device.artifactory.url:null}") + private String artifactoryConfigUrl; + + /** + * + * @param deviceIdentifier + * - + * @param userId + * - + * @return - + */ + public RegisterDevice getDevice(String deviceIdentifier, String userId) { + log.info("Calling getDevice"); //$NON-NLS-1$ + return getDevice("/" + DEVICE, userId, deviceIdentifier); //$NON-NLS-1$ + + } + + /** + * Registers a device + * + * @param device + * - + * @param userId + * - + * @return RegisterDevice + * @throws DeviceRegistrationError + * - + */ + public RegisterDevice registerDevice(RegisterDevice device, String userId) throws DeviceRegistrationError { + // reactivation TBD + log.info("Calling registerDevice for device=" + device.getUri() + " User = " + userId); //$NON-NLS-1$ //$NON-NLS-2$ + return createorUpdateDevice(device, userId); + } + + /** + * @param device + * - + * @param userId - + * @return RegisterDevice + * @throws DeviceRegistrationError - + */ + public RegisterDevice createorUpdateDevice(RegisterDevice device, String userId) throws DeviceRegistrationError { + + List
headers = getServiceHeaders(); + // log.debug("In here to get Service Headers + // "+this.jsonMapper.toJson(device)); + if (StringUtils.isEmpty(device.getUri())) { + device.setUri("/" + DEVICE + "/" + device.getDeviceAddress()); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (device.getCreatedDate() == null) { + device.setCreatedDate(String.valueOf(Instant.now().toEpochMilli())); + } + if (device.getUpdateDate() == null) { + device.setUpdateDate(String.valueOf(Instant.now().toEpochMilli())); + } + + if (device.getActivationDate() == null) { + device.setActivationDate(String.valueOf(Instant.now().toEpochMilli())); + } + + if (!StringUtils.isEmpty(device.getDeviceGroup()) + && !device.getDeviceGroup().toLowerCase().startsWith("/devicegroup")) { //$NON-NLS-1$ + String groupRef = device.getDeviceGroup(); + device.setDeviceGroup("/" + DEVICEGROUP + "/" + groupRef); //$NON-NLS-1$ //$NON-NLS-2$ + } else if (!StringUtils.isEmpty(device.getDeviceGroup()) && device.getDeviceGroup().contains("group")) { //$NON-NLS-1$ + device.getDeviceGroup().replaceFirst("group", DEVICEGROUP); //$NON-NLS-1$ + } + + // add default Asset tags + List tags = getDefaultTags(device.getDeviceAddress()); + device.setTags(new HashSet(tags)); + + // User and user group , device group + // 1. Check if the userGroup exists for the device + // 2. if userGroup, then add userId to users only, if not both places + // owner and users + // 3. add this new userGroup to list of device-group. userGroup list. + // 4. check if the deviceGroup name exists if yes use it add userGroup + // to the list + // 5 .update the device with deviceGroup and userGroup. + + UserGroup userGroup = null; + if (!StringUtils.isEmpty(device.getUserGroup())) { + userGroup = this.groupManagementService.getUserGroup(device.getUserGroup(), headers); + } + if (userGroup != null) { + // this means that user group found adding the user to this user + // group + userGroup.getUaaUsers().add(userId); + userGroup.setUpdatedDate(String.valueOf(Instant.now().toEpochMilli())); + } else { + // user group not found creating a new userGroup adding user as a + // owner + userGroup = this.groupManagementService.createUserGroup(userId); + } + device.setUserGroup(userGroup.getUri()); + // ****END user group setup + + DeviceGroup deviceGroup = null; + if (!StringUtils.isEmpty(device.getDeviceGroup())) { + deviceGroup = this.groupManagementService.getDeviceGroup(headers, device.getDeviceGroup()); + } + if (deviceGroup == null) { + // this means that device group not ** found adding the user to this + // user group + deviceGroup = this.groupManagementService.createDeviceGroup(device.getDeviceGroup(), userGroup.getUri()); + } + + String userGroupString = this.groupManagementService.getUserGroupString(userGroup); + String group = this.groupManagementService.getDeviceGroupString(deviceGroup); + log.debug("With devicegroup" + deviceGroup.getUri() + "userGroup" + userGroupString); //$NON-NLS-1$ //$NON-NLS-2$ + + List kitModels = new ArrayList<>(); + kitModels.add(device); + String deviceString = this.jsonMapper.toJson(kitModels); + PutFieldDataRequest putFieldDataRequest = FdhUtils.createRegisterPutRequest(deviceString, group, + userGroupString); + PutFieldDataResult result = this.assetPutFieldDataHandler.putData(putFieldDataRequest, null, headers, + HttpPost.METHOD_NAME); + log.debug(this.jsonMapper.toJson(result)); + if (!CollectionUtils.isEmpty(result.getErrorEvent())) { + log.error("Error: registering/Updating Device for With devicegroup" + deviceGroup.getUri() + "userGroup" //$NON-NLS-1$ //$NON-NLS-2$ + + userGroupString + " for User with Id" + userId); //$NON-NLS-1$ + throw new DeviceRegistrationError(result.getErrorEvent().get(0)); + } + return device; + + } + + /** + * @param data + * @return - + */ + private RegisterDevice getDeviceInfoFromData(Data predixString) { + RegisterDevice device = null; + PredixString data = (PredixString) predixString; + String deviceString = StringEscapeUtils.unescapeJava(data.getString()); + deviceString = deviceString.substring(1, deviceString.length() - 1); + deviceString = deviceString.substring(0, deviceString.length()); + List registeredDevice = this.jsonMapper.fromJsonArray("[" + deviceString + "]", //$NON-NLS-1$ //$NON-NLS-2$ + RegisterDevice.class); + if (CollectionUtils.isNotEmpty(registeredDevice)) { + device = registeredDevice.get(0); + if (device.getActivationDate() == null) { + device.setExpirationDate(calculateExpiryDate(String.valueOf(Instant.now().toEpochMilli()))); + } else { + device.setExpirationDate(calculateExpiryDate(device.getActivationDate())); + } + } + + return device; + } + + /** + * @param accessToken - + * @return - + */ + public String getUserId(Jwt accessToken) { + if (accessToken == null) + return null; + Map claims = JsonUtils.readValue(accessToken.getClaims(), + new TypeReference>() {// + }); + if (claims == null) + return null; + return (String) claims.get("user_id"); //$NON-NLS-1$ + } + + /** + * + * @param activatationDate + * @return - + */ + private String calculateExpiryDate(String activatationDate) { + Date date = new Date(); + date.setTime(Long.valueOf(activatationDate)); + Date expiry = DateUtils.addDays(date, Integer.valueOf(this.deactivationPeriod)); + return String.valueOf(expiry.getTime()); + } + + /** + * @return - + */ + private List getDefaultTags(String deviceAddress) { + Map valuesMap = new HashMap(); + valuesMap.put("DEVICE_ADDRESS", deviceAddress);//$NON-NLS-1$ + StrSubstitutor sub = new StrSubstitutor(valuesMap); + String jsonTemplate = sub.replace(jsonTagTemplate()); + + // log.info("read Json is " +jsonTemplate ); //$NON-NLS-1$ + return this.jsonMapper.fromJsonArray(jsonTemplate, AssetTag.class); + + } + + /** + * TBD either cache this or use the vault service + * + * @return - + */ + private List
getServiceHeaders() { + List
headers = this.restClient.getSecureTokenForClientId(); + headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$//$NON-NLS-2$ + return headers; + } + + /** + * @param userId + * - + * @return - + */ + public List getDevices(String userId) { + log.info("Calling get All Device for"); //$NON-NLS-1$ + + return getDevice(userId); + } + + /** + * @param deviceIdentifier + * - + * @param userId + * - + * @param deviceAddress + * - + * @param deviceName + * - + * @return - + */ + public List getDevice(String userId) { + log.info("Calling getDevice"); //$NON-NLS-1$ + List devices = new ArrayList(); + List
headers = getServiceHeaders(); + GetFieldDataRequest request; + try { + request = FdhUtils.createGetUserDeviceRequest("/" + DEVICE, "PredixString", userId, null); //$NON-NLS-1$//$NON-NLS-2$ + List fieldDatas = getFieldDataResult(request, headers); + + if (CollectionUtils.isNotEmpty(fieldDatas)) { + for (FieldData fieldData : fieldDatas) { + devices.add(getDeviceInfoFromData(fieldData.getData())); + } + } + + } catch (UnsupportedEncodingException e) { + log.info("Error with decoding the String Asset filter " + e.toString(), e); //$NON-NLS-1$ + } + + return devices; + } + + /** + * @param deviceIdentifier + * - + * @param userId + * - + * @param deviceAddress + * - + * @param deviceName + * - + * @return - + */ + public RegisterDevice getDevice(String deviceIdentifier, String userId, String deviceAddress) { + + log.info("Calling getDevice by user and device address"); //$NON-NLS-1$ + RegisterDevice device = null; + List
headers = getServiceHeaders(); + GetFieldDataRequest request; + try { + request = FdhUtils.createGetUserDeviceRequest(deviceIdentifier, "PredixString", userId, deviceAddress);//$NON-NLS-1$ + List fieldData = getFieldDataResult(request, headers); + if (CollectionUtils.isNotEmpty(fieldData)) { + device = getDeviceInfoFromData(fieldData.get(0).getData()); + } + } catch (UnsupportedEncodingException e) { + + log.info("Error with decoding the String Asset filter " + e.toString(), e); //$NON-NLS-1$ + + } + + return device; + + } + + /** + * + * @return - + */ + private String jsonTagTemplate() { + String tagModelTemplate = null; + try { + log.info("DeviceManager: Loading asset-model..."); //$NON-NLS-1$ + Resource resource = getResourceLoader().getResource("classpath:asset-model/device-asset-tags.json"); //$NON-NLS-1$ + File dbAsFile = resource.getFile(); + tagModelTemplate = FileUtils.readFileToString(dbAsFile, "UTF-8"); //$NON-NLS-1$ + return tagModelTemplate; + } catch (IOException | NullPointerException e) { + log.error("DeviceManager: Asset model could not be initialized. ", e); //$NON-NLS-1$ + } + return tagModelTemplate; + } + + /** + * @return the resourceLoader + */ + public ResourceLoader getResourceLoader() { + return this.resourceLoader; + } + + /** + * @param resourceLoader + * the resourceLoader to set + */ + public void setResourceLoader(ResourceLoader resourceLoader) { + this.resourceLoader = resourceLoader; + } + + /** + * + * @return - + */ + @SuppressWarnings({ "unchecked", "nls" }) + public Map getDeviceConfig() { + @SuppressWarnings("rawtypes") + Map deviceConfig = new LinkedHashMap(); + deviceConfig.put("predixUaaIssuer", this.restConfig.getOauthIssuerId()); //$NON-NLS-1$ + + deviceConfig.put("client", this.deviceCredentials); + deviceConfig.put("predixTimeSeriesIngestUri", this.timeseriesConfig.getWsUri()); //$NON-NLS-1$ + deviceConfig.put("predixTimeSeriesZoneid", this.timeseriesConfig.getZoneId()); + deviceConfig.put("deviceDeactivationPeriod", this.deactivationPeriod); + deviceConfig.put("cloudApplicationUrl", this.kitApplicationUrl); + deviceConfig.put("artifactoryConfigUrl", this.artifactoryConfigUrl); + return deviceConfig; + + } + + /** + * @param device + * - + * @param originalDevice + * - + * @param userId + * - + * @throws DeviceRegistrationError + * - + */ + public void updateDevice(RegisterDevice device, RegisterDevice originalDevice, String userId) + throws DeviceRegistrationError { + log.info("Calling updateDevice for device=" + originalDevice.getUri() + " User = " + userId); //$NON-NLS-1$ //$NON-NLS-2$ + + if (StringUtils.isNotEmpty(device.getDeviceName()) + && !originalDevice.getDeviceName().equalsIgnoreCase(device.getDeviceName())) { + originalDevice.setDeviceName(device.getDeviceName()); + } + if (StringUtils.isNotEmpty(device.getDeviceGroup()) + && !originalDevice.getDeviceGroup().equalsIgnoreCase(device.getDeviceGroup())) { + originalDevice.setDeviceGroup(device.getDeviceGroup()); + } + if (CollectionUtils.isNotEmpty(device.getTags())) { + originalDevice.getTags().addAll(device.getTags()); + } + if (device.getGeoLocation() != null && StringUtils.isNotEmpty(device.getGeoLocation().getLatitude())) { + originalDevice.getGeoLocation().setLatitude(device.getGeoLocation().getLatitude()); + } + if (device.getGeoLocation() != null && StringUtils.isNotEmpty(device.getGeoLocation().getLongitude())) { + originalDevice.getGeoLocation().setLongitude(device.getGeoLocation().getLongitude()); + } + + originalDevice.setUpdateDate(String.valueOf(Instant.now().toEpochMilli())); + this.createorUpdateDevice(originalDevice, userId); + } + + /** + * @param device + * - + * @throws DeviceRegistrationError + * - + */ + public void checkDeviceExpiry(RegisterDevice device) throws DeviceRegistrationError { + Long currentTime = Instant.now().toEpochMilli(); + // Date currentDate = new Date(currentTime); + Long activationTime = Long.valueOf(device.getActivationDate()); + // Date activationDate = new Date(activationTime); + + DateTime currentDate = new DateTime(currentTime); + DateTime activationDate = new DateTime(activationTime); + + int days = Days.daysBetween(currentDate, activationDate).getDays(); + + if (Math.abs(days) > Integer.valueOf(this.deactivationPeriod)) { + throw new DeviceRegistrationError("Device has past its activation period."); //$NON-NLS-1$ + } + } + + /** + * @param device + * - + * @param isAdmin + * - + * @param userid + * - + * @throws DeviceRegistrationError + * - + */ + public void resetDeviceActivation(RegisterDevice device, Boolean isAdmin, String userid) throws DeviceRegistrationError { + if (isAdmin) { + log.info("DeviceManager: admin access... resetting device" + device.getUri()); //$NON-NLS-1$ + device.setUpdateDate(String.valueOf(Instant.now().toEpochMilli())); + device.setActivationDate(device.getUpdateDate()); + createorUpdateDevice(device, userid); + } + + } + + /** + * - + * + * @return - + */ + public List getAllAdminDevices() { + log.info("Calling getAdminDevice"); //$NON-NLS-1$ + List devices = new ArrayList(); + List
headers = getServiceHeaders(); + GetFieldDataRequest request; + try { + request = FdhUtils.createGetAdminDeviceRequest("/" + DEVICE, "PredixString"); //$NON-NLS-1$//$NON-NLS-2$ + List fieldDatas = getFieldDataResult(request, headers); + + if (CollectionUtils.isNotEmpty(fieldDatas)) { + for (FieldData fieldData : fieldDatas) { + devices.add(getDeviceInfoFromData(fieldData.getData())); + } + } + + } catch (UnsupportedEncodingException e) { + log.info("Error with decoding the String Asset filter " + e.toString(), e); //$NON-NLS-1$ + } + + return devices; + + } } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/manager/GroupManagementService.java b/src/main/java/com/ge/predix/solsvc/kitservice/manager/GroupManagementService.java index d3210d5..04c1bf7 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/manager/GroupManagementService.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/manager/GroupManagementService.java @@ -36,163 +36,165 @@ * @author 212421693 - */ @Component -public class GroupManagementService extends BaseManager -{ - private static final Logger log = LoggerFactory.getLogger(GroupManagementService.class); - private static final String USERGROUP = "userGroup"; //$NON-NLS-1$ - - /** - * @param headers - - * @param userId - - * @return - - */ - public UserGroup getUserGroupbyUserId(List
headers, String userId) - { - UserGroup userGroup = null; - if ( StringUtils.isNotEmpty(userId) ) - { - GetFieldDataRequest request = FdhUtils.createGetUserGroupRequest("/" + USERGROUP, "PredixString", userId); //$NON-NLS-1$ //$NON-NLS-2$ - List fieldData = getFieldDataResult(request, headers); - if ( CollectionUtils.isEmpty(fieldData) ) - { - return null; - } - Data predixString = fieldData.get(0).getData(); - PredixString data = (PredixString) predixString; - String deviceString = StringEscapeUtils.unescapeJava(data.getString()); - deviceString = deviceString.substring(1, deviceString.length() - 1); - deviceString = deviceString.substring(0, deviceString.length()); - List userGroups = this.jsonMapper.fromJsonArray("[" + deviceString + "]", UserGroup.class); //$NON-NLS-1$ //$NON-NLS-2$ - if ( CollectionUtils.isNotEmpty(userGroups) ) userGroup = userGroups.get(0); - return userGroup; - - } - return userGroup; - } - - - /** - * @param headers - - * @param deviceGroup - - * @param userId - - * @return - - */ - public UserGroup createUserGroup(String userId) - { - - UserGroup userGroup = new UserGroup(); - userGroup.setUri("/" + USERGROUP + "/" + UUID.randomUUID().toString()); //$NON-NLS-1$ //$NON-NLS-2$ - userGroup.getUaaOwners().add(userId); - userGroup.getUaaUsers().add(userId); - userGroup.setCreatedDate(String.valueOf(Instant.now().toEpochMilli())); - return userGroup; - - } - - /** - * @param userGroupUri - - * @param headers - - * @param deviceGroup - - * @param userId - - * @return - - */ - public UserGroup getUserGroup(String userGroupUri, List
headers) - { - - UserGroup userGroup = null; - - GetFieldDataRequest request = FdhUtils.createGetUserGroupRequest(userGroupUri, "PredixString", null); //$NON-NLS-1$ - List fieldData = getFieldDataResult(request, headers); - if ( CollectionUtils.isEmpty(fieldData) ) - { - return null; - } - Data predixString = fieldData.get(0).getData(); - PredixString data = (PredixString) predixString; - String deviceString = StringEscapeUtils.unescapeJava(data.getString()); - deviceString = deviceString.substring(1, deviceString.length() - 1); - deviceString = deviceString.substring(0, deviceString.length()); - List userGroups = this.jsonMapper.fromJsonArray("[" + deviceString + "]", UserGroup.class); //$NON-NLS-1$ //$NON-NLS-2$ - if ( CollectionUtils.isNotEmpty(userGroups) ) userGroup = userGroups.get(0); - return userGroup; - - } - - /** - * - * @param userGroup - - * @return - - */ - public String getUserGroupString(final UserGroup userGroup) - { - ArrayList kitModels = new ArrayList<>(); - kitModels.add(userGroup); - return this.jsonMapper.toJson(kitModels); - } - - /** - * - * @param deviceGroupRef - - * @param userGroupRef - - * @return - - */ - DeviceGroup createDeviceGroup(String deviceGroupRef, String userGroupRef) - { - DeviceGroup group = new DeviceGroup(); - group.setUri(deviceGroupRef); - group.setCreatedate(String.valueOf(Instant.now().toEpochMilli())); - group.setDescription(deviceGroupRef); - String[] parts = deviceGroupRef.split("/"); //$NON-NLS-1$ - if ( parts.length > 0 ) - { - group.setName(parts[parts.length - 1]); - } - group.getUserGroup().add(userGroupRef); - return group; - } - - /** - * - * @param headers - - * @param deviceGroupRef - - * @return - - */ - DeviceGroup getDeviceGroup(List
headers, String deviceGroupRef) - { - log.info("Calling deviceGroupRef for " + deviceGroupRef); //$NON-NLS-1$ - DeviceGroup group = null; - if ( StringUtils.isNotEmpty(deviceGroupRef) ) - { - GetFieldDataRequest request = FdhUtils.createGetGroupRequest(deviceGroupRef, "PredixString"); //$NON-NLS-1$ - List fieldData = getFieldDataResult(request, headers); - if ( CollectionUtils.isEmpty(fieldData) ) - { - return null; - } - Data predixString = fieldData.get(0).getData(); - PredixString data = (PredixString) predixString; - String deviceString = StringEscapeUtils.unescapeJava(data.getString()); - deviceString = deviceString.substring(1, deviceString.length() - 1); - deviceString = deviceString.substring(0, deviceString.length()); - List groups = this.jsonMapper.fromJsonArray("[" + deviceString + "]", DeviceGroup.class); //$NON-NLS-1$ //$NON-NLS-2$ - if ( CollectionUtils.isNotEmpty(groups) ) group = groups.get(0); - return group; - - } - return group; - - } - -/** - * @param deviceGroup - - * @return - - */ -public String getDeviceGroupString(DeviceGroup deviceGroup) -{ - List kitModels = new ArrayList<>(); - kitModels.add(deviceGroup); - return this.jsonMapper.toJson(kitModels); -} - +public class GroupManagementService extends BaseManager { + private static final Logger log = LoggerFactory.getLogger(GroupManagementService.class); + private static final String USERGROUP = "userGroup"; //$NON-NLS-1$ + + /** + * @param headers + * - + * @param userId + * - + * @return - + */ + public UserGroup getUserGroupbyUserId(List
headers, String userId) { + UserGroup userGroup = null; + if (StringUtils.isNotEmpty(userId)) { + GetFieldDataRequest request = FdhUtils.createGetUserGroupRequest("/" + USERGROUP, "PredixString", userId); //$NON-NLS-1$ //$NON-NLS-2$ + List fieldData = getFieldDataResult(request, headers); + if (CollectionUtils.isEmpty(fieldData)) { + return null; + } + Data predixString = fieldData.get(0).getData(); + PredixString data = (PredixString) predixString; + String deviceString = StringEscapeUtils.unescapeJava(data.getString()); + deviceString = deviceString.substring(1, deviceString.length() - 1); + deviceString = deviceString.substring(0, deviceString.length()); + List userGroups = this.jsonMapper.fromJsonArray("[" + deviceString + "]", UserGroup.class); //$NON-NLS-1$ //$NON-NLS-2$ + if (CollectionUtils.isNotEmpty(userGroups)) + userGroup = userGroups.get(0); + return userGroup; + + } + return userGroup; + } + + /** + * @param headers + * - + * @param deviceGroup + * - + * @param userId + * - + * @return - + */ + public UserGroup createUserGroup(String userId) { + + UserGroup userGroup = new UserGroup(); + userGroup.setUri("/" + USERGROUP + "/" + UUID.randomUUID().toString()); //$NON-NLS-1$ //$NON-NLS-2$ + userGroup.getUaaOwners().add(userId); + userGroup.getUaaUsers().add(userId); + userGroup.setCreatedDate(String.valueOf(Instant.now().toEpochMilli())); + return userGroup; + + } + + /** + * @param userGroupUri + * - + * @param headers + * - + * @param deviceGroup + * - + * @param userId + * - + * @return - + */ + public UserGroup getUserGroup(String userGroupUri, List
headers) { + + UserGroup userGroup = null; + + GetFieldDataRequest request = FdhUtils.createGetUserGroupRequest(userGroupUri, "PredixString", null); //$NON-NLS-1$ + List fieldData = getFieldDataResult(request, headers); + if (CollectionUtils.isEmpty(fieldData)) { + return null; + } + Data predixString = fieldData.get(0).getData(); + PredixString data = (PredixString) predixString; + String deviceString = StringEscapeUtils.unescapeJava(data.getString()); + deviceString = deviceString.substring(1, deviceString.length() - 1); + deviceString = deviceString.substring(0, deviceString.length()); + List userGroups = this.jsonMapper.fromJsonArray("[" + deviceString + "]", UserGroup.class); //$NON-NLS-1$ //$NON-NLS-2$ + if (CollectionUtils.isNotEmpty(userGroups)) + userGroup = userGroups.get(0); + return userGroup; + + } + + /** + * + * @param userGroup + * - + * @return - + */ + public String getUserGroupString(final UserGroup userGroup) { + ArrayList kitModels = new ArrayList<>(); + kitModels.add(userGroup); + return this.jsonMapper.toJson(kitModels); + } + + /** + * + * @param deviceGroupRef + * - + * @param userGroupRef + * - + * @return - + */ + DeviceGroup createDeviceGroup(String deviceGroupRef, String userGroupRef) { + DeviceGroup group = new DeviceGroup(); + group.setUri(deviceGroupRef); + group.setCreatedate(String.valueOf(Instant.now().toEpochMilli())); + group.setDescription(deviceGroupRef); + String[] parts = deviceGroupRef.split("/"); //$NON-NLS-1$ + if (parts.length > 0) { + group.setName(parts[parts.length - 1]); + } + group.getUserGroup().add(userGroupRef); + return group; + } + + /** + * + * @param headers + * - + * @param deviceGroupRef + * - + * @return - + */ + DeviceGroup getDeviceGroup(List
headers, String deviceGroupRef) { + log.info("Calling deviceGroupRef for " + deviceGroupRef); //$NON-NLS-1$ + DeviceGroup group = null; + if (StringUtils.isNotEmpty(deviceGroupRef)) { + GetFieldDataRequest request = FdhUtils.createGetGroupRequest(deviceGroupRef, "PredixString"); //$NON-NLS-1$ + List fieldData = getFieldDataResult(request, headers); + if (CollectionUtils.isEmpty(fieldData)) { + return null; + } + Data predixString = fieldData.get(0).getData(); + PredixString data = (PredixString) predixString; + String deviceString = StringEscapeUtils.unescapeJava(data.getString()); + deviceString = deviceString.substring(1, deviceString.length() - 1); + deviceString = deviceString.substring(0, deviceString.length()); + List groups = this.jsonMapper.fromJsonArray("[" + deviceString + "]", DeviceGroup.class); //$NON-NLS-1$ //$NON-NLS-2$ + if (CollectionUtils.isNotEmpty(groups)) + group = groups.get(0); + return group; + + } + return group; + + } + + /** + * @param deviceGroup + * - + * @return - + */ + public String getDeviceGroupString(DeviceGroup deviceGroup) { + List kitModels = new ArrayList<>(); + kitModels.add(deviceGroup); + return this.jsonMapper.toJson(kitModels); + } } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/model/DeviceGroup.java b/src/main/java/com/ge/predix/solsvc/kitservice/model/DeviceGroup.java index fb12891..fa0bc6b 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/model/DeviceGroup.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/model/DeviceGroup.java @@ -7,7 +7,7 @@ * with the terms and conditions stipulated in the agreement/contract * under which the software has been supplied. */ - + package com.ge.predix.solsvc.kitservice.model; import java.util.HashSet; @@ -23,50 +23,50 @@ * * @author 212421693 - */ -public class DeviceGroup extends Group -{ - /** - * - */ - Set userGroup = new HashSet(); - +public class DeviceGroup extends Group { + /** + * + */ + Set userGroup = new HashSet(); + + /** + * @return the userGroupRef + */ + public Set getUserGroup() { + return this.userGroup; + } + + /** + * @param userGroupRef + * the userGroupRef to set + */ + public void setUserGroup(Set userGroupRef) { + this.userGroup = userGroupRef; + } - /** - * @return the userGroupRef - */ - public Set getUserGroup() - { - return this.userGroup; - } + /* + * (non-Javadoc) + * + * @see + * com.ge.predix.solsvc.bootstrap.ams.dto.Group#equals(java.lang.Object) + */ + @Override + public boolean equals(Object other) { + return EqualsBuilder.reflectionEquals(this, other); + } - /** - * @param userGroupRef the userGroupRef to set - */ - public void setUserGroup(Set userGroupRef) - { - this.userGroup = userGroupRef; - } + /* + * (non-Javadoc) + * + * @see com.ge.predix.solsvc.bootstrap.ams.dto.Group#hashCode() + */ + @Override + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } - /* (non-Javadoc) - * @see com.ge.predix.solsvc.bootstrap.ams.dto.Group#equals(java.lang.Object) - */ - @Override - public boolean equals(Object other) - { - return EqualsBuilder.reflectionEquals(this, other); - } - - /* (non-Javadoc) - * @see com.ge.predix.solsvc.bootstrap.ams.dto.Group#hashCode() - */ - @Override - public int hashCode() - { - return HashCodeBuilder.reflectionHashCode(this); - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/model/GeoLocation.java b/src/main/java/com/ge/predix/solsvc/kitservice/model/GeoLocation.java index 423b330..b360981 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/model/GeoLocation.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/model/GeoLocation.java @@ -7,7 +7,7 @@ * with the terms and conditions stipulated in the agreement/contract * under which the software has been supplied. */ - + package com.ge.predix.solsvc.kitservice.model; import java.io.Serializable; @@ -16,54 +16,50 @@ * * @author 212421693 - */ -public class GeoLocation implements Serializable -{ +public class GeoLocation implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3350292912815020657L; + /** + * + */ + String latitude; + + /** + * + */ + String longitude; - /** - * - */ - private static final long serialVersionUID = -3350292912815020657L; - /** - * - */ - String latitude; - - /** - * - */ - String longitude; - - /** - * @return the latitude - */ - public String getLatitude() - { - return this.latitude; - } + /** + * @return the latitude + */ + public String getLatitude() { + return this.latitude; + } - /** - * @param latitude the latitude to set - */ - public void setLatitude(String latitude) - { - this.latitude = latitude; - } + /** + * @param latitude + * the latitude to set + */ + public void setLatitude(String latitude) { + this.latitude = latitude; + } - /** - * @return the longitude - */ - public String getLongitude() - { - return this.longitude; - } + /** + * @return the longitude + */ + public String getLongitude() { + return this.longitude; + } - /** - * @param longitude the longitude to set - */ - public void setLongitude(String longitude) - { - this.longitude = longitude; - } + /** + * @param longitude + * the longitude to set + */ + public void setLongitude(String longitude) { + this.longitude = longitude; + } - } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/model/RegisterDevice.java b/src/main/java/com/ge/predix/solsvc/kitservice/model/RegisterDevice.java index 9103055..28c062b 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/model/RegisterDevice.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/model/RegisterDevice.java @@ -7,7 +7,7 @@ * with the terms and conditions stipulated in the agreement/contract * under which the software has been supplied. */ - + package com.ge.predix.solsvc.kitservice.model; import java.util.HashSet; @@ -23,319 +23,332 @@ * @author 212421693 - */ -@XmlRootElement(name="device") -public class RegisterDevice -{ - /** - * - - */ - public RegisterDevice() - { - super(); - } - /** - * - */ - String uri; - - /** - * - */ - String deviceId; - - /** - * - */ - String deviceName; - /** - * - */ - String deviceAddress; - /** - * - */ - String deviceType; - /** - * - */ - String activationDate; - - /** - * - */ - String expirationDate; - /** - * - */ - - String deviceGroup; - - /** - * - */ - String userGroup; - - /** - * - */ - String createdDate; - - /** - * - */ - String updateDate; - - /** - * - */ - String ipAddress; - - /** - * - */ - String industrialAssetRef; - - /** - * - */ - private GeoLocation geoLocation = new GeoLocation(); - - /** - * @return reference to associated industrial asset - */ - public String getIndustrialAssetRef() - { - return this.industrialAssetRef; - } - /** - * @param industrialAssetRef the industrialAssetRef to set - */ - public void setIndustrialAssetRef(String industrialAssetRef) - { - this.industrialAssetRef = industrialAssetRef; - } - - /** - * @return the ipAddress - */ - public String getIpAddress() - { - return this.ipAddress; - } - /** - * @param ipAddress the ipAddress to set - */ - public void setIpAddress(String ipAddress) - { - this.ipAddress = ipAddress; - } - /** - * - */ - Set tags = new HashSet(); - - private Map deviceConfig; - /** - * @return the uri - */ - public String getUri() - { - return this.uri; - } - /** - * @param uri the uri to set - */ - public void setUri(String uri) - { - this.uri = uri; - } - /** - * @return the deviceName - */ - public String getDeviceName() - { - return this.deviceName; - } - /** - * @param deviceName the deviceName to set - */ - public void setDeviceName(String deviceName) - { - this.deviceName = deviceName; - } - /** - * @return the deviceAddress - */ - public String getDeviceAddress() - { - return this.deviceAddress; - } - /** - * @param deviceAddress the deviceAddress to set - */ - public void setDeviceAddress(String deviceAddress) - { - this.deviceAddress = deviceAddress; - if (deviceAddress != null) { - this.deviceId = deviceAddress.replaceAll("[^a-zA-Z0-9]", ""); //$NON-NLS-1$ //$NON-NLS-2$ +@XmlRootElement(name = "device") +public class RegisterDevice { + /** + * - + */ + public RegisterDevice() { + super(); + } + + /** + * + */ + String uri; + + /** + * + */ + String deviceId; + + /** + * + */ + String deviceName; + /** + * + */ + String deviceAddress; + /** + * + */ + String deviceType; + /** + * + */ + String activationDate; + + /** + * + */ + String expirationDate; + /** + * + */ + + String deviceGroup; + + /** + * + */ + String userGroup; + + /** + * + */ + String createdDate; + + /** + * + */ + String updateDate; + + /** + * + */ + String ipAddress; + + /** + * + */ + String industrialAssetRef; + + /** + * + */ + private GeoLocation geoLocation = new GeoLocation(); + + /** + * @return reference to associated industrial asset + */ + public String getIndustrialAssetRef() { + return this.industrialAssetRef; + } + + /** + * @param industrialAssetRef + * the industrialAssetRef to set + */ + public void setIndustrialAssetRef(String industrialAssetRef) { + this.industrialAssetRef = industrialAssetRef; + } + + /** + * @return the ipAddress + */ + public String getIpAddress() { + return this.ipAddress; + } + + /** + * @param ipAddress + * the ipAddress to set + */ + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + /** + * + */ + Set tags = new HashSet(); + + private Map deviceConfig; + + /** + * @return the uri + */ + public String getUri() { + return this.uri; + } + + /** + * @param uri + * the uri to set + */ + public void setUri(String uri) { + this.uri = uri; + } + + /** + * @return the deviceName + */ + public String getDeviceName() { + return this.deviceName; + } + + /** + * @param deviceName + * the deviceName to set + */ + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + /** + * @return the deviceAddress + */ + public String getDeviceAddress() { + return this.deviceAddress; + } + + /** + * @param deviceAddress + * the deviceAddress to set + */ + public void setDeviceAddress(String deviceAddress) { + this.deviceAddress = deviceAddress; + if (deviceAddress != null) { + this.deviceId = deviceAddress.replaceAll("[^a-zA-Z0-9]", ""); //$NON-NLS-1$ //$NON-NLS-2$ } - } - /** - * @return the deviceType - */ - public String getDeviceType() - { - return this.deviceType; - } - /** - * @param deviceType the deviceType to set - */ - public void setDeviceType(String deviceType) - { - this.deviceType = deviceType; - } - /** - * @return the activationDate - */ - public String getActivationDate() - { - return this.activationDate; - } - /** - * @param activationDate the activationDate to set - */ - public void setActivationDate(String activationDate) - { - this.activationDate = activationDate; - } - - /** - * @return the deviceGroupRef - */ - public String getDeviceGroup() - { - return this.deviceGroup; - } - /** - * @param deviceGroupRef the deviceGroupRef to set - */ - public void setDeviceGroup(String deviceGroupRef) - { - this.deviceGroup = deviceGroupRef; - } - /** - * @return the userGroupRef - */ - public String getUserGroup() - { - return this.userGroup; - } - /** - * @param userGroupRef the userGroupRef to set - */ - public void setUserGroup(String userGroupRef) - { - this.userGroup = userGroupRef; - } - /** - * @return the createdDate - */ - public String getCreatedDate() - { - return this.createdDate; - } - /** - * @param createdDate the createdDate to set - */ - public void setCreatedDate(String createdDate) - { - this.createdDate = createdDate; - } - /** - * @return the tags - */ - public Set getTags() - { - return this.tags; - } - /** - * @param tags the tags to set - */ - public void setTags(Set tags) - { - this.tags = tags; - } - - /** - * @return the deviceConfig - */ - public Map getDeviceConfig() - { - return this.deviceConfig; - } - /** - * @param deviceConfig the deviceConfig to set - */ - public void setDeviceConfig(Map deviceConfig) - { - this.deviceConfig = deviceConfig; - } - /** - * @return the updateDate - */ - public String getUpdateDate() - { - return this.updateDate; - } - /** - * @param updateDate the updateDate to set - */ - public void setUpdateDate(String updateDate) - { - this.updateDate = updateDate; - } - - /** - * - * @return - - */ + } + + /** + * @return the deviceType + */ + public String getDeviceType() { + return this.deviceType; + } + + /** + * @param deviceType + * the deviceType to set + */ + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + + /** + * @return the activationDate + */ + public String getActivationDate() { + return this.activationDate; + } + + /** + * @param activationDate + * the activationDate to set + */ + public void setActivationDate(String activationDate) { + this.activationDate = activationDate; + } + + /** + * @return the deviceGroupRef + */ + public String getDeviceGroup() { + return this.deviceGroup; + } + + /** + * @param deviceGroupRef + * the deviceGroupRef to set + */ + public void setDeviceGroup(String deviceGroupRef) { + this.deviceGroup = deviceGroupRef; + } + + /** + * @return the userGroupRef + */ + public String getUserGroup() { + return this.userGroup; + } + + /** + * @param userGroupRef + * the userGroupRef to set + */ + public void setUserGroup(String userGroupRef) { + this.userGroup = userGroupRef; + } + + /** + * @return the createdDate + */ + public String getCreatedDate() { + return this.createdDate; + } + + /** + * @param createdDate + * the createdDate to set + */ + public void setCreatedDate(String createdDate) { + this.createdDate = createdDate; + } + + /** + * @return the tags + */ + public Set getTags() { + return this.tags; + } + + /** + * @param tags + * the tags to set + */ + public void setTags(Set tags) { + this.tags = tags; + } + + /** + * @return the deviceConfig + */ + public Map getDeviceConfig() { + return this.deviceConfig; + } + + /** + * @param deviceConfig + * the deviceConfig to set + */ + public void setDeviceConfig(Map deviceConfig) { + this.deviceConfig = deviceConfig; + } + + /** + * @return the updateDate + */ + public String getUpdateDate() { + return this.updateDate; + } + + /** + * @param updateDate + * the updateDate to set + */ + public void setUpdateDate(String updateDate) { + this.updateDate = updateDate; + } + + /** + * + * @return - + */ public String getExpirationDate() { return this.expirationDate; } - + /** * - * @param expirationDate - + * @param expirationDate + * - */ public void setExpirationDate(String expirationDate) { this.expirationDate = expirationDate; } - /** - * @return the geLocation - */ - public GeoLocation getGeoLocation() - { - return this.geoLocation; - } - /** - * @param geLocation the geLocation to set - */ - public void setGeoLocation(GeoLocation geLocation) - { - this.geoLocation = geLocation; - } + + /** + * @return the geLocation + */ + public GeoLocation getGeoLocation() { + return this.geoLocation; + } + + /** + * @param geLocation + * the geLocation to set + */ + public void setGeoLocation(GeoLocation geLocation) { + this.geoLocation = geLocation; + } + /** * @return the deviceId */ public String getDeviceId() { return this.deviceId; } + /** - * @param deviceId the deviceId to set + * @param deviceId + * the deviceId to set */ public void setDeviceId(String deviceId) { this.deviceId = deviceId; } - - + } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/model/UserGroup.java b/src/main/java/com/ge/predix/solsvc/kitservice/model/UserGroup.java index dc3f383..a15a084 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/model/UserGroup.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/model/UserGroup.java @@ -7,7 +7,7 @@ * with the terms and conditions stipulated in the agreement/contract * under which the software has been supplied. */ - + package com.ge.predix.solsvc.kitservice.model; import java.util.HashSet; @@ -18,98 +18,100 @@ * * @author 212421693 - */ -public class UserGroup -{ - - private String uri; - /** - * - */ - Set uaaUsers = new HashSet(); - /** - * - */ - Set uaaOwners = new HashSet(); - - /** - * - */ - String createdDate; - /** - * - */ - String updatedDate; - /** - * @return the uri - */ - public String getUri() - { - return this.uri; - } - /** - * @param uri the uri to set - */ - public void setUri(String uri) - { - this.uri = uri; - } - /** - * @return the users - */ - public Set getUaaUsers() - { - return this.uaaUsers; - } - /** - * @param users the users to set - */ - public void setUaaUsers(Set users) - { - this.uaaUsers = users; - } - /** - * @return the owners - */ - public Set getUaaOwners() - { - return this.uaaOwners; - } - /** - * @param owners the owners to set - */ - public void setUaaOwners(Set owners) - { - this.uaaOwners = owners; - } - - /** - * @return the createdDate - */ - public String getCreatedDate() - { - return this.createdDate; - } - /** - * @param createdDate the createdDate to set - */ - public void setCreatedDate(String createdDate) - { - this.createdDate = createdDate; - } - /** - * @return the updatedDate - */ - public String getUpdatedDate() - { - return this.updatedDate; - } - /** - * @param updatedDate the updatedDate to set - */ - public void setUpdatedDate(String updatedDate) - { - this.updatedDate = updatedDate; - } - +public class UserGroup { + + private String uri; + /** + * + */ + Set uaaUsers = new HashSet(); + /** + * + */ + Set uaaOwners = new HashSet(); + + /** + * + */ + String createdDate; + /** + * + */ + String updatedDate; + + /** + * @return the uri + */ + public String getUri() { + return this.uri; + } + + /** + * @param uri + * the uri to set + */ + public void setUri(String uri) { + this.uri = uri; + } + + /** + * @return the users + */ + public Set getUaaUsers() { + return this.uaaUsers; + } + + /** + * @param users + * the users to set + */ + public void setUaaUsers(Set users) { + this.uaaUsers = users; + } + + /** + * @return the owners + */ + public Set getUaaOwners() { + return this.uaaOwners; + } + + /** + * @param owners + * the owners to set + */ + public void setUaaOwners(Set owners) { + this.uaaOwners = owners; + } + + /** + * @return the createdDate + */ + public String getCreatedDate() { + return this.createdDate; + } + + /** + * @param createdDate + * the createdDate to set + */ + public void setCreatedDate(String createdDate) { + this.createdDate = createdDate; + } + + /** + * @return the updatedDate + */ + public String getUpdatedDate() { + return this.updatedDate; + } + + /** + * @param updatedDate + * the updatedDate to set + */ + public void setUpdatedDate(String updatedDate) { + this.updatedDate = updatedDate; + } } diff --git a/src/main/java/com/ge/predix/solsvc/kitservice/validator/RegisterDeviceValidation.java b/src/main/java/com/ge/predix/solsvc/kitservice/validator/RegisterDeviceValidation.java index 7a63285..0b1353e 100644 --- a/src/main/java/com/ge/predix/solsvc/kitservice/validator/RegisterDeviceValidation.java +++ b/src/main/java/com/ge/predix/solsvc/kitservice/validator/RegisterDeviceValidation.java @@ -7,7 +7,7 @@ * with the terms and conditions stipulated in the agreement/contract * under which the software has been supplied. */ - + package com.ge.predix.solsvc.kitservice.validator; import java.util.regex.Matcher; @@ -24,93 +24,101 @@ * * @author 212421693 - */ -public class RegisterDeviceValidation implements Validator -{ - +public class RegisterDeviceValidation implements Validator { - private Pattern pattern; - private Pattern deviceTypePattern; - private Pattern groupRefPattern; + private Pattern pattern; + private Pattern deviceTypePattern; + private Pattern groupRefPattern; - @SuppressWarnings("javadoc") - public static final String DEVICE_NAME_PATTERN = "^[A-Za-z0-9-]*$"; //$NON-NLS-1$ - @SuppressWarnings("javadoc") - public static final String DEVICE_TYPE_PATTERN = "^[A-Za-z0-9]*$"; //$NON-NLS-1$ - @SuppressWarnings("javadoc") - public static final String GROUP_REF_PATTERN = "^[A-Za-z0-9-/]*$"; //$NON-NLS-1$ - @SuppressWarnings("javadoc") - public static final int DEVICE_ADDRESS_LENGTH = 75; - @SuppressWarnings("javadoc") - public static final int DEVICE_NAME_LENGTH = 50; + /** + * + */ + public static final String DEVICE_NAME_PATTERN = "^[A-Za-z0-9-]*$"; //$NON-NLS-1$ + /** + * + */ + public static final String DEVICE_TYPE_PATTERN = "^[A-Za-z0-9]*$"; //$NON-NLS-1$ + /** + * + */ + public static final String GROUP_REF_PATTERN = "^[A-Za-z0-9-/]*$"; //$NON-NLS-1$ + /** + * + */ + public static final int DEVICE_ADDRESS_LENGTH = 75; + /** + * + */ + public static final int DEVICE_NAME_LENGTH = 50; - - /** - * - - */ - public RegisterDeviceValidation() - { - this.pattern = Pattern.compile(DEVICE_NAME_PATTERN); - this.deviceTypePattern = Pattern.compile(DEVICE_TYPE_PATTERN); - this.groupRefPattern = Pattern.compile(GROUP_REF_PATTERN); - } + /** + * - + */ + public RegisterDeviceValidation() { + this.pattern = Pattern.compile(DEVICE_NAME_PATTERN); + this.deviceTypePattern = Pattern.compile(DEVICE_TYPE_PATTERN); + this.groupRefPattern = Pattern.compile(GROUP_REF_PATTERN); + } + /* + * (non-Javadoc) + * + * @see org.springframework.validation.Validator#supports(java.lang.Class) + */ + @Override + public boolean supports(Class clazz) { + return RegisterDevice.class.equals(clazz); + } - /* (non-Javadoc) - * @see org.springframework.validation.Validator#supports(java.lang.Class) - */ - @Override - public boolean supports(Class clazz) - { - return RegisterDevice.class.equals(clazz); - } + /* + * (non-Javadoc) + * + * @see org.springframework.validation.Validator#validate(java.lang.Object, + * org.springframework.validation.Errors) + */ + @Override + public void validate(Object target, Errors errors) { + RegisterDevice device = (RegisterDevice) target; + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "deviceName", "field.required"); //$NON-NLS-1$//$NON-NLS-2$ + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "deviceAddress", "field.required"); //$NON-NLS-1$//$NON-NLS-2$ + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "deviceType", "field.required"); //$NON-NLS-1$//$NON-NLS-2$ + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "deviceGroup", "field.required"); //$NON-NLS-1$//$NON-NLS-2$ - /* (non-Javadoc) - * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors) - */ - @Override - public void validate(Object target, Errors errors) - { - RegisterDevice device = (RegisterDevice) target; - ValidationUtils.rejectIfEmptyOrWhitespace(errors, "deviceName", "field.required"); //$NON-NLS-1$//$NON-NLS-2$ - ValidationUtils.rejectIfEmptyOrWhitespace(errors, "deviceAddress", "field.required"); //$NON-NLS-1$//$NON-NLS-2$ - ValidationUtils.rejectIfEmptyOrWhitespace(errors, "deviceType", "field.required"); //$NON-NLS-1$//$NON-NLS-2$ - ValidationUtils.rejectIfEmptyOrWhitespace(errors, "deviceGroup", "field.required"); //$NON-NLS-1$//$NON-NLS-2$ - - - if(!validate(device.getDeviceName() , this.pattern)){ - errors.rejectValue("DeviceName", "Device Name should match ^[A-Za-z0-9-]*"); //$NON-NLS-1$//$NON-NLS-2$ - } - if(!validate(device.getDeviceAddress(),this.pattern)){ - errors.rejectValue("DeviceAddress", "Device Address should match ^[A-Za-z0-9-]*"); //$NON-NLS-1$//$NON-NLS-2$ - } - if(!validate(device.getDeviceType(),this.deviceTypePattern)){ - errors.rejectValue("DeviceType", "Device Type should match ^[A-Za-z0-9]*"); //$NON-NLS-1$//$NON-NLS-2$ - } - if(!validate(device.getDeviceGroup(),this.groupRefPattern)){ - errors.rejectValue("GroupRef", "DeviceGroupRef should match ^[A-Za-z0-9-/]*"); //$NON-NLS-1$//$NON-NLS-2$ - } - - if( StringUtils.isEmpty(device.getDeviceName()) || DEVICE_NAME_LENGTH <= device.getDeviceName().length() ){ - errors.rejectValue("DeviceName", "Device Name is limited to max 50"); //$NON-NLS-1$//$NON-NLS-2$ - } - if( StringUtils.isEmpty(device.getDeviceAddress()) || DEVICE_ADDRESS_LENGTH <= device.getDeviceAddress().length()){ - errors.rejectValue("DeviceAddress", "Device Address is limited to max 75"); //$NON-NLS-1$//$NON-NLS-2$ - } - } + if (!validate(device.getDeviceName(), this.pattern)) { + errors.rejectValue("DeviceName", "Device Name should match ^[A-Za-z0-9-]*"); //$NON-NLS-1$//$NON-NLS-2$ + } + if (!validate(device.getDeviceAddress(), this.pattern)) { + errors.rejectValue("DeviceAddress", "Device Address should match ^[A-Za-z0-9-]*"); //$NON-NLS-1$//$NON-NLS-2$ + } + if (!validate(device.getDeviceType(), this.deviceTypePattern)) { + errors.rejectValue("DeviceType", "Device Type should match ^[A-Za-z0-9]*"); //$NON-NLS-1$//$NON-NLS-2$ + } + if (!validate(device.getDeviceGroup(), this.groupRefPattern)) { + errors.rejectValue("GroupRef", "DeviceGroupRef should match ^[A-Za-z0-9-/]*"); //$NON-NLS-1$//$NON-NLS-2$ + } + if (StringUtils.isEmpty(device.getDeviceName()) || DEVICE_NAME_LENGTH <= device.getDeviceName().length()) { + errors.rejectValue("DeviceName", "Device Name is limited to max 50"); //$NON-NLS-1$//$NON-NLS-2$ + } + if (StringUtils.isEmpty(device.getDeviceAddress()) + || DEVICE_ADDRESS_LENGTH <= device.getDeviceAddress().length()) { + errors.rejectValue("DeviceAddress", "Device Address is limited to max 75"); //$NON-NLS-1$//$NON-NLS-2$ + } + } - /** - * @param deviceName - - * @param pattern - - * @return - - */ - public static boolean validate(String deviceName, Pattern pattern) - { - if(StringUtils.isEmpty(deviceName) ){ - return false; - } - Matcher matcher = pattern.matcher(deviceName); - return matcher.matches(); - } + /** + * @param deviceName + * - + * @param pattern + * - + * @return - + */ + public static boolean validate(String deviceName, Pattern pattern) { + if (StringUtils.isEmpty(deviceName)) { + return false; + } + Matcher matcher = pattern.matcher(deviceName); + return matcher.matches(); + } } diff --git a/src/test/java/com/ge/predix/solsvc/service/AbstractBaseControllerIT.java b/src/test/java/com/ge/predix/solsvc/service/AbstractBaseControllerIT.java index 62e403d..18c0e27 100644 --- a/src/test/java/com/ge/predix/solsvc/service/AbstractBaseControllerIT.java +++ b/src/test/java/com/ge/predix/solsvc/service/AbstractBaseControllerIT.java @@ -7,7 +7,7 @@ * with the terms and conditions stipulated in the agreement/contract * under which the software has been supplied. */ - + package com.ge.predix.solsvc.service; import org.junit.runner.RunWith; @@ -25,9 +25,8 @@ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration -@IntegrationTest({"server.port=9092"}) -public abstract class AbstractBaseControllerIT -{ +@IntegrationTest({ "server.port=9092" }) +public abstract class AbstractBaseControllerIT { /* * */ diff --git a/src/test/java/com/ge/predix/solsvc/service/HelloControllerIT.java b/src/test/java/com/ge/predix/solsvc/service/HelloControllerIT.java index 453da88..da91a1c 100644 --- a/src/test/java/com/ge/predix/solsvc/service/HelloControllerIT.java +++ b/src/test/java/com/ge/predix/solsvc/service/HelloControllerIT.java @@ -7,12 +7,13 @@ * with the terms and conditions stipulated in the agreement/contract * under which the software has been supplied. */ - + package com.ge.predix.solsvc.service; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertThat; +import java.net.MalformedURLException; import java.net.URL; import org.junit.Before; @@ -26,44 +27,45 @@ * * @author 212421693 - */ -public class HelloControllerIT extends AbstractBaseControllerIT -{ - @Value("${local.server.port}") - private int localServerPort; +public class HelloControllerIT extends AbstractBaseControllerIT { + @Value("${local.server.port}") + private int localServerPort; + + private URL base; + private RestTemplate template; + + /** + * - + */ + @Before + public void setUp() { + this.template = new TestRestTemplate(); + } + + /** + * - + * @throws MalformedURLException - + */ + @SuppressWarnings("nls") + @Test + public void getHealth() throws MalformedURLException { + this.base = new URL("http://localhost:" + this.localServerPort + "/health"); + ResponseEntity response = this.template.getForEntity(this.base.toString(), String.class); + assertThat(response.getBody(), startsWith("{\"status\":\"up\"")); - private URL base; - private RestTemplate template; + } - /** - * @throws Exception - - */ - @Before - public void setUp() throws Exception { - this.template = new TestRestTemplate(); - } + /** + * @throws MalformedURLException - + * - + */ + @SuppressWarnings("nls") + @Test + public void getEcho() throws MalformedURLException { + this.base = new URL("http://localhost:" + this.localServerPort + "/echo"); + ResponseEntity response = this.template.getForEntity(this.base.toString(), String.class); + assertThat(response.getBody(), startsWith("Greetings from Predix Spring Boot! echo=")); - /** - * @throws Exception - - */ - @SuppressWarnings("nls") - @Test - public void getHealth() throws Exception { - this.base = new URL("http://localhost:" + this.localServerPort + "/health"); - ResponseEntity response = this.template.getForEntity(this.base.toString(), String.class); - assertThat(response.getBody(), startsWith("{\"status\":\"up\"")); - - } - - /** - * @throws Exception - - */ - @SuppressWarnings("nls") - @Test - public void getEcho() throws Exception { - this.base = new URL("http://localhost:" + this.localServerPort + "/echo"); - ResponseEntity response = this.template.getForEntity(this.base.toString(), String.class); - assertThat(response.getBody(), startsWith("Greetings from Predix Spring Boot! echo=")); - - } + } } diff --git a/src/test/java/com/ge/predix/solsvc/service/KitControllerIT.java b/src/test/java/com/ge/predix/solsvc/service/KitControllerIT.java index 2641776..21e779d 100644 --- a/src/test/java/com/ge/predix/solsvc/service/KitControllerIT.java +++ b/src/test/java/com/ge/predix/solsvc/service/KitControllerIT.java @@ -15,6 +15,7 @@ import static org.junit.Assert.assertTrue; import java.io.IOException; +import java.net.MalformedURLException; import java.net.URL; import java.time.Instant; import java.util.ArrayList; @@ -38,6 +39,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.security.jwt.Jwt; +import org.springframework.security.jwt.JwtHelper; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; @@ -46,6 +49,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.ge.predix.solsvc.ext.util.JsonMapper; +import com.ge.predix.solsvc.kitservice.error.DeviceRegistrationError; +import com.ge.predix.solsvc.kitservice.manager.DeviceManager; import com.ge.predix.solsvc.kitservice.model.GeoLocation; import com.ge.predix.solsvc.kitservice.model.RegisterDevice; import com.ge.predix.solsvc.restclient.config.IOauthRestConfig; @@ -55,522 +60,551 @@ * * @author 212421693 - */ -public class KitControllerIT extends AbstractBaseControllerIT -{ - - private static final Logger log = LoggerFactory.getLogger(KitControllerIT.class); - - @Value("${local.server.port}") - private int localServerPort; - - private URL base; - private RestTemplate template; - - @Autowired - private RestClient restClient; - - @Autowired - @Qualifier("defaultOauthRestConfig") - private IOauthRestConfig restConfig; - - @Autowired - private JsonMapper jsonMapper; - private ObjectMapper objectMapper; - - @SuppressWarnings("javadoc") - @Value("${kit.test.webapp.user:null}") - String appUser; - - @SuppressWarnings("javadoc") - @Value("${kit.test.webapp.user.password:null}") - String appUserPassword; - - @SuppressWarnings("javadoc") - @Value("${kit.test.predix.oauth.clientId:null}") - String clientCreds; - - - /** - * @throws Exception - - */ - @Before - public void setUp() - throws Exception - { - this.template = new TestRestTemplate(); - this.template.getMessageConverters().add(new FormHttpMessageConverter()); - this.template.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); - this.objectMapper = new ObjectMapper(); - } - - /** - * @throws Exception - - */ - @Test - public void registerDeviceWithAuthenticationError() - throws Exception - { - this.base = new URL("http://localhost:" + this.localServerPort + "/device/register"); //$NON-NLS-1$ //$NON-NLS-2$ - ResponseEntity response = this.template.getForEntity(this.base.toString(), String.class); - assertThat(response.getBody(), containsString("unauthorized")); //$NON-NLS-1$ - } - - /** - * @throws Exception - - */ - @Test - public void registerDevice() - throws Exception - { - - String url = "http://localhost:" + this.localServerPort + "/device/register"; //$NON-NLS-1$ //$NON-NLS-2$ - RegisterDevice device = getRegisterDevice(); - - String req = this.jsonMapper.toJson(device); - log.debug("Register Device Json req is " + this.jsonMapper.toJson(device)); //$NON-NLS-1$ - List
headers = new ArrayList
(); - String userToken = getUserToken(this.appUser, this.appUserPassword); - headers.add(new BasicHeader("Authorization", userToken)); //$NON-NLS-1$ - headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$ //$NON-NLS-2$ - - CloseableHttpResponse response = null; - try - { - response = this.restClient.post(url, req, headers, this.restConfig.getDefaultConnectionTimeout(), - this.restConfig.getDefaultSocketTimeout()); - Assert.assertNotNull(response); - Assert.assertTrue(response.toString().contains("HTTP/1.1 200 OK")); //$NON-NLS-1$ - String body = EntityUtils.toString(response.getEntity()); - assertThat(body, containsString("uri")); //$NON-NLS-1$ - RegisterDevice registeredDevice = this.objectMapper.readValue(body, RegisterDevice.class); - assertTrue(registeredDevice.getUri() != null); - String kitDeviceUrl = (String) registeredDevice.getDeviceConfig().get("artifactoryConfigUrl"); //$NON-NLS-1$ - assertTrue(kitDeviceUrl != null && kitDeviceUrl.startsWith("https")); //$NON-NLS-1$ - - } - finally - { - if ( response != null ) response.close(); - } - } - - /** - * @throws Exception - - */ - @Test - public void updateDevice() - throws Exception - { - List
headers = new ArrayList
(); - String userToken = getUserToken(this.appUser, this.appUserPassword); - headers.add(new BasicHeader("Authorization", userToken)); //$NON-NLS-1$ - headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$ //$NON-NLS-2$ - - RegisterDevice device = getRegisterDevice(); - String url = "http://localhost:" + this.localServerPort + "/device/" + device.getDeviceAddress(); //$NON-NLS-1$//$NON-NLS-2$ - - RegisterDevice updateDevice = getRegisterDevicebyId(headers,url); - - updateDevice.setDeviceName("UpdateDevice-Test"); //$NON-NLS-1$ - - String req = this.jsonMapper.toJson(updateDevice); - log.debug("update Device Json req is " + this.jsonMapper.toJson(updateDevice)); //$NON-NLS-1$ - - CloseableHttpResponse response = null; - try - { - response = this.restClient.put(url, req, headers, this.restConfig.getDefaultConnectionTimeout(), - this.restConfig.getDefaultSocketTimeout()); - Assert.assertNotNull(response); - Assert.assertTrue(response.toString().contains("HTTP/1.1 200 OK")); //$NON-NLS-1$ - - RegisterDevice newUpdatedDevice = getRegisterDevicebyId(headers,url); - Assert.assertTrue(newUpdatedDevice.getDeviceName().equalsIgnoreCase(updateDevice.getDeviceName())); - } - finally - { - if ( response != null ) response.close(); - } - } - - /** - * @return - - */ - private RegisterDevice getRegisterDevicebyId(List
headers , String url ) - { - RegisterDevice registeredDevice = null; - CloseableHttpResponse response = null; - try - { - response = this.restClient.get(url, headers); - Assert.assertNotNull(response); - Assert.assertTrue(response.toString().contains("HTTP/1.1 200 OK"));//$NON-NLS-1$ - String body = EntityUtils.toString(response.getEntity()); - registeredDevice = this.objectMapper.readValue(body, RegisterDevice.class); - assertTrue(registeredDevice.getUri() != null); - - } - catch (ParseException | IOException e) - { - e.printStackTrace(); - } - finally - { - if ( response != null ) try - { - response.close(); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - return registeredDevice; - } - - /** - * @throws Exception - - */ - @Test - public void registerDeviceValidationFailure() - throws Exception - { - - String url = "http://localhost:" + this.localServerPort + "/device/register"; //$NON-NLS-1$ //$NON-NLS-2$ - RegisterDevice device = getRegisterDevice(); - // device.setUserId(""); - //device.setDeviceAddress(""); - device.setDeviceName("!!!!"); //$NON-NLS-1$ - String req = this.jsonMapper.toJson(device); - log.debug("Register Device Json req is " + this.jsonMapper.toJson(device)); //$NON-NLS-1$ - List
headers = new ArrayList
(); - String userToken = getUserToken(this.appUser, this.appUserPassword); - headers.add(new BasicHeader("Authorization", userToken)); //$NON-NLS-1$ - headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$ //$NON-NLS-2$ - - CloseableHttpResponse response = null; - try - { - response = this.restClient.post(url, req, headers, this.restConfig.getDefaultConnectionTimeout(), - this.restConfig.getDefaultSocketTimeout()); - Assert.assertNotNull(response); - Assert.assertTrue(response.toString().contains("HTTP/1.1 400")); //$NON-NLS-1$ - String body = EntityUtils.toString(response.getEntity()); - assertThat(body, containsString("error")); //$NON-NLS-1$ - - } - finally - { - if ( response != null ) response.close(); - } - } - - /** - * - * @throws Exception - - */ - @Test - public void getDevice() - throws Exception - { - RegisterDevice device = getRegisterDevice(); - String url = "http://localhost:" + this.localServerPort + "/device/" + device.getDeviceAddress(); //$NON-NLS-1$ //$NON-NLS-2$ - List
headers = new ArrayList
(); - String userToken = getUserToken(this.appUser, this.appUserPassword); - headers.add(new BasicHeader("Authorization", userToken)); //$NON-NLS-1$ - headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$ //$NON-NLS-2$ - - CloseableHttpResponse response = null; - try - { - response = this.restClient.get(url, headers); - Assert.assertNotNull(response); - String body = EntityUtils.toString(response.getEntity()); - Assert.assertTrue(response.toString().contains("HTTP/1.1 200 OK")); //$NON-NLS-1$ - // assertThat(body, containsString("uri")); - RegisterDevice registeredDevice = this.objectMapper.readValue(body, RegisterDevice.class); - assertTrue(registeredDevice.getUri() != null); - - } - finally - { - if ( response != null ) response.close(); - } - } - - /** - * - * @throws Exception - - */ - @Test - public void getDeviceValidation() - throws Exception - { - String url = "http://localhost:" + this.localServerPort + "/device/tinfoil_0481%29"; //$NON-NLS-1$ //$NON-NLS-2$ - List
headers = new ArrayList
(); - String userToken = getUserToken(this.appUser, this.appUserPassword); - headers.add(new BasicHeader("Authorization", userToken)); //$NON-NLS-1$ - headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$ //$NON-NLS-2$ - - CloseableHttpResponse response = null; - try - { - response = this.restClient.get(url, headers); - Assert.assertNotNull(response); - Assert.assertTrue(response.toString().contains("HTTP/1.1 400")); //$NON-NLS-1$ - String body = EntityUtils.toString(response.getEntity()); - assertThat(body, containsString("error")); //$NON-NLS-1$ - - } - finally - { - if ( response != null ) response.close(); - } - } - - /** - * - * @throws Exception - - */ - @SuppressWarnings({ "unchecked" }) -@Test - public void getAllDevice() - throws Exception - { - String url = "http://localhost:" + this.localServerPort + "/device/"; //$NON-NLS-1$ //$NON-NLS-2$ - List
headers = new ArrayList
(); - String userToken = getUserToken(this.appUser, this.appUserPassword); - headers.add(new BasicHeader("Authorization", userToken)); //$NON-NLS-1$ - headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$ //$NON-NLS-2$ - - CloseableHttpResponse response = null; - try - { - response = this.restClient.get(url, headers); - Assert.assertNotNull(response); - Assert.assertTrue(response.toString().contains("HTTP/1.1 200 OK")); //$NON-NLS-1$ - String body = EntityUtils.toString(response.getEntity()); - List registeredDevices = this.objectMapper.readValue(body, ArrayList.class); - assertTrue(registeredDevices != null); - assertTrue(registeredDevices.size() > 0); - - } - finally - { - if ( response != null ) response.close(); - } - } - - /** - * - * @throws Exception - - */ - @SuppressWarnings({ - "resource" - }) - @Test - public void checkDeviceActivationExpiry() - throws Exception - { - - String url = "http://localhost:" + this.localServerPort + "/device/register"; //$NON-NLS-1$ //$NON-NLS-2$ - RegisterDevice device = getRegisterDevice(); - device.setUri("/device/testexpiry"); //$NON-NLS-1$ - device.setDeviceGroup("/deviceGroup/testexpiry"); //$NON-NLS-1$ - device.setDeviceName("TEST-EXPIRY"); //$NON-NLS-1$ - device.setDeviceAddress("testexpiry"); //$NON-NLS-1$ - DateTime lastWeek = new DateTime().minusDays(60+1); - device.setActivationDate(String.valueOf(lastWeek.getMillis())); - String req = this.jsonMapper.toJson(device); - log.debug("Register Device Json req is " + this.jsonMapper.toJson(device)); //$NON-NLS-1$ - List
headers = new ArrayList
(); - String userToken = getUserToken(this.appUser, this.appUserPassword); - - headers.add(new BasicHeader("Authorization", userToken)); //$NON-NLS-1$ - headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$ //$NON-NLS-2$ - - CloseableHttpResponse response = null; - try - { - response = this.restClient.post(url, req, headers, this.restConfig.getDefaultConnectionTimeout(), - this.restConfig.getDefaultSocketTimeout()); - Assert.assertNotNull(response); - // first time response is 200OK, next time its a validation failure due to expire time check - Assert.assertTrue(response.toString().contains("HTTP/1.1 200 OK") || (response.toString().contains("400 Bad Request") )); //$NON-NLS-1$ //$NON-NLS-2$ - String geturl = "http://localhost:" + this.localServerPort + "/device/"+device.getDeviceAddress(); //$NON-NLS-1$ //$NON-NLS-2$ - response = this.restClient.get(geturl, headers); - String body = EntityUtils.toString(response.getEntity()); - assertThat(body, containsString("Device has past its activation period.")); //$NON-NLS-1$ - - } - finally - { - if ( response != null ) response.close(); - } - } - - /** - * @return - - */ - private RegisterDevice getRegisterDevice() - { - RegisterDevice device = new RegisterDevice(); - // device.setUri("/device/test-guid"); //$NON-NLS-1$ - device.setActivationDate("1496181827187"); //$NON-NLS-1$ - device.setActivationDate(String.valueOf(Instant.now().toEpochMilli())); - // device.setCreatedDate(String.valueOf(Instant.now().toEpochMilli())); - device.setDeviceName("NUC-WR-IDP-E799-2"); //$NON-NLS-1$ - device.setDeviceAddress("WR-IDP-E799"); //$NON-NLS-1$ - device.setDeviceType("NUC"); //$NON-NLS-1$ - device.setDeviceGroup("/deviceGroup/testcompany-2"); //$NON-NLS-1$ - // device.setUserId("bd9f70a3-8aaa-490b-b2a8-91ba59e58f0f"); //$NON-NLS-1$ - device.setUri("/device/" + device.getDeviceAddress()); //$NON-NLS-1$ - GeoLocation geoLocation = new GeoLocation(); - geoLocation.setLatitude("51.5033640"); //$NON-NLS-1$ - geoLocation.setLongitude("-0.1276250"); //$NON-NLS-1$ - device.setGeoLocation(geoLocation); - return device; - } - - /** - * Returns a OAuth2RestTemplate based on the username password - */ - - private String getUserToken(String username, String password) - { - // get token here based on username password; - ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails(); - resourceDetails.setUsername(username); - resourceDetails.setPassword(password); - - String url = this.restConfig.getOauthIssuerId(); - - resourceDetails.setAccessTokenUri(url); - - String[] clientIds = this.clientCreds.split(":"); //$NON-NLS-1$ - resourceDetails.setClientId(clientIds[0]); - resourceDetails.setClientSecret(clientIds[1]); - - OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails); - OAuth2AccessToken token = restTemplate.getAccessToken(); - - return token.getTokenType() + " " + token.getValue(); //$NON-NLS-1$ - } - - - private String getClientToken(String clientId, String secret) - { - ClientCredentialsResourceDetails clientCreds = new ClientCredentialsResourceDetails(); - String url = this.restConfig.getOauthIssuerId(); - clientCreds.setAccessTokenUri(url); - clientCreds.setClientId(clientId); - clientCreds.setClientSecret(secret); - OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(clientCreds); - OAuth2AccessToken token = restTemplate.getAccessToken(); - return token.getTokenType() + " " + token.getValue(); //$NON-NLS-1$ - } - - - - /** - * @throws Exception - - */ - @Test - public void getMachineDevice() - throws Exception - { - RegisterDevice device = getRegisterDevice(); - String url = "http://localhost:" + this.localServerPort + "/device/" + device.getDeviceAddress(); //$NON-NLS-1$ //$NON-NLS-2$ - List
headers = new ArrayList
(); - String clientToken = getClientToken("device_client_id", "secret"); //$NON-NLS-1$ //$NON-NLS-2$ - headers.add(new BasicHeader("Authorization", clientToken)); //$NON-NLS-1$ - headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$ //$NON-NLS-2$ - - CloseableHttpResponse response = null; - try - { - response = this.restClient.get(url, headers); - Assert.assertNotNull(response); - Assert.assertTrue(response.toString().contains("HTTP/1.1 200 OK")); //$NON-NLS-1$ - String body = EntityUtils.toString(response.getEntity()); - // assertThat(body, containsString("uri")); - RegisterDevice registeredDevice = this.objectMapper.readValue(body, RegisterDevice.class); - assertTrue(registeredDevice.getUri() != null); - - } - finally - { - if ( response != null ) response.close(); - } - } - - - /** - * @throws Exception - - */ - //@Test - public void resetDevice() - throws Exception - { - List
headers = new ArrayList
(); - String userToken = getUserToken(this.appUser, this.appUserPassword); - headers.add(new BasicHeader("Authorization", userToken)); //$NON-NLS-1$ - headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$ //$NON-NLS-2$ - - RegisterDevice device = getRegisterDevice(); - String url = "http://localhost:" + this.localServerPort + "/device/reset/" + device.getDeviceAddress(); //$NON-NLS-1$//$NON-NLS-2$ - - CloseableHttpResponse response = null; - try - { - response = this.restClient.put(url, "", headers, this.restConfig.getDefaultConnectionTimeout(), //$NON-NLS-1$ - this.restConfig.getDefaultSocketTimeout()); - Assert.assertNotNull(response); - Assert.assertTrue(response.toString().contains("HTTP/1.1 200 OK")); //$NON-NLS-1$ - String getUrl = "http://localhost:" + this.localServerPort + "/device/" + device.getDeviceAddress(); //$NON-NLS-1$//$NON-NLS-2$ - RegisterDevice newUpdatedDevice = getRegisterDevicebyId(headers,getUrl); - Assert.assertTrue(org.apache.commons.lang.StringUtils.equalsIgnoreCase(newUpdatedDevice.getActivationDate(), newUpdatedDevice.getUpdateDate())); - } - finally - { - if ( response != null ) response.close(); - } - } - - - /** - * - * @throws Exception - - */ - @SuppressWarnings({ "unchecked" }) - //@Test - public void getAdminDevice() - throws Exception - { - - String url = "http://localhost:" + this.localServerPort + "/device/"; //$NON-NLS-1$ //$NON-NLS-2$ - List
headers = new ArrayList
(); - String userToken = getUserToken("app_admin_1", "app_admin_1"); //$NON-NLS-1$ //$NON-NLS-2$ - headers.add(new BasicHeader("Authorization", userToken)); //$NON-NLS-1$ - headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-1$ //$NON-NLS-2$ - - CloseableHttpResponse response = null; - try - { - response = this.restClient.get(url, headers); - Assert.assertNotNull(response); - Assert.assertTrue(response.toString().contains("HTTP/1.1 200 OK")); //$NON-NLS-1$ - String body = EntityUtils.toString(response.getEntity()); - List registeredDevices = this.objectMapper.readValue(body, ArrayList.class); - assertTrue(registeredDevices != null); - assertTrue(registeredDevices.size() > 0); - - } - finally - { - if ( response != null ) response.close(); - } - } - +public class KitControllerIT extends AbstractBaseControllerIT { + + private static final Logger log = LoggerFactory.getLogger(KitControllerIT.class); + + @Value("${local.server.port}") + private int localServerPort; + + private URL base; + private RestTemplate template; + + @Autowired + private RestClient restClient; + + @Autowired + @Qualifier("defaultOauthRestConfig") + private IOauthRestConfig restConfig; + + @Autowired + private JsonMapper jsonMapper; + private ObjectMapper objectMapper; + + private @Value("${kit.test.webapp.user:null}") String appUser; + + @Value("${kit.test.webapp.user.password:null}") + private String appUserPassword; + + @Value("${kit.test.predix.oauth.clientId:null}") + private String clientCreds; + + @Autowired + private DeviceManager deviceManager; + + /** + * - + */ + @Before + public void setUp() { + this.template = new TestRestTemplate(); + this.template.getMessageConverters().add(new FormHttpMessageConverter()); + this.template.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); + this.objectMapper = new ObjectMapper(); + } + + /** + * @throws MalformedURLException + * - + */ + @SuppressWarnings("nls") + @Test + public void registerDeviceWithAuthenticationError() throws MalformedURLException { + this.base = new URL("http://localhost:" + this.localServerPort + "/device/register"); //$NON-NLS-2$ + ResponseEntity response = this.template.getForEntity(this.base.toString(), String.class); + assertThat(response.getBody(), containsString("unauthorized")); + } + + /** + * @throws IOException + * - + * @throws ParseException + * - + */ + @SuppressWarnings("nls") + @Test + public void registerDevice() throws ParseException, IOException { + + String url = "http://localhost:" + this.localServerPort + "/device/register"; //$NON-NLS-2$ + RegisterDevice device = getRegisterDevice(); + + String req = this.jsonMapper.toJson(device); + log.debug("Register Device Json req is " + this.jsonMapper.toJson(device)); + List
headers = new ArrayList
(); + String userToken = getUserToken(this.appUser, this.appUserPassword); + headers.add(new BasicHeader("Authorization", userToken)); + headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-2$ + + CloseableHttpResponse response = null; + try { + response = this.restClient.post(url, req, headers, this.restConfig.getDefaultConnectionTimeout(), + this.restConfig.getDefaultSocketTimeout()); + Assert.assertNotNull(response); + String body = EntityUtils.toString(response.getEntity()); + Assert.assertTrue(response.toString() + body, response.toString().contains("HTTP/1.1 200 OK")); + assertThat(body, containsString("uri")); + RegisterDevice registeredDevice = this.objectMapper.readValue(body, RegisterDevice.class); + assertTrue(registeredDevice.getUri() != null); + String kitDeviceUrl = (String) registeredDevice.getDeviceConfig().get("artifactoryConfigUrl"); + assertTrue(kitDeviceUrl != null && kitDeviceUrl.startsWith("https")); + + } finally { + if (response != null) + response.close(); + } + } + + /** + * @return - + */ + @SuppressWarnings("nls") + private RegisterDevice getRegisterDevicebyId(List
headers, String url) { + RegisterDevice registeredDevice = null; + CloseableHttpResponse response = null; + try { + response = this.restClient.get(url, headers); + Assert.assertNotNull(response); + String body = EntityUtils.toString(response.getEntity()); + Assert.assertTrue(response.toString() + body, response.toString().contains("HTTP/1.1 200 OK")); + registeredDevice = this.objectMapper.readValue(body, RegisterDevice.class); + assertTrue(registeredDevice.getUri() != null); + + } catch (ParseException | IOException e) { + throw new RuntimeException(e); + } finally { + if (response != null) + try { + response.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + return registeredDevice; + } + + /** + * @throws IOException + * - + * @throws ParseException + * - - + */ + @SuppressWarnings("nls") + @Test + public void registerDeviceValidationFailure() throws ParseException, IOException { + + String url = "http://localhost:" + this.localServerPort + "/device/register"; //$NON-NLS-2$ + RegisterDevice device = getRegisterDevice(); + // device.setUserId(""); + // device.setDeviceAddress(""); + device.setDeviceName("!!!!"); + String req = this.jsonMapper.toJson(device); + log.debug("Register Device Json req is " + this.jsonMapper.toJson(device)); + List
headers = new ArrayList
(); + String userToken = getUserToken(this.appUser, this.appUserPassword); + headers.add(new BasicHeader("Authorization", userToken)); + headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-2$ + + CloseableHttpResponse response = null; + try { + response = this.restClient.post(url, req, headers, this.restConfig.getDefaultConnectionTimeout(), + this.restConfig.getDefaultSocketTimeout()); + Assert.assertNotNull(response); + String body = EntityUtils.toString(response.getEntity()); + Assert.assertTrue(response.toString() + body, response.toString().contains("HTTP/1.1 400")); + assertThat(body, containsString("error")); + + } finally { + if (response != null) + response.close(); + } + } + + /** + * + * @throws IOException + * - + * @throws ParseException + * - + */ + @SuppressWarnings("nls") + @Test + public void getDevice() throws ParseException, IOException { + RegisterDevice device = getRegisterDevice(); + String url = "http://localhost:" + this.localServerPort + "/device/" + device.getDeviceAddress(); //$NON-NLS-2$ + List
headers = new ArrayList
(); + String userToken = getUserToken(this.appUser, this.appUserPassword); + headers.add(new BasicHeader("Authorization", userToken)); + headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-2$ + + CloseableHttpResponse response = null; + try { + response = this.restClient.get(url, headers); + Assert.assertNotNull(response); + String body = EntityUtils.toString(response.getEntity()); + Assert.assertTrue(response.toString() + body, response.toString().contains("HTTP/1.1 200 OK")); + // assertThat(body, containsString("uri")); + RegisterDevice registeredDevice = this.objectMapper.readValue(body, RegisterDevice.class); + assertTrue(registeredDevice.getUri() != null); + + } finally { + if (response != null) + response.close(); + } + } + + /** + * + * @throws IOException + * - + * @throws ParseException + * - + */ + @SuppressWarnings("nls") + @Test + public void getDeviceValidation() throws ParseException, IOException { + String url = "http://localhost:" + this.localServerPort + "/device/tinfoil_0481%29"; //$NON-NLS-2$ + List
headers = new ArrayList
(); + String userToken = getUserToken(this.appUser, this.appUserPassword); + headers.add(new BasicHeader("Authorization", userToken)); + headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-2$ + + CloseableHttpResponse response = null; + try { + response = this.restClient.get(url, headers); + Assert.assertNotNull(response); + String body = EntityUtils.toString(response.getEntity()); + Assert.assertTrue(response.toString() + body, response.toString().contains("HTTP/1.1 400")); + assertThat(body, containsString("error")); + + } finally { + if (response != null) + response.close(); + } + } + + /** + * + * @throws IOException + * - + * @throws ParseException + * - + */ + @SuppressWarnings({ "unchecked", "nls" }) + @Test + public void getAllDevice() throws ParseException, IOException { + String url = "http://localhost:" + this.localServerPort + "/device/"; //$NON-NLS-2$ + List
headers = new ArrayList
(); + String userToken = getUserToken(this.appUser, this.appUserPassword); + headers.add(new BasicHeader("Authorization", userToken)); + headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-2$ + + CloseableHttpResponse response = null; + try { + response = this.restClient.get(url, headers); + Assert.assertNotNull(response); + String body = EntityUtils.toString(response.getEntity()); + Assert.assertTrue(response.toString() + body, + response.toString().contains("HTTP/1.1 200 OK")); + List registeredDevices = this.objectMapper.readValue(body, ArrayList.class); + assertTrue(registeredDevices != null); + assertTrue(registeredDevices.size() > 0); + + } finally { + if (response != null) + response.close(); + } + } + + /** + * @throws IOException + * - + * @throws DeviceRegistrationError - + */ + @SuppressWarnings("nls") + @Test + public void updateDevice() throws IOException, DeviceRegistrationError { + List
headers = new ArrayList
(); + String userToken = getUserToken(this.appUser, this.appUserPassword); + headers.add(new BasicHeader("Authorization", userToken)); + headers.add(new BasicHeader("Content-Type", "application/json")); + + RegisterDevice device = getRegisterDevice(); + + // ensure the device hasn't expired + DateTime twoDaysAgo = new DateTime().minusDays(2); + device.setActivationDate(String.valueOf(twoDaysAgo.getMillis())); + Jwt accessToken = JwtHelper.decode(userToken.substring(7)); + String userId = this.deviceManager.getUserId(accessToken); + this.deviceManager.createorUpdateDevice(device, userId ); + + String url = "http://localhost:" + this.localServerPort + "/device/" + device.getDeviceAddress(); //$NON-NLS-2$ + RegisterDevice updateDevice = getRegisterDevicebyId(headers, url); + updateDevice.setDeviceName("UpdateDevice-Test"); + + String req = this.jsonMapper.toJson(updateDevice); + log.debug("update Device Json req is " + this.jsonMapper.toJson(updateDevice)); + + CloseableHttpResponse response = null; + try { + response = this.restClient.put(url, req, headers, this.restConfig.getDefaultConnectionTimeout(), + this.restConfig.getDefaultSocketTimeout()); + Assert.assertNotNull(response); + Assert.assertTrue(response.toString() + EntityUtils.toString(response.getEntity()), + response.toString().contains("HTTP/1.1 200 OK")); + + RegisterDevice newUpdatedDevice = getRegisterDevicebyId(headers, url); + Assert.assertTrue(newUpdatedDevice.getDeviceName().equalsIgnoreCase(updateDevice.getDeviceName())); + } finally { + if (response != null) + response.close(); + } + } + + + /** + * @param url + * @param device + * @param lastWeek + * @throws IOException + * - + */ + @SuppressWarnings("nls") + private void callPost(String url, RegisterDevice device) throws IOException { + String req = this.jsonMapper.toJson(device); + log.debug("Device Json req is " + this.jsonMapper.toJson(device)); + List
headers = new ArrayList
(); + String userToken = getUserToken(this.appUser, this.appUserPassword); + + headers.add(new BasicHeader("Authorization", userToken)); + headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-2$ + + CloseableHttpResponse response = null; + try { + response = this.restClient.post(url, req, headers, this.restConfig.getDefaultConnectionTimeout(), + this.restConfig.getDefaultSocketTimeout()); + Assert.assertNotNull(response); + // first time response is 200OK, next time its a validation failure + // due to expire time check + Assert.assertTrue(response.toString() + EntityUtils.toString(response.getEntity()), + response.toString().contains("HTTP/1.1 200 OK") + || (response.toString().contains("400 Bad Request"))); + + } finally { + if (response != null) + response.close(); + } + } + + /** + * @return - + */ + @SuppressWarnings("nls") + private RegisterDevice getRegisterDevice() { + RegisterDevice device = new RegisterDevice(); + // device.setUri("/device/test-guid"); + // device.setActivationDate("1496181827187"); + device.setActivationDate(String.valueOf(Instant.now().toEpochMilli())); + // device.setCreatedDate(String.valueOf(Instant.now().toEpochMilli())); + device.setDeviceName("NUC-WR-IDP-E799-2"); + device.setDeviceAddress("WR-IDP-E799"); + device.setDeviceType("NUC"); + device.setDeviceGroup("/deviceGroup/testcompany-2"); + // device.setUserId("bd9f70a3-8aaa-490b-b2a8-91ba59e58f0f"); + // + device.setUri("/device/" + device.getDeviceAddress()); + GeoLocation geoLocation = new GeoLocation(); + geoLocation.setLatitude("51.5033640"); + geoLocation.setLongitude("-0.1276250"); + device.setGeoLocation(geoLocation); + return device; + } + + /** + * Returns a OAuth2RestTemplate based on the username password + */ + + @SuppressWarnings("nls") + private String getUserToken(String username, String password) { + // get token here based on username password; + ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails(); + resourceDetails.setUsername(username); + resourceDetails.setPassword(password); + + String url = this.restConfig.getOauthIssuerId(); + + resourceDetails.setAccessTokenUri(url); + + String[] clientIds = this.clientCreds.split(":"); + resourceDetails.setClientId(clientIds[0]); + resourceDetails.setClientSecret(clientIds[1]); + + OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails); + OAuth2AccessToken token = restTemplate.getAccessToken(); + + return token.getTokenType() + " " + token.getValue(); + } + + @SuppressWarnings("nls") + private String getClientToken(String clientId, String secret) { + ClientCredentialsResourceDetails clientCredsLocal = new ClientCredentialsResourceDetails(); + String url = this.restConfig.getOauthIssuerId(); + clientCredsLocal.setAccessTokenUri(url); + clientCredsLocal.setClientId(clientId); + clientCredsLocal.setClientSecret(secret); + OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(clientCredsLocal); + OAuth2AccessToken token = restTemplate.getAccessToken(); + return token.getTokenType() + " " + token.getValue(); + } + + /** + * + * @throws IOException + * - + * @throws ParseException + * - + */ + @SuppressWarnings({ "nls" }) + @Test + public void checkDeviceActivationExpiry() throws ParseException, IOException { + + String url = "http://localhost:" + this.localServerPort + "/device/register"; //$NON-NLS-2$ + RegisterDevice device = getRegisterDevice(); + device.setUri("/device/testexpiry"); + device.setDeviceGroup("/deviceGroup/testexpiry"); + device.setDeviceName("TEST-EXPIRY"); + device.setDeviceAddress("testexpiry"); + DateTime twoMonthsAgo = new DateTime().minusDays(60 + 1); + device.setActivationDate(String.valueOf(twoMonthsAgo.getMillis())); + log.debug("Register Device Json req is " + this.jsonMapper.toJson(device)); + List
headers = new ArrayList
(); + String userToken = getUserToken(this.appUser, this.appUserPassword); + + headers.add(new BasicHeader("Authorization", userToken)); + headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-2$ + callPost(url, device); + + CloseableHttpResponse response = null; + try { + String geturl = "http://localhost:" + this.localServerPort + "/device/" + device.getDeviceAddress(); //$NON-NLS-2$ + response = this.restClient.get(geturl, headers); + String body = EntityUtils.toString(response.getEntity()); + assertThat(body, containsString("Device has past its activation period.")); + + } finally { + if (response != null) + response.close(); + } + + } + + /** + * @throws IOException + * - + * @throws ParseException + * - + */ + @SuppressWarnings("nls") + @Test + public void getMachineDevice() throws ParseException, IOException { + RegisterDevice device = getRegisterDevice(); + String url = "http://localhost:" + this.localServerPort + "/device/" + device.getDeviceAddress(); //$NON-NLS-2$ + List
headers = new ArrayList
(); + String clientToken = getClientToken("device_client_id", "secret"); //$NON-NLS-2$ + headers.add(new BasicHeader("Authorization", clientToken)); + headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-2$ + + CloseableHttpResponse response = null; + try { + response = this.restClient.get(url, headers); + Assert.assertNotNull(response); + String body = EntityUtils.toString(response.getEntity()); + Assert.assertTrue(response.toString() + body, response.toString().contains("HTTP/1.1 200 OK")); + // assertThat(body, containsString("uri")); + RegisterDevice registeredDevice = this.objectMapper.readValue(body, RegisterDevice.class); + assertTrue(registeredDevice.getUri() != null); + + } finally { + if (response != null) + response.close(); + } + } + + /** + * @throws IOException + * - + */ + // @Test + @SuppressWarnings("nls") + public void resetDevice() throws IOException { + List
headers = new ArrayList
(); + String userToken = getUserToken(this.appUser, this.appUserPassword); + headers.add(new BasicHeader("Authorization", userToken)); + headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-2$ + + RegisterDevice device = getRegisterDevice(); + String url = "http://localhost:" + this.localServerPort + "/device/reset/" + device.getDeviceAddress(); //$NON-NLS-2$ + + callPut(headers, url, ""); + + String getUrl = "http://localhost:" + this.localServerPort + "/device/" + device.getDeviceAddress(); //$NON-NLS-2$ + RegisterDevice newUpdatedDevice = getRegisterDevicebyId(headers, getUrl); + Assert.assertTrue(org.apache.commons.lang.StringUtils.equalsIgnoreCase(newUpdatedDevice.getActivationDate(), + newUpdatedDevice.getUpdateDate())); + } + + /** + * @param headers + * @param url + * @param device + * @throws IOException + * - + */ + @SuppressWarnings("nls") + private void callPut(List
headers, String url, String body) throws IOException { + CloseableHttpResponse response = null; + try { + response = this.restClient.put(url, body, headers, this.restConfig.getDefaultConnectionTimeout(), + this.restConfig.getDefaultSocketTimeout()); + Assert.assertNotNull(response); + Assert.assertTrue(response.toString() + EntityUtils.toString(response.getEntity()), + response.toString().contains("HTTP/1.1 200 OK")); + } finally { + if (response != null) + response.close(); + } + } + + /** + * + * @throws IOException + * - + * @throws ParseException + * - + */ + @SuppressWarnings({ "unchecked", "nls" }) + // @Test + public void getAdminDevice() throws ParseException, IOException { + + String url = "http://localhost:" + this.localServerPort + "/device/"; //$NON-NLS-2$ + List
headers = new ArrayList
(); + String userToken = getUserToken("app_admin_1", "app_admin_1"); //$NON-NLS-2$ + headers.add(new BasicHeader("Authorization", userToken)); + headers.add(new BasicHeader("Content-Type", "application/json")); //$NON-NLS-2$ + + CloseableHttpResponse response = null; + try { + response = this.restClient.get(url, headers); + Assert.assertNotNull(response); + String body = EntityUtils.toString(response.getEntity()); + Assert.assertTrue(response.toString() + body, response.toString().contains("HTTP/1.1 200 OK")); + List registeredDevices = this.objectMapper.readValue(body, ArrayList.class); + assertTrue(registeredDevices != null); + assertTrue(registeredDevices.size() > 0); + + } finally { + if (response != null) + response.close(); + } + } }