Commit 18fb961e authored by Spiros Koulouzis's avatar Spiros Koulouzis

replace services

parent 57a8fd69
<?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.*" />
<include pattern="nl.uva.sne.drip.api.v0.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.*"/>
<api-import pattern="nl.uva.sne.drip.drip.commons.data.v0.external.*"/>
<modules>
<swagger disabled="true" />
</modules>
</enunciate>
...@@ -13,8 +13,6 @@ You can copy and paste the single properties, into the pom.xml file and the IDE ...@@ -13,8 +13,6 @@ You can copy and paste the single properties, into the pom.xml file and the IDE
That way multiple projects can share the same settings (useful for formatting rules for example). 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. 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>
<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>
<netbeans.hint.licensePath>${project.basedir}/../licenseheader.txt</netbeans.hint.licensePath> <netbeans.hint.licensePath>${project.basedir}/../licenseheader.txt</netbeans.hint.licensePath>
</properties> </properties>
</project-shared-configuration> </project-shared-configuration>
This diff is collapsed.
/*
* 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.ansible.BenchmarkResult;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface BenchmarkResultDao extends MongoRepository<BenchmarkResult, 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.Script;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface ScriptDao extends MongoRepository<Script, 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.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;
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}", jsonInString);
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_queue";
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.BenchmarkResultDao;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import nl.uva.sne.drip.drip.commons.data.v1.external.ansible.BenchmarkResult;
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 BenchmarkResultService {
@Autowired
private BenchmarkResultDao benchmarkResultDao;
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public BenchmarkResult findOne(String id) {
BenchmarkResult benchmarkResult = benchmarkResultDao.findOne(id);
if (benchmarkResult == null) {
throw new NotFoundException();
}
return benchmarkResult;
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<BenchmarkResult> findAll() {
return benchmarkResultDao.findAll();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public BenchmarkResult delete(String id) {
BenchmarkResult benchmarkResult = benchmarkResultDao.findOne(id);
if (benchmarkResult == null) {
throw new NotFoundException();
}
benchmarkResultDao.delete(benchmarkResult);
return benchmarkResult;
}
public BenchmarkResult save(BenchmarkResult ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return benchmarkResultDao.save(ownedObject);
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
benchmarkResultDao.deleteAll();
}
public List<BenchmarkResult> findBySysbench() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.s
}
}
/*
* 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.exception.NotFoundException;
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.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import nl.uva.sne.drip.api.dao.KeyPairDao;
import nl.uva.sne.drip.drip.commons.data.v1.external.KeyPair;
/**
*
* @author S. Koulouzis
*/
@Service
public class KeyPairService {
@Autowired
KeyPairDao dao;
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<KeyPair> findAll() {
return dao.findAll();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public KeyPair findOne(String id) {
KeyPair key = dao.findOne(id);
if (key == null) {
throw new NotFoundException();
}
return key;
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public KeyPair delete(KeyPair k) {
k = dao.findOne(k.getId());
dao.delete(k);
return k;
}
public KeyPair save(KeyPair 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();
}
}
/*
* 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 java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import nl.uva.sne.drip.api.dao.ScriptDao;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.drip.commons.data.v1.external.Script;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.core.context.SecurityContextHolder;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class ScriptService {
@Autowired
ScriptDao dao;
public Script save(Script 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 Script findOne(String id) {
Script script = dao.findOne(id);
if (script == null) {
throw new NotFoundException();
}
return script;
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public Script delete(String id) {
Script script = dao.findOne(id);
if (script == null) {
throw new NotFoundException();
}
dao.delete(script);
return script;
}
// @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<Script> 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.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.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
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 topLevel;
}
}
/*
* 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.
*
* 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.v0.rest;
import javax.annotation.security.RolesAllowed;
import nl.uva.sne.drip.api.service.ProvisionService;
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.RestController;
import nl.uva.sne.drip.api.service.ScriptService;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v0.external.ConfScript;
import nl.uva.sne.drip.drip.commons.data.v1.external.ProvisionResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.Script;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* This controller is responsible for handling user scripts. These user can be
* used by the provisioner to run on the created VMs.
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v0.0/switch/provision")
@Component
@Deprecated
public class UserScriptController0 {
@Autowired
private ScriptService scriptService;
@RequestMapping(value = "/confscript", method = RequestMethod.POST, consumes = MediaType.TEXT_XML_VALUE)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String uploadUserScript(@RequestBody ConfScript confScript) {
Script script = new Script();
script.setContents(confScript.script);
script = scriptService.save(script);
return "Success: script for GUI is uploaded: " + script.getId();
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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