Commit 973a393b authored by Spiros Koulouzis's avatar Spiros Koulouzis

cleanup old code

parent 97f29837
<?xml version="1.0" encoding="UTF-8"?>
<enunciate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://enunciate.webcohesion.com/schemas/enunciate-1.30.xsd">
<facets>
<exclude name="internal_api" />
</facets>
<api-classes>
<include pattern="nl.uva.sne.drip.api.v1.rest.*" />
</api-classes>
<api-import pattern="nl.uva.sne.drip.drip.commons.data.v1.external.*"/>
<api-import pattern="nl.uva.sne.drip.drip.commons.data.v1.external.ansible.*"/>
<modules>
<swagger disabled="true" />
</modules>
</enunciate>
<?xml version="1.0" encoding="UTF-8"?>
<project-shared-configuration>
<!--
This file contains additional configuration written by modules in the NetBeans IDE.
The configuration is intended to be shared among all the users of project and
therefore it is assumed to be part of version control checkout.
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
-->
<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
<!--
Properties that influence various parts of the IDE, especially code formatting and the like.
You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
That way multiple projects can share the same settings (useful for formatting rules for example).
Any value defined here will override the pom.xml file value but is only applicable to the current project.
-->
<org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_j2eeVersion>1.6-web</org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_j2eeVersion>
<netbeans.hint.licensePath>${project.basedir}/../licenseheader.txt</netbeans.hint.licensePath>
<org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_deploy_2e_server>Tomcat</org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_deploy_2e_server>
</properties>
</project-shared-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>drip</artifactId>
<groupId>nl.uva.sne.drip</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>nl.uva.sne.drip</groupId>
<artifactId>drip-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>drip-api</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<skipTests>true</skipTests>
</properties>
<dependencies>
<dependency>
<groupId>nl.uva.sne.drip</groupId>
<artifactId>drip-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.5.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.8.0.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-core</artifactId>
<version>2.5.6.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.webcohesion.enunciate</groupId>
<artifactId>enunciate-core-annotations</artifactId>
<version>2.9.1</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>nl.uva.sne.drip</groupId>
<artifactId>drip-planner2provisioner</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.jvnet.ws.wadl</groupId>
<artifactId>wadl-core</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>org.jvnet.ws.wadl</groupId>
<artifactId>wadl-client-plugin</artifactId>
<version>1.1.6</version>
</dependency>
<!-- <dependency>
<groupId>net.bull.javamelody</groupId>
<artifactId>javamelody-core</artifactId>
<version>1.71.0</version>
</dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>9</source>
<target>9</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>6.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<!-- <plugin>
<groupId>com.webcohesion.enunciate</groupId>
<artifactId>enunciate-maven-plugin</artifactId>
<version>2.9.1</version>
<executions>
<execution>
<id>assemble</id>
<goals>
<goal>assemble</goal>
<goal>docs</goal>
</goals>
<configuration>
<docsDir>${project.basedir}/../docs/apidocs</docsDir>
<configFile>enunciate.xml</configFile>
<sourcepath-includes>
<include>
configure Enunciate to look for the source jars for all dependencies groupId.
<groupId>nl.uva.sne.drip</groupId>
<artifactId>drip-commons</artifactId>
</include>
</sourcepath-includes>
</configuration>
</execution>
</executions>
</plugin>-->
<!-- <plugin>
<groupId>com.webcohesion.enunciate</groupId>
<artifactId>enunciate-maven-plugin</artifactId>
<version>2.8.1</version>
<executions>
<execution>
<goals>
<goal>docs</goal>
</goals>
<configuration>
<docsDir>${project.basedir}/../docs</docsDir>
<configFile>enunciate.xml</configFile>
</configuration>
</execution>
</executions>
</plugin>-->
</plugins>
</build>
</project>
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.auth;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.web.filter.GenericFilterBean;
/**
*
* @author S. Koulouzis
*/
public class AuthFilter extends GenericFilterBean {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.auth;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
/**
*
* @author S. Koulouzis
*/
@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
throws IOException, ServletException {
// super.commence(request, response, authEx);
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 - " + authEx.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("DRIP");
super.afterPropertiesSet();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.auth;
import java.io.Serializable;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
/**
*
* @author S. Koulouzis
*/
public class PermissionEvaluatorImp implements PermissionEvaluator {
@Override
public boolean hasPermission(Authentication a, Object o, Object o1) {
if (!a.isAuthenticated()) {
return false;
}
if (!(a.getPrincipal() instanceof User)) {
return false;
} else {
User user = (User) a.getPrincipal();
return true;
}
// return false;
}
@Override
public boolean hasPermission(Authentication a, Serializable srlzbl, String string, Object o) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.uva.sne.drip.api.conf;
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
*
* @author S. Koulouzis
*/
@Configuration
@EnableScheduling
@EnableAsync
@ComponentScan("nl.uva.sne.drip")
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(5);
scheduler.initialize();
return scheduler;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.conf;
import nl.uva.sne.drip.api.auth.PermissionEvaluatorImp;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
/**
*
* @author S. Koulouzis
*/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler
= new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(new PermissionEvaluatorImp());
return expressionHandler;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.conf;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
/**
*
* @author S. Koulouzis
*/
@Configuration
@EnableMongoRepositories(basePackages = "nl.uva.sne.drip.api")
@PropertySources({
@PropertySource(value = "classpath:drip.properties", ignoreResourceNotFound = true),
@PropertySource(value = "file:etc/drip.properties", ignoreResourceNotFound = true)
})
@ComponentScan("nl.uva.sne.drip")
public class MongoConfig extends AbstractMongoConfiguration {
@Value("${db.name}")
private String dbName;
@Value("${db.host}")
private String dbHost;
@Value("${db.username}")
private String dbUsername;
@Value("${db.password}")
private String dbPass;
// @Autowired
// private MongoDbFactory mongoFactory;
// @Autowired
// private MongoMappingContext mongoMappingContext;
@Override
protected String getDatabaseName() {
return dbName;
}
@Override
public Mongo mongo() throws Exception {
return new MongoClient(dbHost, 27017);
}
@Override
protected String getMappingBasePackage() {
return "nl.uva.sne.drip";
}
}
/*
* Copyright 2016 S. Koulouzis
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package nl.uva.sne.drip.api.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan("nl.uva.sne.drip")
//@PropertySource("classpath:drip.properties")
@PropertySources({
@PropertySource(value = "classpath:drip.properties", ignoreResourceNotFound = true),
@PropertySource(value = "file:etc/drip.properties", ignoreResourceNotFound = true)
})
@EnableWebMvc
public class MultipartConfig {
@Bean(name = "multipartResolver")
public CommonsMultipartResolver createMultipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
// resolver.setMaxInMemorySize(0);
//resolver.setMaxUploadSize(0);
//resolver.setMaxUploadSizePerFile(0);
return resolver;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.conf;
import nl.uva.sne.drip.api.auth.MyBasicAuthenticationEntryPoint;
import nl.uva.sne.drip.api.auth.AuthFilter;
import nl.uva.sne.drip.api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
/**
*
* @author S. Koulouzis
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true)
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Autowired
private MyBasicAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/user/*").hasRole("USER")
.and()
.authorizeRequests()
.antMatchers("/manager/*").hasRole("ADMIN")
.and()
.authorizeRequests()
.antMatchers("/monitoring/*").hasRole("ADMIN")
.and()
.formLogin()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new AuthFilter(), BasicAuthenticationFilter.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.conf;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
/*
* Copyright 2016 S. Koulouzis
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package nl.uva.sne.drip.api.conf;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MultipartConfig.class);
ctx.register(MongoConfig.class);
ctx.register(SecurityConfig.class);
ctx.register(AsyncConfig.class);
// ctx.register(MethodSecurityConfig.class);
ctx.setServletContext(servletContext);
DispatcherServlet dispatcher = new DispatcherServlet(ctx);
Dynamic dynamic = servletContext.addServlet("dispatcher", dispatcher);
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
dynamic.setAsyncSupported(true);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.ansible.AnsibleOutput;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface AnsibleOutputDao extends MongoRepository<AnsibleOutput, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.CloudCredentials;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface CloudCredentialsDao extends MongoRepository<CloudCredentials, String> {
// @Override
// CloudCredentials findOne(String id);
//
// @PreAuthorize(ALLOWED_FOR_ADMINISTRATOR)
// @Override
// void delete(String id);
//
// @PreAuthorize(ALLOWED_FOR_OWNER + " or " + ALLOWED_FOR_ADMINISTRATOR)
// @Override
// List<CloudCredentials> findAll();
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.ConfigurationRepresentation;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface ConfigurationDao extends MongoRepository<ConfigurationRepresentation, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.DeployResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.KeyValueHolder;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
/**
*
* @author S. Koulouzis
*/
public interface DeployDao extends MongoRepository<DeployResponse, String> {
@Query(value = "{'statusHistories':{$elemMatch:{'status':{$in:['PROCESSABLE']}}},'created' : { '$gt' : { '$date' : ':?0' } , '$lt' : { '$date' : ':?1'}}}", count = true)
public Iterable<KeyValueHolder> findByCommand(String cmd);
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.KeyPair;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface KeyPairDao extends MongoRepository<KeyPair, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.MonitorringMessage;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface MonitorringMessageDao extends MongoRepository<MonitorringMessage, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.PlanResponse;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface PlanDao extends MongoRepository<PlanResponse, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.ProvisionResponse;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface ProvisionResponseDao extends MongoRepository<ProvisionResponse, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.ToscaRepresentation;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface ToscaDao extends MongoRepository<ToscaRepresentation, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface UserDao extends MongoRepository<User, String> {
public User findByUsername(String username);
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String massage) {
super(massage);
}
public BadRequestException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Cloud credentials not found")
public class CloudCredentialsNotFoundException extends RuntimeException {
public CloudCredentialsNotFoundException(String string) {
super(string);
}
public CloudCredentialsNotFoundException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
/**
*
* @author S. Koulouzis
*/
public class ExceptionHandler {
public static RuntimeException generateException(String name, String value) {
if (value == null) {
return new InternalServerErrorException();
}
if (value.contains("The maximum number of VPCs has been reached")) {
return new VMLimitException(name + "." + value);
} else {
return new InternalServerErrorException();
}
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public class InternalServerErrorException extends RuntimeException {
public InternalServerErrorException(String massage) {
super(massage);
}
public InternalServerErrorException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
/**
*
* @author S. Koulouzis
*/
public class KeyException extends Exception{
public KeyException(String message) {
super(message);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
public NotFoundException(String string) {
super(string);
}
public NotFoundException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Cloud provider name can't be null")
public class NullCloudProviderException extends RuntimeException {
public NullCloudProviderException(String string) {
super(string);
}
public NullCloudProviderException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Key can't be null")
public class NullKeyException extends RuntimeException {
public NullKeyException(String string) {
super(string);
}
public NullKeyException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "KeyId can't be null")
public class NullKeyIDException extends RuntimeException {
public NullKeyIDException(String string) {
super(string);
}
public NullKeyIDException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "User already exists")
public class PasswordNullException extends RuntimeException {
public PasswordNullException() {
super();
}
public PasswordNullException(String string) {
super(string);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Plan not found")
public class PlanNotFoundException extends RuntimeException {
public PlanNotFoundException(String string) {
super(string);
}
public PlanNotFoundException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public class UnauthorizedExeption extends RuntimeException {
public UnauthorizedExeption(String string) {
super(string);
}
public UnauthorizedExeption() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "User already exists")
public class UserExistsException extends RuntimeException {
public UserExistsException() {
super();
}
public UserExistsException(String string) {
super(string);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "User not found")
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String string) {
super(string);
}
public UserNotFoundException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "User name can't be null")
public class UserNullException extends RuntimeException {
public UserNullException(String massage) {
super(massage);
}
public UserNullException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "The maximum number of VMs has been reached")
public class VMLimitException extends RuntimeException {
public VMLimitException(String string) {
super(string);
}
public VMLimitException() {
super();
}
}
package nl.uva.sne.drip.api.rpc;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.uva.sne.drip.drip.commons.data.internal.Message;
import nl.uva.sne.drip.commons.utils.Converter;
import org.json.JSONException;
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
* @author S. Koulouzis
*/
public abstract class DRIPCaller implements AutoCloseable {
private final Connection connection;
private final Channel channel;
private final String replyQueueName;
private final String requestQeueName;
private final ObjectMapper mapper;
public DRIPCaller(String messageBrokerHost, String requestQeueName) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(messageBrokerHost);
factory.setPort(AMQP.PROTOCOL.PORT);
//factory.setUsername("guest");
//factory.setPassword("pass");
connection = factory.newConnection();
channel = connection.createChannel();
// create a single callback queue per client not per requests.
replyQueueName = channel.queueDeclare().getQueue();
this.requestQeueName = requestQeueName;
this.mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
}
/**
* @return the connection
*/
public Connection getConnection() {
return connection;
}
/**
* @return the channel
*/
public Channel getChannel() {
return channel;
}
/**
* @return the replyQueueName
*/
public String getReplyQueueName() {
return replyQueueName;
}
@Override
public void close() throws IOException, TimeoutException {
if (channel != null && channel.isOpen()) {
channel.close();
}
if (connection != null && connection.isOpen()) {
connection.close();
}
}
public Message call(Message r) throws IOException, TimeoutException, InterruptedException, JSONException {
String jsonInString = mapper.writeValueAsString(r);
//Build a correlation ID to distinguish responds
final String corrId = UUID.randomUUID().toString();
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
.correlationId(corrId)
.replyTo(getReplyQueueName())
.build();
Logger.getLogger(DRIPCaller.class.getName()).log(Level.INFO, "Sending: {0} to queue: {1}", new Object[]{jsonInString, requestQeueName});
getChannel().basicPublish("", requestQeueName, props, jsonInString.getBytes("UTF-8"));
final BlockingQueue<String> response = new ArrayBlockingQueue(1);
getChannel().basicConsume(getReplyQueueName(), true, new DefaultConsumer(getChannel()) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
if (properties.getCorrelationId().equals(corrId)) {
response.offer(new String(body, "UTF-8"));
}
}
});
String resp = response.take();
String clean = resp;
if (resp.contains("'null'")) {
clean = resp.replaceAll("'null'", "null").replaceAll("\'", "\"").replaceAll(" ", "");
}
if (clean.contains("\"value\":{\"")) {
return Converter.string2Message(clean);
}
if (clean.contains("\"null\"")) {
clean = clean.replaceAll("\"null\"", "null");
}
Logger.getLogger(DRIPCaller.class.getName()).log(Level.INFO, "Got: {0}", clean);
return mapper.readValue(clean, Message.class);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.rpc;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* @author S. Koulouzis
*/
public class DeployerCaller extends DRIPCaller {
private static final String REQUEST_QUEUE_NAME = "deployer_queue";
public DeployerCaller(String messageBrokerHost) throws IOException, TimeoutException {
super(messageBrokerHost, REQUEST_QUEUE_NAME);
}
}
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.rpc;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* @author S. Koulouzis.
*/
public class PlannerCaller extends DRIPCaller {
private static final String REQUEST_QUEUE_NAME = "planner";
public PlannerCaller(String messageBrokerHost) throws IOException, TimeoutException {
super(messageBrokerHost, REQUEST_QUEUE_NAME);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.rpc;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* @author S. Koulouzis
*/
public class ProvisionerCaller0 extends DRIPCaller {
private static final String REQUEST_QUEUE_NAME = "provisioner_queue_v0";
public ProvisionerCaller0(String messageBrokerHost) throws IOException, TimeoutException {
super(messageBrokerHost, REQUEST_QUEUE_NAME);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.rpc;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* @author S. Koulouzis
*/
public class ProvisionerCaller1 extends DRIPCaller {
private static final String REQUEST_QUEUE_NAME = "provisioner_queue_v1";
public ProvisionerCaller1(String messageBrokerHost) throws IOException, TimeoutException {
super(messageBrokerHost, REQUEST_QUEUE_NAME);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.rpc;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* @author S. Koulouzis
*/
public class TransformerCaller extends DRIPCaller {
private static final String REQUEST_QUEUE_NAME = "tosca_2_docker_compose_queue";
public TransformerCaller(String messageBrokerHost) throws IOException, TimeoutException {
super(messageBrokerHost, REQUEST_QUEUE_NAME);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import nl.uva.sne.drip.api.dao.AnsibleOutputDao;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.drip.commons.data.v1.external.KeyValueHolder;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import nl.uva.sne.drip.drip.commons.data.v1.external.ansible.AnsibleOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class AnsibleOutputService {
@Autowired
private AnsibleOutputDao ansibleOutputDao;
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public AnsibleOutput findOne(String id) {
AnsibleOutput ansibleOut = ansibleOutputDao.findOne(id);
if (ansibleOut == null) {
throw new NotFoundException();
}
return ansibleOut;
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<AnsibleOutput> findAll() {
return ansibleOutputDao.findAll();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public AnsibleOutput delete(String id) {
AnsibleOutput ansibleOut = ansibleOutputDao.findOne(id);
if (ansibleOut == null) {
throw new NotFoundException();
}
ansibleOutputDao.delete(ansibleOut);
return ansibleOut;
}
public AnsibleOutput save(AnsibleOutput ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return ansibleOutputDao.save(ownedObject);
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
ansibleOutputDao.deleteAll();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.util.List;
import nl.uva.sne.drip.api.dao.CloudCredentialsDao;
import nl.uva.sne.drip.api.exception.CloudCredentialsNotFoundException;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.drip.commons.data.v1.external.CloudCredentials;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class CloudCredentialsService {
@Autowired
private CloudCredentialsDao dao;
public CloudCredentials save(CloudCredentials ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return dao.save(ownedObject);
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public CloudCredentials findOne(String id) {
CloudCredentials creds = dao.findOne(id);
if (creds == null) {
throw new CloudCredentialsNotFoundException();
}
return creds;
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public CloudCredentials delete(String id) {
CloudCredentials creds = dao.findOne(id);
if (creds == null) {
throw new NotFoundException();
}
dao.delete(creds);
return creds;
}
// @PreAuthorize(" (hasRole('ROLE_ADMIN')) or (hasRole('ROLE_USER'))")
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
// @PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')")
public List<CloudCredentials> findAll() {
return dao.findAll();
}
@PostFilter("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
dao.deleteAll();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.drip.commons.data.v1.external.ConfigurationRepresentation;
import nl.uva.sne.drip.commons.utils.Converter;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import nl.uva.sne.drip.api.dao.ConfigurationDao;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class ConfigurationService {
@Autowired
private ConfigurationDao dao;
public String get(String id, String fromat) throws JSONException, NotFoundException {
ConfigurationRepresentation configuration = findOne(id);
if (configuration == null) {
throw new NotFoundException();
}
Map<String, Object> map = configuration.getKeyValue();
if (fromat != null && fromat.toLowerCase().equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = cleanup(ymlStr);
return ymlStr;
}
if (fromat != null && fromat.toLowerCase().equals("json")) {
String jsonStr = Converter.map2JsonString(map);
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
ymlStr = cleanup(ymlStr);
return ymlStr;
}
public String saveFile(MultipartFile file) throws IOException {
String originalFileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
String str = new String(bytes, "UTF-8");
return saveStringContents(str);
}
public String saveYamlString(String yamlString, String name) throws IOException {
yamlString = yamlString.replaceAll("\\.", "\uff0E");
Map<String, Object> map = Converter.ymlString2Map(yamlString);
ConfigurationRepresentation t = new ConfigurationRepresentation();
t.setKvMap(map);
save(t);
return t.getId();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public ConfigurationRepresentation delete(String id) {
ConfigurationRepresentation tr = dao.findOne(id);
if (tr == null) {
throw new NotFoundException();
}
dao.delete(tr);
return tr;
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<ConfigurationRepresentation> findAll() {
return dao.findAll();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public ConfigurationRepresentation findOne(String id) {
return dao.findOne(id);
}
private ConfigurationRepresentation save(ConfigurationRepresentation ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return dao.save(ownedObject);
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
dao.deleteAll();
}
public String saveStringContents(String yamlContents) throws IOException {
Map<String, Object> map = Converter.cleanStringContents(yamlContents, false);
ConfigurationRepresentation t = new ConfigurationRepresentation();
t.setKvMap(map);
save(t);
return t.getId();
}
private String cleanup(String ymlStr) {
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
ymlStr = ymlStr.replaceAll("\'---':", "---");
Pattern p = Pattern.compile("version:.*");
Matcher match = p.matcher(ymlStr);
while (match.find()) {
String line = match.group();
if (!line.contains("\"") && !line.contains("'")) {
String number = line.split(": ")[1];
ymlStr = ymlStr.replaceAll("version: " + number, "version: " + "\'" + number + "\'");
}
}
p = Pattern.compile("cpus:.*,");
match = p.matcher(ymlStr);
while (match.find()) {
String line = match.group();
if (!line.contains("\"") || line.contains("'")) {
String cpusNum = line.split(":")[1];
cpusNum = cpusNum.replaceAll(",", "").trim();
ymlStr = ymlStr.replaceAll("cpus: " + cpusNum, "cpus: " + '\'' + cpusNum + '\'');
}
}
p = Pattern.compile("memory:.*");
match = p.matcher(ymlStr);
while (match.find()) {
String line = match.group();
if (!line.contains("\"") && !line.contains("'")) {
String memory = line.split(":")[1];
memory = memory.replaceAll("}", "").trim();
ymlStr = ymlStr.replaceAll("memory: " + memory, "memory: " + '\'' + memory + '\'');
}
}
return ymlStr.replaceAll("'''", "'");
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.GetResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import nl.uva.sne.drip.drip.commons.data.v1.external.DRIPLogRecord;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class DRIPLogService {
@Value("${message.broker.host}")
private String messageBrokerHost;
private final String qeueName = "log_qeue";
private ObjectMapper mapper;
private ConnectionFactory factory;
public List<DRIPLogRecord> get() throws IOException, TimeoutException {
Channel channel = null;
if (factory == null) {
this.factory = new ConnectionFactory();
factory.setHost(messageBrokerHost);
factory.setPort(AMQP.PROTOCOL.PORT);
}
if (this.mapper == null) {
this.mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
}
try (Connection connection = factory.newConnection()) {
channel = connection.createChannel();
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
String qeueNameUser = qeueName + "_" + owner;
channel.queueDeclare(qeueNameUser, true, false, false, null);
GetResponse response = channel.basicGet(qeueNameUser, true);
List<DRIPLogRecord> logs = new ArrayList<>();
while (response != null) {
String message = new String(response.getBody(), "UTF-8");
response = channel.basicGet(qeueNameUser, true);
logs.add(mapper.readValue(message, DRIPLogRecord.class));
}
return logs;
}
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.util.List;
import nl.uva.sne.drip.api.dao.MonitorringMessageDao;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.drip.commons.data.v1.external.MonitorringMessage;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class MonitorringMessageService {
@Autowired
private MonitorringMessageDao dao;
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public MonitorringMessage delete(String id) {
MonitorringMessage tr = dao.findOne(id);
if (tr == null) {
throw new NotFoundException();
}
dao.delete(tr);
return tr;
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<MonitorringMessage> findAll() {
return dao.findAll();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public MonitorringMessage findOne(String id) {
return dao.findOne(id);
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
dao.deleteAll();
}
public MonitorringMessage save(MonitorringMessage ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return dao.save(ownedObject);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import nl.uva.sne.drip.commons.utils.DRIPLogHandler;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.uva.sne.drip.api.dao.PlanDao;
import nl.uva.sne.drip.api.exception.BadRequestException;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.rpc.DRIPCaller;
import nl.uva.sne.drip.api.rpc.PlannerCaller;
import nl.uva.sne.drip.drip.commons.data.internal.Message;
import nl.uva.sne.drip.drip.commons.data.internal.MessageParameter;
import nl.uva.sne.drip.drip.commons.data.v1.external.PlanResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.ToscaRepresentation;
import nl.uva.sne.drip.commons.utils.Converter;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.Base64;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class PlannerService {
@Autowired
private ToscaService toscaService;
@Autowired
private PlanDao planDao;
@Value("${message.broker.host}")
private String messageBrokerHost;
private final Logger logger;
@Autowired
public PlannerService(@Value("${message.broker.host}") String messageBrokerHost) throws IOException, TimeoutException {
logger = Logger.getLogger(PlannerService.class.getName());
logger.addHandler(new DRIPLogHandler(messageBrokerHost));
}
public PlanResponse getPlan(String toscaId, String cloudProvider, Integer maxVM) throws JSONException, UnsupportedEncodingException, IOException, TimeoutException, InterruptedException {
try (DRIPCaller planner = new PlannerCaller(messageBrokerHost)) {
Message plannerInvokationMessage = buildPlannerMessage(toscaId, maxVM);
logger.log(Level.INFO, "Calling planner");
plannerInvokationMessage.setOwner(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
Message plannerReturnedMessage = (planner.call(plannerInvokationMessage));
logger.log(Level.INFO, "Got response from planner");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
List<MessageParameter> messageParams = plannerReturnedMessage.getParameters();
String toscaPlan = null;
for (MessageParameter mp : messageParams) {
String value = mp.getValue();
toscaPlan = new String(Base64.getDecoder().decode(value));
logger.log(Level.INFO, "TOSCA Plann: {0}", toscaPlan);
}
Map<String, Object> toscaPlanMap = Converter.ymlString2Map(toscaPlan);
// SimplePlanContainer simplePlan = P2PConverter.transfer(toscaPlanMap, null, null, null);
PlanResponse planResponse = new PlanResponse();
planResponse.setToscaID(toscaId);
planResponse.setKvMap(toscaPlanMap);
save(planResponse);
logger.log(Level.INFO, "Plan saved");
return planResponse;
}
}
private Message buildPlannerMessage(String toscaId, Integer maxVM) throws JSONException, UnsupportedEncodingException {
ToscaRepresentation toscaRepresentation = toscaService.findOne(toscaId);
if (toscaRepresentation == null) {
throw new BadRequestException();
}
logger.log(Level.INFO, "Building invokation message for planner");
Map<String, Object> map = toscaRepresentation.getKeyValue();
String json = Converter.map2JsonString(map);
json = json.replaceAll("\\uff0E", ".");
byte[] bytes = json.getBytes();
Message invokationMessage = new Message();
List parameters = new ArrayList();
MessageParameter jsonArgument = new MessageParameter();
String charset = "UTF-8";
jsonArgument.setValue(new String(bytes, charset));
jsonArgument.setEncoding(charset);
jsonArgument.setName("tosca_input");
parameters.add(jsonArgument);
if (maxVM != null) {
MessageParameter maxVMsArgument = new MessageParameter();
maxVMsArgument.setValue(String.valueOf(maxVM));
maxVMsArgument.setEncoding(charset);
maxVMsArgument.setName("max_vm");
parameters.add(maxVMsArgument);
}
invokationMessage.setParameters(parameters);
invokationMessage.setCreationDate((System.currentTimeMillis()));
return invokationMessage;
}
public String get(String id, String fromat) throws JSONException {
PlanResponse plan = findOne(id);
if (plan == null) {
throw new NotFoundException();
}
Map<String, Object> map = plan.getKeyValue();
if (fromat != null && fromat.equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
if (fromat != null && fromat.equals("json")) {
String jsonStr = Converter.map2JsonString(map);
jsonStr = jsonStr.replaceAll("\\uff0E", ".");
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
public String getToscaID(String id) {
return findOne(id).getToscaID();
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<PlanResponse> findAll() {
List<PlanResponse> all = planDao.findAll();
return all;
}
public PlanResponse save(PlanResponse ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return planDao.save(ownedObject);
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public PlanResponse findOne(String id) {
PlanResponse plan = planDao.findOne(id);
if (plan == null) {
throw new NotFoundException();
}
return plan;
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public PlanResponse delete(String id) {
PlanResponse plan = planDao.findOne(id);
if (plan == null) {
throw new NotFoundException();
}
planDao.delete(plan);
return plan;
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
planDao.deleteAll();
}
public String saveStringContents(String ymlContents, Integer level, String name) {
Map<String, Object> map = Converter.cleanStringContents(ymlContents, true);
PlanResponse pr = new PlanResponse();
pr.setKvMap(map);
save(pr);
return pr.getId();
}
public boolean verify(String ymlContents) {
Map<String, Object> map = Converter.cleanStringContents(ymlContents, true);
ArrayList<Map> topologies = topologies = (ArrayList) map.get("topologies");
ArrayList<String> topologyNames = new ArrayList();
for (Map<String, Object> m : topologies) {
String topology = (String) m.get("topology");
topologyNames.add(topology);
}
for (String name : topologyNames) {
Map<String, Object> topology = (Map<String, Object>) map.get(name);
ArrayList<Map> components = (ArrayList<Map>) topology.get("components");
for (Map<String, Object> component : components) {
String nodeType = (String) component.get("nodeType");
String OStype = (String) component.get("OStype");
if (nodeType != null && OStype != null) {
return true;
}
}
}
return false;
}
// private String getBestCloudProvider() {
// List<CloudCredentials> creds = credentialService.findAll();
// return creds.get(0).getCloudProviderName().toUpperCase();
// }
// private String getBestDomain(String cloudProvider) {
// switch (cloudProvider.trim().toLowerCase()) {
// case "ec2":
// return "Frankfurt";
// case "egi":
// return "CESNET";
// case "exogeni":
// return "RENCI (Chapel Hill, NC USA) XO Rack";
// }
// return null;
// }
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import nl.uva.sne.drip.api.dao.PlanDao;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.rpc.PlannerCaller;
import nl.uva.sne.drip.drip.commons.data.internal.Message;
import nl.uva.sne.drip.drip.commons.data.internal.MessageParameter;
import nl.uva.sne.drip.drip.commons.data.v1.external.PlanResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.ToscaRepresentation;
import nl.uva.sne.drip.commons.utils.Converter;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
public class SimplePlannerService {
@Value("${message.broker.host}")
private String messageBrokerHost;
@Autowired
private ToscaService toscaService;
@Autowired
private PlanDao planDao;
public PlanResponse getPlan(String toscaId) throws JSONException, IOException, TimeoutException, InterruptedException {
ToscaRepresentation tosca = toscaService.findOne(toscaId);
Message plannerInvokationMessage = buildSimplePlannerMessage(tosca);
PlanResponse topLevel;
try (PlannerCaller planner = new PlannerCaller(messageBrokerHost)) {
Message plannerReturnedMessage = (planner.call(plannerInvokationMessage));
List<MessageParameter> planFiles = plannerReturnedMessage.getParameters();
topLevel = new PlanResponse();
// Set<String> ids = topLevel.getLoweLevelPlanIDs();
// if (ids == null) {
// ids = new HashSet<>();
// }
PlanResponse lowerLevelPlan = null;
for (MessageParameter p : planFiles) {
//Should have levels in attributes
Map<String, String> attributess = p.getAttributes();
if (attributess != null) {
attributess.get("level");
}
String originalFileName = p.getName();
String name = System.currentTimeMillis() + "_" + originalFileName;
if (originalFileName.equals("planner_output_all.yml")) {
// topLevel.setName(name);
// topLevel.setLevel(0);
topLevel.setKvMap(Converter.ymlString2Map(p.getValue()));
} else {
lowerLevelPlan = new PlanResponse();
// lowerLevelPlan.setName(name);
lowerLevelPlan.setKvMap(Converter.ymlString2Map(p.getValue()));
// lowerLevelPlan.setLevel(1);
planDao.save(lowerLevelPlan);
// ids.add(lowerLevelPlan.getId());
}
}
// topLevel.setLoweLevelPlansIDs(ids);
}
topLevel.setToscaID(toscaId);
planDao.save(topLevel);
return topLevel;
}
private Message buildSimplePlannerMessage(ToscaRepresentation t2) throws JSONException, UnsupportedEncodingException, IOException {
if (t2 == null) {
throw new NotFoundException();
}
Map<String, Object> map = t2.getKeyValue();
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
byte[] bytes = ymlStr.getBytes();
Message invokationMessage = new Message();
List parameters = new ArrayList();
MessageParameter fileArgument = new MessageParameter();
String charset = "UTF-8";
fileArgument.setValue(new String(bytes, charset));
fileArgument.setEncoding(charset);
fileArgument.setName("input");
parameters.add(fileArgument);
fileArgument = new MessageParameter();
bytes = Files.readAllBytes(Paths.get(System.getProperty("user.home") + File.separator + "Downloads/DRIP/example_a.yml"));
fileArgument.setValue(new String(bytes, charset));
fileArgument.setEncoding(charset);
fileArgument.setName("example");
parameters.add(fileArgument);
invokationMessage.setParameters(parameters);
invokationMessage.setCreationDate((System.currentTimeMillis()));
return invokationMessage;
}
public String get(String id, String fromat) throws JSONException {
PlanResponse plan = planDao.findOne(id);
if (plan == null) {
throw new NotFoundException();
}
Map<String, Object> map = plan.getKeyValue();
// Set<String> ids = plan.getLoweLevelPlanIDs();
// for (String lowID : ids) {
// Map<String, Object> lowLevelMap = planDao.findOne(lowID).getKeyValue();
// map.putAll(lowLevelMap);
// }
if (fromat != null && fromat.equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
if (fromat != null && fromat.equals("json")) {
String jsonStr = Converter.map2JsonString(map);
jsonStr = jsonStr.replaceAll("\\uff0E", ".");
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
public PlanDao getDao() {
return planDao;
}
public String getToscaID(String id) {
return planDao.findOne(id).getToscaID();
}
public List<PlanResponse> findAll() {
List<PlanResponse> all = planDao.findAll();
// List<PlanResponse> topLevel = new ArrayList<>();
// for (PlanResponse p : all) {
// if (p.getLevel() == 0) {
// topLevel.add(p);
// }
// }
return all;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import nl.uva.sne.drip.api.dao.ToscaDao;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.rpc.DRIPCaller;
import nl.uva.sne.drip.api.rpc.TransformerCaller;
import nl.uva.sne.drip.drip.commons.data.v1.external.ToscaRepresentation;
import nl.uva.sne.drip.commons.utils.Converter;
import nl.uva.sne.drip.drip.commons.data.internal.Message;
import nl.uva.sne.drip.drip.commons.data.internal.MessageParameter;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class ToscaService {
@Autowired
private ToscaDao dao;
@Value("${message.broker.host}")
private String messageBrokerHost;
public String get(Map<String, Object> map, String fromat) throws JSONException {
if (fromat != null && fromat.equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
if (fromat != null && fromat.equals("json")) {
String jsonStr = Converter.map2JsonString(map);
jsonStr = jsonStr.replaceAll("\\uff0E", ".");
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
public String get(String id, String fromat) throws JSONException {
ToscaRepresentation tosca = findOne(id);
if (tosca == null) {
throw new NotFoundException();
}
Map<String, Object> map = tosca.getKeyValue();
if (fromat != null && fromat.equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
if (fromat != null && fromat.equals("json")) {
String jsonStr = Converter.map2JsonString(map);
jsonStr = jsonStr.replaceAll("\\uff0E", ".");
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
public String saveFile(MultipartFile file) throws IOException {
String originalFileName = file.getOriginalFilename();
String name = System.currentTimeMillis() + "_" + originalFileName;
byte[] bytes = file.getBytes();
String str = new String(bytes, "UTF-8");
return saveStringContents(str, name);
}
public String saveYamlString(String yamlString, String name) throws IOException {
if (name == null) {
name = System.currentTimeMillis() + "_" + "tosca.yaml";
}
yamlString = yamlString.replaceAll("\\.", "\uff0E");
Map<String, Object> map = Converter.ymlString2Map(yamlString);
ToscaRepresentation t = new ToscaRepresentation();
t.setName(name);
t.setKvMap(map);
save(t);
return t.getId();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public ToscaRepresentation delete(String id) {
ToscaRepresentation tr = dao.findOne(id);
dao.delete(tr);
return tr;
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<ToscaRepresentation> findAll() {
return dao.findAll();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public ToscaRepresentation findOne(String id) {
ToscaRepresentation tr = dao.findOne(id);
return tr;
}
private ToscaRepresentation save(ToscaRepresentation ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return dao.save(ownedObject);
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
dao.deleteAll();
}
public String saveStringContents(String toscaContents, String name) throws IOException {
Map<String, Object> map = Converter.cleanStringContents(toscaContents, true);
ToscaRepresentation t = new ToscaRepresentation();
t.setName(name);
t.setKvMap(map);
save(t);
return t.getId();
}
public String transform(String id, String target) throws JSONException, IOException, TimeoutException, InterruptedException {
ToscaRepresentation toscaRep = findOne(id);
switch (target) {
case "docker_compose":
return getDockerCompose(toscaRep);
}
return null;
}
private String getDockerCompose(ToscaRepresentation toscaRep) throws IOException, TimeoutException, JSONException, InterruptedException {
String dockerCompose;
try (DRIPCaller transformer = new TransformerCaller(messageBrokerHost);) {
Message transformerInvokationMessage = buildDockerComposeMessage(toscaRep);
transformerInvokationMessage.setOwner(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
Message response = (transformer.call(transformerInvokationMessage));
dockerCompose = response.getParameters().get(0).getValue();
}
return dockerCompose;
}
private Message buildDockerComposeMessage(ToscaRepresentation toscaRep) throws JSONException {
Message deployInvokationMessage = new Message();
List<MessageParameter> parameters = new ArrayList<>();
MessageParameter messageParam = new MessageParameter();
messageParam.setName(toscaRep.getName());
messageParam.setValue(get(toscaRep.getKeyValue(), "yml"));
parameters.add(messageParam);
deployInvokationMessage.setParameters(parameters);
deployInvokationMessage.setCreationDate(System.currentTimeMillis());
return deployInvokationMessage;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.uva.sne.drip.api.dao.UserDao;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
public class UserService implements UserDetailsService {
public static final String ADMIN = "ADMIN";
public static final String USER = "USER";
@Autowired
private UserDao dao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
User user = dao.findByUsername(username);
return user;
} catch (Exception ex) {
Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public User save(User user) {
return dao.save(user);
}
public User findOne(String id) {
return dao.findOne(id);
}
public void delete(User user) {
dao.delete(user);
}
public List<User> findAll() {
return dao.findAll();
}
public void deleteAll() {
dao.deleteAll();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.service.AnsibleOutputService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v1.external.ansible.AnsibleOutput;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
/**
* This controller is responsible for showing the output from ansible executions
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/deployer/ansible")
@Controller
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class AnsibleOutputController {
@Autowired
private AnsibleOutputService ansibleOutputService;
/**
* Returns an AnsibleOutput.
*
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "AnsibleOutput not found"),
@ResponseCode(code = 200, condition = "AnsibleOutput exists")
})
public @ResponseBody
AnsibleOutput get(@PathVariable("id") String id) {
AnsibleOutput resp = ansibleOutputService.findOne(id);
if (resp == null) {
throw new NotFoundException();
}
return resp;
}
/**
* Returns the ids of stored objects. Empty list if non stored
*
* @return
*/
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful query")
})
public @ResponseBody
List<String> getIds() {
List<AnsibleOutput> all = ansibleOutputService.findAll();
List<String> ids = new ArrayList<>(all.size());
for (AnsibleOutput pi : all) {
ids.add(pi.getId());
}
return ids;
}
/**
* Deletes object
*
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful delete"),
@ResponseCode(code = 404, condition = "Non existing id")
})
public @ResponseBody
String delete(@PathVariable("id") String id) {
AnsibleOutput Key = ansibleOutputService.findOne(id);
if (Key != null) {
ansibleOutputService.delete(id);
return "Deleted : " + id;
}
throw new NotFoundException();
}
/**
* Deletes all entries. Use with caution !
*
* @return
*/
@RequestMapping(value = "/all", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful delete")
})
public @ResponseBody
String deleteAll() {
ansibleOutputService.deleteAll();
return "Done";
}
}
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.core.MediaType;
import nl.uva.sne.drip.drip.commons.data.v1.external.CloudCredentials;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import nl.uva.sne.drip.api.exception.BadRequestException;
import nl.uva.sne.drip.api.exception.KeyException;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.exception.NullCloudProviderException;
import nl.uva.sne.drip.api.exception.NullKeyException;
import nl.uva.sne.drip.api.service.CloudCredentialsService;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v1.external.Key;
import nl.uva.sne.drip.drip.commons.data.v1.external.KeyPair;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
/**
*
* This controller is responsible for handling CloudCredentials.
* CloudCredentials are a representation of the credentials that are used by the
* provisoner to request for resources (VMs)
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/credentials/cloud")
@Component
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class CloudCredentialsController {
@Autowired
private CloudCredentialsService cloudCredentialsService;
/**
* Post the cloud credentials.
*
* @param cloudCredentials
* @return the CloudCredentials id
*/
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "Key can't be empty")
,
@ResponseCode(code = 404, condition = "Cloud provider's name can't be empty")
,
@ResponseCode(code = 200, condition = "At least one key ID is posted")
})
public @ResponseBody
String postCredentials(@RequestBody CloudCredentials cloudCredentials) {
if (cloudCredentials.getSecretKey() == null || cloudCredentials.getSecretKey().length() < 1) {
throw new NullKeyException();
}
if (cloudCredentials.getCloudProviderName() == null || cloudCredentials.getCloudProviderName().length() < 1) {
throw new NullCloudProviderException();
}
cloudCredentials = cloudCredentialsService.save(cloudCredentials);
return cloudCredentials.getId();
}
/**
* Upload the login keys for a cloud provider. The cloud credentials have to
* be created
*
* @param file
* @param id
* @return the CloudCredentials id
* @throws java.lang.Exception
*/
@RequestMapping(value = "/upload/{id}", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "Credential not found")
,
@ResponseCode(code = 400, condition = "Did not upload file")
,
@ResponseCode(code = 200, condition = "Key added to credential")
})
public @ResponseBody
String addLogineKey(@RequestParam("file") MultipartFile file, @PathVariable("id") String id) throws Exception {
try {
CloudCredentials cloudCredentials = cloudCredentialsService.findOne(id);
if (cloudCredentials == null) {
throw new NotFoundException();
}
if (file.isEmpty()) {
throw new BadRequestException("Must uplaod a file");
}
String originalFileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
// List<String> loginKeyIDs = cloudCredentials.getkeyPairIDs();
// if (loginKeyIDs == null) {
// loginKeyIDs = new ArrayList<>();
// }
Key key = new Key();
key.setKey(new String(bytes, "UTF-8"));
if (cloudCredentials.getCloudProviderName().toLowerCase().equals("ec2")) {
Map<String, String> attributes = new HashMap<>();
attributes.put("domain_name", FilenameUtils.removeExtension(originalFileName));
key.setAttributes(attributes);
KeyPair pair = new KeyPair();
pair.setPrivateKey(key);
}
if (cloudCredentials.getCloudProviderName().toLowerCase().equals("egi")) {
cloudCredentials.setSecretKey(new String(bytes, "UTF-8"));
}
cloudCredentials = cloudCredentialsService.save(cloudCredentials);
return cloudCredentials.getId();
} catch (IOException | KeyException ex) {
Logger.getLogger(CloudCredentialsController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Get the cloud credentials
*
* @param id the id of the cloud credentials
* @return the cloud credentials
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "Credential not found")
,
@ResponseCode(code = 200, condition = "Credential exists")
})
public @ResponseBody
CloudCredentials get(@PathVariable("id") String id) {
CloudCredentials cc = cloudCredentialsService.findOne(id);
if (cc == null) {
throw new NotFoundException();
}
return cc;
}
/**
* Delete the cloud credentials
*
* @param id the id of the cloud credentials
* @return the id of the cloud credentials
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Credential exists")
})
public @ResponseBody
String delete(@PathVariable("id") String id) {
cloudCredentialsService.delete(id);
return "Deleted :" + id;
}
/**
* Deletes all credentials. Use with caution !
*
* @return
*/
@RequestMapping(value = "/all", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Credentiasl exist")
})
public @ResponseBody
String deleteAll() {
cloudCredentialsService.deleteAll();
return "Done";
}
/**
* Gets all the IDs of the stored cloud credentials
*
* @return a list of stored IDs
*/
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Credentials exist")
})
public @ResponseBody
List<String> getIds() {
List<CloudCredentials> all = cloudCredentialsService.findAll();
List<String> ids = new ArrayList<>();
for (CloudCredentials tr : all) {
ids.add(tr.getId());
}
return ids;
}
@RequestMapping(value = "/sample", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
CloudCredentials getSample() {
CloudCredentials cloudCredentials = new CloudCredentials();
cloudCredentials.setAccessKeyId("AKIAITWERHZUQ6M7YBSQ");
cloudCredentials.setCloudProviderName("egi");
cloudCredentials.setSecretKey("6J7uo99ifrff45sa6Gsy5vgb3b3ewdsdtwY6hBxtYt9y");
List<String> keyIDs = new ArrayList<>();
keyIDs.add("58da4c91f7b43a3282cacdbb");
keyIDs.add("58da4d2af7b43a3282cacdbd");
Map<String, Object> attributes = new HashMap<>();
attributes.put("myProxyEndpoint", "myproxy.egee.host.com");
attributes.put("trustedCertificatesURL", "https://dist.eugridpma.info/distribution/igtf/current/accredited/igtf-preinstalled-bundle-classic.tar.gz");
cloudCredentials.setAttributes(attributes);
return cloudCredentials;
}
}
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import nl.uva.sne.drip.drip.commons.data.v1.external.ConfigurationRepresentation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.PathVariable;
import nl.uva.sne.drip.api.exception.BadRequestException;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.service.ConfigurationService;
import nl.uva.sne.drip.api.service.UserService;
import org.springframework.web.bind.annotation.RequestBody;
/**
* This controller is responsible for managing deployment configurations used
* by the deployer. Currently docker-compose.yml and ansible playbooks are supported.
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/deployer/configuration")
@Component
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class ConfigurationController {
@Autowired
private ConfigurationService configurationService;
/**
* Post a deployment configuration.
*
* @param yamlContents
* @return
*/
@RequestMapping(value = "/post", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful post"),
@ResponseCode(code = 400, condition = "contents are not valid (e.g. not a yaml format)")
})
public @ResponseBody
String post(@RequestBody String yamlContents) {
try {
return configurationService.saveStringContents(yamlContents);
} catch (IOException ex) {
throw new BadRequestException("Not valid contents");
}
}
/**
* Uploads and stores a configuration file
*
* @param file. The configuration description file
* @return the ID of the configuration description
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful upload"),
@ResponseCode(code = 400, condition = "Didn't upload (multipart) file or "
+ "contents are not valid (e.g. not a yaml format)")
})
public @ResponseBody
String configurationUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
throw new BadRequestException("Must uplaod a file");
}
try {
return configurationService.saveFile(file);
} catch (IOException | IllegalStateException ex) {
throw new BadRequestException("Not valid contents");
}
}
/**
* Gets the configuration contents.
*
* @param id the ID configuration contents.
* @param format. the format to display the configuration description.
* @return the configuration contents.
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, params = {"format"})
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Object found"),
@ResponseCode(code = 400, condition = "contents are not valid (e.g. not a yaml format)"),
@ResponseCode(code = 404, condition = "Object not found")
})
public @ResponseBody
String get(@PathVariable("id") String id, @RequestParam(value = "format") String format) {
try {
return configurationService.get(id, format);
} catch (JSONException | NotFoundException ex) {
throw new BadRequestException("Not valid contents");
}
}
/**
* Deletes the configuration
*
* @param id. The ID of configuration
* @return The ID of the deleted configuration
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful delete"),
@ResponseCode(code = 404, condition = "Object not found")
})
public @ResponseBody
String delete(@PathVariable("id") String id) {
try {
configurationService.delete(id);
} catch (NotFoundException ex) {
throw ex;
}
return "Deleted : " + id;
}
/**
* Gets the IDs of all the stored configuration
*
* @return a list of all the IDs
*/
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful query")
})
public @ResponseBody
List<String> getIds() {
List<ConfigurationRepresentation> all = configurationService.findAll();
List<String> ids = new ArrayList<>();
for (ConfigurationRepresentation tr : all) {
ids.add(tr.getId());
}
return ids;
}
/**
* Deletes all entries. Use with caution !
*
* @return
*/
@RequestMapping(value = "/all", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful delete")
})
public @ResponseBody
String deleteAll() {
configurationService.deleteAll();
return "Done";
}
}
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import nl.uva.sne.drip.api.service.DRIPLogService;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v1.external.DRIPLogRecord;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
/**
* This controller is responsible for storing TOSCA descriptions that can be
* used by the planner.
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/logs")
@Component
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class LogController {
@Autowired
private DRIPLogService logService;
@RequestMapping(method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
List<DRIPLogRecord> get() {
try {
return logService.get();
} catch (IOException | TimeoutException ex) {
Logger.getLogger(LogController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
// @RequestMapping(method = RequestMethod.GET, value = "/ll")
// @RolesAllowed({UserService.USER, UserService.ADMIN})
// public @ResponseBody
// ResponseBodyEmitter streamLogs() {
//
// final ResponseBodyEmitter emitter = new ResponseBodyEmitter();
// ExecutorService service = Executors.newSingleThreadExecutor();
// service.execute(new Runnable() {
// @Override
// public void run() {
// int i = 0;
// while (true) {
// try {
// i++;
// emitter.send(i + " - ", MediaType.TEXT_PLAIN);
// Thread.sleep(10);
// } catch (InterruptedException | IOException ex) {
// Logger.getLogger(LogController.class.getName()).log(Level.SEVERE, null, ex);
// emitter.completeWithError(ex);
// }
//
// }
//// emitter.complete();
// }
// });
//
// return emitter;
// }
@RequestMapping(method = RequestMethod.GET, value = "/ll")
@RolesAllowed({UserService.USER, UserService.ADMIN})
public StreamingResponseBody streamLogs() {
return new StreamingResponseBody() {
@Override
public void writeTo(OutputStream out) throws IOException {
ObjectMapper mapper = new ObjectMapper();
while (true) {
try {
List<DRIPLogRecord> logs = logService.get();
for (DRIPLogRecord log : logs) {
out.write(mapper.writeValueAsBytes(log));
out.write("\n".getBytes());
Thread.sleep(10);
}
Thread.sleep(2000);
} catch (InterruptedException | TimeoutException ex) {
Logger.getLogger(LogController.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.flush();
}
}
}
};
}
}
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import nl.uva.sne.drip.drip.commons.data.v1.external.GrafanaMonitorringMessage;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import nl.uva.sne.drip.api.service.MonitorringMessageService;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v1.external.MonitorringMessage;
import org.springframework.web.bind.annotation.RequestBody;
/**
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/monitoring_message")
@Component
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class MonitorringMessageController {
@Autowired
private MonitorringMessageService monitorringMessageService;
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String post(@RequestBody MonitorringMessage message) {
return monitorringMessageService.save(message).getId();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
MonitorringMessage get(@PathVariable("id") String id) {
return monitorringMessageService.findOne(id);
}
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
List<String> getIds() {
List<MonitorringMessage> all = monitorringMessageService.findAll();
List<String> ids = new ArrayList<>();
for (MonitorringMessage tr : all) {
ids.add(tr.getId());
}
return ids;
}
}
This diff is collapsed.
This diff is collapsed.
message.broker.host=127.0.0.1
db.host=127.0.0.1
db.name=drip
db.username=drip-user
db.password=drip-pass
This diff is collapsed.
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/drip-api"/>
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment