Commit 771261f9 authored by Spiros Koulouzis's avatar Spiros Koulouzis

merge them back

parent 14c0a3eb
package nl.uva.sne.drip.configuration;
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.threeten.bp.Instant;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZonedDateTime;
@Configuration
public class JacksonConfiguration {
@Bean
@ConditionalOnMissingBean(ThreeTenModule.class)
ThreeTenModule threeTenModule() {
ThreeTenModule module = new ThreeTenModule();
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
return module;
}
}
......@@ -115,11 +115,30 @@
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.fridujo</groupId>
<artifactId>rabbitmq-mock</artifactId>
<version>1.0.12</version>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>nl.uva.sne.drip</groupId>
<artifactId>drip-manager-services</artifactId>
<version>3.0.0</version>
<type>jar</type>
</dependency>
</dependency> -->
</dependencies>
</project>
package nl.uva.sne.drip;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Home redirection to swagger api documentation
*/
@Controller
public class HomeController {
@RequestMapping(value = "/")
public String index() {
System.out.println("swagger-ui.html");
return "redirect:swagger-ui.html";
}
}
package nl.uva.sne.drip;
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.threeten.bp.Instant;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZonedDateTime;
@Configuration
public class JacksonConfiguration {
@Bean
@ConditionalOnMissingBean(ThreeTenModule.class)
ThreeTenModule threeTenModule() {
ThreeTenModule module = new ThreeTenModule();
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
return module;
}
}
package nl.uva.sne.drip;
import nl.uva.sne.drip.dao.ToscaTemplateDAO;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages = {"nl.uva.sne.drip", "nl.uva.sne.drip.api", "nl.uva.sne.drip"})
@PropertySources({
@PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = true)
})
@EnableMongoRepositories(basePackageClasses = {ToscaTemplateDAO.class})
@ComponentScan(basePackages = {"nl.uva.sne.drip", "nl.uva.sne.drip.api",
"nl.uva.sne.drip.configuration", "nl.uva.sne.drip.dao", "nl.uva.sne.drip.service"})
public class Swagger2SpringBoot implements CommandLineRunner {
@Override
......
......@@ -75,8 +75,6 @@ public class ToscaTemplateApiController implements ToscaTemplateApi {
} catch (IOException e) {
log.error("Couldn't serialize response for content type ", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (ApiException ex) {
return ApiException.handleExceptions(ex);
}
}
......@@ -93,8 +91,6 @@ public class ToscaTemplateApiController implements ToscaTemplateApi {
} catch (IOException e) {
log.error("Couldn't serialize response for content type application/json", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (ApiException ex) {
return ApiException.handleExceptions(ex);
}
}
......
package nl.uva.sne.drip;
package nl.uva.sne.drip.configuration;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonTokenId;
......@@ -27,6 +27,7 @@ import java.math.BigDecimal;
* Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format.
*
* @author Nick Williams
* @param <T>
*/
public class CustomInstantDeserializer<T extends Temporal>
extends ThreeTenDateTimeDeserializerBase<T> {
......
/*
* 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.configuration;
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:application.properties", ignoreResourceNotFound = true)
})
@ComponentScan(basePackages = {"nl.uva.sne.drip", "nl.uva.sne.drip.api", "nl.uva.sne.drip.configuration", "nl.uva.sne.drip.dao", "nl.uva.sne.drip.model", "nl.uva.sne.drip.service"})
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
protected String getMappingBasePackage() {
return "nl.uva.sne.drip";
}
@Override
public MongoClient mongoClient() {
return new MongoClient(dbHost, 27017);
}
}
/*
* 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.configuration;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
/**
*
* @author S. Koulouzis
*/
@Configuration
public class RPCCallersConfig {
@Autowired
ConnectionFactory factory;
}
/*
* 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.configuration;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
*
* @author S. Koulouzis
*/
@Configuration
public class RabbitMQConfig {
@Value("${message.broker.host}")
private String messageBrokerHost;
@Value("${message.broker.username}")
private String messageBrokerUsername;
@Value("${message.broker.password}")
private String messageBrokerPassword;
@Bean
public ConnectionFactory connectionFactory() {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost(messageBrokerHost);
connectionFactory.setUsername(messageBrokerUsername);
connectionFactory.setPassword(messageBrokerPassword);
return connectionFactory;
}
}
package nl.uva.sne.drip;
package nl.uva.sne.drip.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
......@@ -10,29 +10,27 @@ import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-12-06T13:31:49.386Z")
@Configuration
public class SwaggerDocumentationConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("CONF")
.description("CONF allows application developers to seamlessly plan a customized virtual infrastructure based on application level constraints on QoS and resource budgets, provisioning the virtual infrastructure, deploy application components onto the virtual infrastructure, and start execution on demand using TOSCA.")
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.termsOfServiceUrl("")
.version("3.0.0")
.contact(new Contact("", "", "z.zhao@uva.nl"))
.build();
.title("DRIP")
.description("The Dynamic Real-time infrastructure planner (DRIP) allows application developers to seamlessly plan a customized virtual infrastructure based on application level constraints on QoS and resource budgets, provisioning the virtual infrastructure, deploy application components onto the virtual infrastructure, and start execution on demand using TOSCA.")
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.termsOfServiceUrl("")
.version("3.0.0")
.contact(new Contact("","", "z.zhao@uva.nl"))
.build();
}
@Bean
public Docket customImplementation() {
public Docket customImplementation(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("nl.uva.sne.drip.api"))
.build()
.apis(RequestHandlerSelectors.basePackage("nl.uva.sne.drip.api"))
.build()
.directModelSubstitute(org.threeten.bp.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(org.threeten.bp.OffsetDateTime.class, java.util.Date.class)
.apiInfo(apiInfo());
......
/*
* 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.dao;
import nl.uva.sne.drip.model.Credentials;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
/**
*
* @author S. Koulouzis
*/
@Repository
public interface CredentialDAO extends MongoRepository<Credentials, String> {
}
/*
* 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.dao;
import nl.uva.sne.drip.model.ToscaTemplate;
import nl.uva.sne.drip.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
/**
*
* @author S. Koulouzis
*/
@Repository
public interface ToscaTemplateDAO extends MongoRepository<ToscaTemplate, String> {
}
package nl.uva.sne.drip.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.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/*
* Copyright 2019 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.
*/
/**
*
* @author S. Koulouzis
*/
@Service
public class DRIPCaller implements AutoCloseable {
private final Connection connection;
private final Channel channel;
private final String replyQueueName;
private String requestQeueName;
private final ObjectMapper mapper;
public DRIPCaller(ConnectionFactory factory) throws IOException, TimeoutException {
// factory.setHost(messageBrokerHost);
// factory.setPort(AMQP.PROTOCOL.PORT);
// factory.setUsername(username);
// factory.setPassword(password);
connection = factory.newConnection();
channel = connection.createChannel();
// create a single callback queue per client not per requests.
replyQueueName = channel.queueDeclare().getQueue();
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 {
String jsonInString = mapper.writeValueAsString(r);
//Build a correlation ID to distinguish responds
final String corrId = UUID.randomUUID().toString();
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
.correlationId(corrId)
.replyTo(getReplyQueueName())
.build();
Logger.getLogger(DRIPCaller.class.getName()).log(Level.INFO, "Sending: {0} to queue: {1}", new Object[]{jsonInString, getRequestQeueName()});
getChannel().basicPublish("", getRequestQeueName(), 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();
Logger.getLogger(DRIPCaller.class.getName()).log(Level.INFO, "Got: {0}", resp);
return mapper.readValue(resp, Message.class);
}
/**
* @return the requestQeueName
*/
public String getRequestQeueName() {
return requestQeueName;
}
/**
* @param requestQeueName the requestQeueName to set
*/
public void setRequestQeueName(String requestQeueName) {
this.requestQeueName = requestQeueName;
}
}
/*
* 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.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import nl.uva.sne.drip.dao.CredentialDAO;
import nl.uva.sne.drip.model.Credentials;
/**
*
* @author S. Koulouzis
*/
@Service
public class CredentialService {
@Autowired
private CredentialDAO dao;
public String save(Credentials document) {
dao.save(document);
return document.getId();
}
public Credentials findByID(String id) throws JsonProcessingException {
Credentials credentials = dao.findById(id).get();
return credentials;
}
public void deleteByID(String id) {
dao.deleteById(id);
}
public List<String> getAllIds() {
List<String> allIds = new ArrayList<>();
List<Credentials> all = dao.findAll();
for (Credentials tt : all) {
allIds.add(tt.getId());
}
return allIds;
}
void deleteAll() {
dao.deleteAll();
}
}
/*
* 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.service;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.uva.sne.drip.model.Message;
import nl.uva.sne.drip.model.ToscaTemplate;
import nl.uva.sne.drip.rpc.DRIPCaller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
public class DRIPService {
@Autowired
private ToscaTemplateService toscaTemplateService;
@Autowired
DRIPCaller caller;
private String requestQeueName;
public String execute(String id) {
try {
String ymlToscaTemplate = toscaTemplateService.findByID(id);
ToscaTemplate toscaTemplate = toscaTemplateService.getYaml2ToscaTemplate(ymlToscaTemplate);
Message message = new Message();
message.setCreationDate(System.currentTimeMillis());
message.setToscaTemplate(toscaTemplate);
caller.setRequestQeueName(requestQeueName);
Message plannerResponse = caller.call(message);
ToscaTemplate plannedToscaTemplate = plannerResponse.getToscaTemplate();
return toscaTemplateService.save(plannedToscaTemplate);
} catch (IOException | TimeoutException | InterruptedException ex) {
Logger.getLogger(DRIPService.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
caller.close();
} catch (IOException | TimeoutException ex) {
Logger.getLogger(DRIPService.class.getName()).log(Level.SEVERE, null, ex);
}
}
return null;
}
/**
* @return the requestQeueName
*/
public String getRequestQeueName() {
return requestQeueName;
}
/**
* @param requestQeueName the requestQeueName to set
*/
public void setRequestQeueName(String requestQeueName) {
this.requestQeueName = requestQeueName;
}
}
/*
* 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.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator.Feature;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import nl.uva.sne.drip.dao.ToscaTemplateDAO;
import nl.uva.sne.drip.model.ToscaTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
*
* @author S. Koulouzis
*/
@Service
public class ToscaTemplateService {
private final ObjectMapper objectMapper;
@org.springframework.beans.factory.annotation.Autowired
public ToscaTemplateService() {
this.objectMapper = new ObjectMapper(new YAMLFactory().disable(Feature.WRITE_DOC_START_MARKER));
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
@Autowired
private ToscaTemplateDAO dao;
public String save(ToscaTemplate tt) {
dao.save(tt);
return tt.getId();
}
public String saveFile(MultipartFile file) throws IOException {
String originalFileName = file.getOriginalFilename();
String name = System.currentTimeMillis() + "_" + originalFileName;
byte[] bytes = file.getBytes();
String ymlStr = new String(bytes, "UTF-8");
ToscaTemplate tt = objectMapper.readValue(ymlStr, ToscaTemplate.class);
save(tt);
return tt.getId();
}
public String updateToscaTemplateByID(String id, MultipartFile file) throws IOException {
ToscaTemplate tt = dao.findById(id).get();
if (tt == null) {
throw new IOException("Tosca Template with id :" + id + " not found");
}
byte[] bytes = file.getBytes();
String ymlStr = new String(bytes, "UTF-8");
tt = objectMapper.readValue(ymlStr, ToscaTemplate.class);
tt.setId(id);
return save(tt);
}
public String findByID(String id) throws JsonProcessingException {
ToscaTemplate tt = dao.findById(id).get();
String ymlStr = objectMapper.writeValueAsString(tt);
return ymlStr;
}
public void deleteByID(String id) {
dao.deleteById(id);
}
public List<String> getAllIds() {
List<String> allIds = new ArrayList<>();
List<ToscaTemplate> all = dao.findAll();
for (ToscaTemplate tt : all) {
allIds.add(tt.getId());
}
return allIds;
}
void deleteAll() {
dao.deleteAll();
}
public ToscaTemplate getYaml2ToscaTemplate(String ymlStr) throws IOException {
return objectMapper.readValue(ymlStr, ToscaTemplate.class);
}
}
......@@ -2,4 +2,19 @@ springfox.documentation.swagger.v2.path=/api-docs
server.contextPath=/conf-api/3.0
server.port=8080
spring.jackson.date-format=nl.uva.sne.drip.RFC3339DateFormat
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
\ No newline at end of file
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
message.broker.host=127.0.0.1
message.broker.username=guest
message.broker.password=guest
message.broker.queue.provisioner=provisioner
message.broker.queue.planner=planner
message.broker.queue.deployer=deployer
db.host=127.0.0.1
db.name=drip
db.username=drip-user
db.password=drip-pass
sure-tosca.base.path=http://localhost:8081/tosca-sure/1.0.0
/*
* 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.configuration;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
/**
*
* @author S. Koulouzis
*/
@Configuration
@ComponentScan(basePackages = {"nl.uva.sne.drip", "nl.uva.sne.drip.api",
"nl.uva.sne.drip.configuration", "nl.uva.sne.drip.dao", "nl.uva.sne.drip.model", "nl.uva.sne.drip.service"})
public class MongoConfig extends AbstractMongoConfiguration {
public static int MONGO_TEST_PORT = 12345;
public static String MONGO_TEST_HOST = "localhost";
@Override
protected String getDatabaseName() {
return "test-db";
}
@Override
protected String getMappingBasePackage() {
return "nl.uva.sne.drip";
}
@Override
public MongoClient mongoClient() {
return new MongoClient(MONGO_TEST_HOST, MONGO_TEST_PORT);
}
}
/*
* 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.configuration;
import com.github.fridujo.rabbitmq.mock.MockConnection;
import com.github.fridujo.rabbitmq.mock.MockConnectionFactory;
import nl.uva.sne.drip.configuration.*;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
*
* @author S. Koulouzis
*/
@Configuration
public class RabbitMQConfig {
@Bean
public ConnectionFactory connectionFactory() {
MockConnectionFactory connectionFactory = new MockConnectionFactory();
connectionFactory.setHost("localhost");
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
connectionFactory.setPort(5555);
return connectionFactory;
}
}
/*
* 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.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embed.process.runtime.Network;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.uva.sne.drip.Swagger2SpringBoot;
import nl.uva.sne.drip.configuration.MongoConfig;
import nl.uva.sne.drip.model.Credentials;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {Swagger2SpringBoot.class})
public class ServiceTests {
@Autowired
ToscaTemplateService toscaTemplateService;
private String toscaTemplateID;
private String testApplicationExampleToscaContents;
private static final String testApplicationExampleToscaFilePath = ".." + File.separator + "TOSCA" + File.separator + "application_example.yaml";
private static final String testUpdatedApplicationExampleToscaFilePath = ".." + File.separator + "TOSCA" + File.separator + "application_example_updated.yaml";
private static final String testOutputApplicationExampleToscaFilePath = ".." + File.separator + "TOSCA" + File.separator + "application_example_output.yaml";
@Autowired
CredentialService credentialService;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
private static final MongodStarter starter = MongodStarter.getDefaultInstance();
private static MongodExecutable _mongodExe;
private static MongodProcess _mongod;
@BeforeClass
public static void setUpClass() {
try {
_mongodExe = starter.prepare(new MongodConfigBuilder()
.version(Version.Main.PRODUCTION)
.net(new Net(MongoConfig.MONGO_TEST_HOST, MongoConfig.MONGO_TEST_PORT, Network.localhostIsIPv6()))
.build());
_mongod = _mongodExe.start();
} catch (IOException ex) {
Logger.getLogger(ServiceTests.class.getName()).log(Level.SEVERE, null, ex);
}
}
@AfterClass
public static void tearDownClass() {
_mongodExe.stop();
}
@Before
public void setUp() {
if (mockMvc == null) {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
mockMvc = builder.build();
}
}
@After
public void tearDown() {
}
@Test
public void testPass() {
Assert.assertTrue(true);
}
/**
* Test of saveFile method, of class ToscaTemplateService.
*
* @throws java.lang.Exception
*/
@Test
public void testToscaTemplateServiceSaveFile() throws Exception {
Logger.getLogger(ServiceTests.class.getName()).log(Level.INFO, "saveFile");
FileInputStream in = new FileInputStream(testApplicationExampleToscaFilePath);
MultipartFile file = new MockMultipartFile("file", in);
toscaTemplateID = toscaTemplateService.saveFile(file);
Assert.assertNotNull(toscaTemplateID);
testApplicationExampleToscaContents = toscaTemplateService.findByID(toscaTemplateID);
Assert.assertNotNull(testApplicationExampleToscaContents);
}
/**
* Test of updateToscaTemplateByID method, of class ToscaTemplateService.
*/
@Test
public void testToscaTemplateServiceUpdateToscaTemplateByID_String_MultipartFile() {
FileInputStream in = null;
try {
Logger.getLogger(ServiceTests.class.getName()).log(Level.INFO, "updateToscaTemplateByID");
if (toscaTemplateID == null) {
testToscaTemplateServiceSaveFile();
}
in = new FileInputStream(testUpdatedApplicationExampleToscaFilePath);
MultipartFile file = new MockMultipartFile("file", in);
String expResult = toscaTemplateID;
String result = toscaTemplateService.updateToscaTemplateByID(toscaTemplateID, file);
assertEquals(expResult, result);
String updatedTemplate = toscaTemplateService.findByID(result);
Assert.assertNotNull(updatedTemplate);
Assert.assertNotEquals(result, testApplicationExampleToscaContents);
} catch (FileNotFoundException ex) {
Logger.getLogger(ServiceTests.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(ServiceTests.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
fail(ex.getMessage());
Logger.getLogger(ServiceTests.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* Test of updateToscaTemplateByID method, of class ToscaTemplateService.
*
* @throws java.io.FileNotFoundException
*/
@Test
public void testToscaTemplateServiceUpdateToscaTemplateByID_Exception_MultipartFile() throws FileNotFoundException, IOException {
FileInputStream in = new FileInputStream(testUpdatedApplicationExampleToscaFilePath);
MultipartFile file = new MockMultipartFile("file", in);
try {
toscaTemplateService.updateToscaTemplateByID("0", file);
} catch (Exception ex) {
if (!(ex instanceof NoSuchElementException)) {
fail(ex.getMessage());
}
}
}
/**
* Test of findByID method, of class ToscaTemplateService.
*/
@Test
public void testToscaTemplateServiceFindByID() {
try {
Logger.getLogger(ServiceTests.class.getName()).log(Level.INFO, "findByID");
if (toscaTemplateID == null) {
testToscaTemplateServiceSaveFile();
}
String result = toscaTemplateService.findByID(toscaTemplateID);
Assert.assertNotNull(result);
assertEquals(testApplicationExampleToscaContents, result);
} catch (JsonProcessingException ex) {
fail(ex.getMessage());
Logger.getLogger(ServiceTests.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
fail(ex.getMessage());
Logger.getLogger(ServiceTests.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Test of deleteByID method, of class ToscaTemplateService.
*/
@Test
public void testToscaTemplateServiceDeleteByID() {
try {
Logger.getLogger(ServiceTests.class.getName()).log(Level.INFO, "deleteByID");
if (toscaTemplateID == null) {
testToscaTemplateServiceSaveFile();
}
toscaTemplateService.deleteByID(toscaTemplateID);
String id = toscaTemplateService.findByID(toscaTemplateID);
} catch (Exception ex) {
if (!(ex instanceof NoSuchElementException)) {
fail(ex.getMessage());
Logger.getLogger(ServiceTests.class.getName()).log(Level.SEVERE, null, ex);
}
} finally {
try {
testToscaTemplateServiceSaveFile();
} catch (Exception ex) {
fail(ex.getMessage());
Logger.getLogger(ServiceTests.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* Test of getAllIds method, of class ToscaTemplateService.
*/
@Test
public void testToscaTemplateServiceGetAllIds() throws Exception {
Logger.getLogger(ServiceTests.class.getName()).log(Level.INFO, "getAllIds");
testToscaTemplateServiceDeleteAll();
int numOfINst = 3;
for (int i = 1; i <= numOfINst; i++) {
testToscaTemplateServiceSaveFile();
}
List<String> result = toscaTemplateService.getAllIds();
assertEquals(numOfINst, result.size());
}
@Test
public void testToscaTemplateServiceDeleteAll() {
toscaTemplateService.deleteAll();
int size = toscaTemplateService.getAllIds().size();
assertEquals(0, size);
}
/**
* Test of save method, of class CredentialService.
*/
@Test
public void testCredentialServiceSave() {
Logger.getLogger(ServiceTests.class.getName()).log(Level.INFO, "save");
saveCredential();
}
public String saveCredential() {
Logger.getLogger(ServiceTests.class.getName()).log(Level.INFO, "saveCredential");
Credentials document = new Credentials();
document.setCloudProviderName("exogeni");
Map<String, String> keys = new HashMap<>();
keys.put("keystore", "/qTlqams0Ppq2rnaOgL5am7ExGO2nMsOZYM61kiAnsvkOixUuoPy9r4d4OfhwQXXg3lZmeRITjNz4ps+hIDKuxodIQXgBtfMy9Kx8Syb9bIl/MQQls5hWyp9yHAl6vAampoxYu0170lceT1sds4OCz3tM9eF7/UoBQwXBPo94QhO1/vSbtICyVsm3Z2HeGKcBWobT3opZV2w30GqX/7OBmNeIG7RBMPuxLsUxJ9Alahi1zXOUjLkd2bmmVFREngmeubgCzPFxxCQQrZK6WratTzJKc1sRVNK5GJzTwi9BlcZSQSgprum9yVHUgQc6Ylmvdrkhn2g9SlluY2JAZyCZvHYaRBKE4o5bXBDumTy1YAPMNPTfpeeLz+YmH0GMfVwKkxtIBpjb045QseoIWcqxke60WWfJguaTqymXknmcqcLNz+UzUdfVfyurOy9X8xmTGCW5V4N");
document.setKeys(keys);
document.setToken("secret");
document.setTokenType("password");
return credentialService.save(document);
}
/**
* Test of findByID method, of class CredentialService.
*
* @throws java.lang.Exception
*/
@Test
public void testCredentialServiceFindByID() throws Exception {
Logger.getLogger(ServiceTests.class.getName()).log(Level.INFO, "findByID");
String id = saveCredential();
Credentials result = credentialService.findByID(id);
assertNotNull(result);
}
/**
* Test of deleteByID method, of class CredentialService.
*/
@Test
public void testCredentialServiceDeleteByID() throws JsonProcessingException {
Logger.getLogger(ServiceTests.class.getName()).log(Level.INFO, "deleteByID");
String id = saveCredential();
credentialService.deleteByID(id);
try {
Credentials res = credentialService.findByID(id);
} catch (Exception ex) {
if (!(ex instanceof NoSuchElementException)) {
fail(ex.getMessage());
}
}
}
/**
* Test of getAllIds method, of class CredentialService.
*/
@Test
public void testCredentialServiceGetAllIds() {
Logger.getLogger(ServiceTests.class.getName()).log(Level.INFO, "getAllIds");
testCredentialServiceDeleteAll();
int numOfINst = 3;
for (int i = 1; i <= numOfINst; i++) {
saveCredential();
}
List<String> result = credentialService.getAllIds();
assertEquals(numOfINst, result.size());
}
/**
* Test of deleteAll method, of class CredentialService.
*/
@Test
public void testCredentialServiceDeleteAll() {
credentialService.deleteAll();
int size = credentialService.getAllIds().size();
assertEquals(0, size);
}
}
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