diff --git a/.gitignore b/.gitignore index 12a7227..eab9f06 100644 --- a/.gitignore +++ b/.gitignore @@ -5,8 +5,8 @@ .mtj.tmp/ # Package Files # -*.jar *.war +maven-wrapper.jar *.ear # Config file diff --git a/cascades-client/src/main/java/pl/gov/coi/cascades/client/CascadesImpl.java b/cascades-client/src/main/java/pl/gov/coi/cascades/client/CascadesImpl.java index 106963c..2dbd6d5 100644 --- a/cascades-client/src/main/java/pl/gov/coi/cascades/client/CascadesImpl.java +++ b/cascades-client/src/main/java/pl/gov/coi/cascades/client/CascadesImpl.java @@ -70,10 +70,6 @@ public RemoteDatabaseSpec getSpec() { private RemoteDatabaseRequest createRequest() { Driver driver = configuration.getDriver(); return new RemoteDatabaseRequest( - checkNotNull( - checkNotNull(driver, "20170330:093926").getType(), - "20170330:093953" - ).getName(), driver.getTemplateId().orNull(), configuration.getInstanceName().orNull() ); diff --git a/cascades-contract/src/main/java/pl/gov/coi/cascades/contract/domain/Template.java b/cascades-contract/src/main/java/pl/gov/coi/cascades/contract/domain/Template.java index c61a0c3..889fa1b 100644 --- a/cascades-contract/src/main/java/pl/gov/coi/cascades/contract/domain/Template.java +++ b/cascades-contract/src/main/java/pl/gov/coi/cascades/contract/domain/Template.java @@ -15,7 +15,10 @@ public class Template implements Serializable { private static final long serialVersionUID = 42L; @Getter - private final String id; + private final Long id; + + @Getter + private final String generatedId; @Getter private final String name; diff --git a/cascades-contract/src/main/java/pl/gov/coi/cascades/contract/service/RemoteDatabaseRequest.java b/cascades-contract/src/main/java/pl/gov/coi/cascades/contract/service/RemoteDatabaseRequest.java index 2d518ff..196721f 100644 --- a/cascades-contract/src/main/java/pl/gov/coi/cascades/contract/service/RemoteDatabaseRequest.java +++ b/cascades-contract/src/main/java/pl/gov/coi/cascades/contract/service/RemoteDatabaseRequest.java @@ -1,7 +1,6 @@ package pl.gov.coi.cascades.contract.service; import com.google.common.base.Optional; -import lombok.Getter; import pl.gov.coi.cascades.contract.domain.Template; import javax.annotation.Nullable; @@ -14,8 +13,6 @@ public class RemoteDatabaseRequest implements Serializable { private static final long serialVersionUID = 42L; - @Getter - private final String type; @Nullable private final Template template; @Nullable @@ -24,14 +21,11 @@ public class RemoteDatabaseRequest implements Serializable { /** * Required argument constructor. * - * @param type Given type of database (a name or FQCN). * @param template Given id of template (Optional). * @param instanceName Given name of instance (Optional). */ - public RemoteDatabaseRequest(String type, - @Nullable Template template, + public RemoteDatabaseRequest(@Nullable Template template, @Nullable String instanceName) { - this.type = type; this.template = template; this.instanceName = instanceName; } diff --git a/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/configuration/DriverTest.java b/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/configuration/DriverTest.java index 4e4e182..61a10c6 100644 --- a/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/configuration/DriverTest.java +++ b/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/configuration/DriverTest.java @@ -10,7 +10,6 @@ import org.mockito.junit.MockitoRule; import pl.gov.coi.cascades.contract.domain.DatabaseType; import pl.gov.coi.cascades.contract.domain.Template; -import pl.gov.coi.cascades.contract.domain.Template; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -38,7 +37,7 @@ public class DriverTest { @Before public void setUp() { driver = new Driver( - databaseType, + databaseType, template ); } @@ -47,7 +46,7 @@ public void setUp() { public void testDefaultConstructor() throws Exception { // when Driver actual = new Driver( - databaseType, + databaseType, template ); diff --git a/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/domain/TemplateTest.java b/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/domain/TemplateTest.java index dba803a..6d9e7d8 100644 --- a/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/domain/TemplateTest.java +++ b/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/domain/TemplateTest.java @@ -11,7 +11,8 @@ */ public class TemplateTest { - private String id; + private Long id; + private String generatedId; private String name; private String serverId; private String version; @@ -20,10 +21,11 @@ public class TemplateTest { @Before public void setUp() { - id = "oracle_template"; + id = 123L; name = "hbet6f73"; serverId = "1234"; version = "0.0.1"; + generatedId = "gw13dqD"; status = TemplateIdStatus.CREATED; isDefault = true; } @@ -33,6 +35,7 @@ public void testToString() { // given Template templateBuilder = Template.builder() .id(id) + .generatedId(generatedId) .name(name) .isDefault(isDefault) .serverId(serverId) @@ -50,7 +53,8 @@ public void testToString() { serverId, status.toString(), version, - id, + id.toString(), + generatedId, name ); } @@ -86,6 +90,7 @@ public void testDefaultConstructor() throws Exception { // when Template actual = new Template( id, + generatedId, name, TemplateIdStatus.CREATED, true, @@ -96,6 +101,7 @@ public void testDefaultConstructor() throws Exception { // then assertThat(actual).isNotNull(); assertThat(actual.getId()).isEqualTo(id); + assertThat(actual.getGeneratedId()).isEqualTo(generatedId); assertThat(actual.getStatus()).isEqualTo(TemplateIdStatus.CREATED); assertThat(actual.getServerId()).isEqualTo(serverId); assertThat(actual.getName()).isEqualTo(name); diff --git a/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/service/RemoteDatabaseRequestTest.java b/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/service/RemoteDatabaseRequestTest.java index 44cb3bf..c5fd111 100644 --- a/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/service/RemoteDatabaseRequestTest.java +++ b/cascades-contract/src/test/java/pl/gov/coi/cascades/contract/service/RemoteDatabaseRequestTest.java @@ -22,7 +22,6 @@ public class RemoteDatabaseRequestTest { private RemoteDatabaseRequest remoteDatabaseRequest; private String instanceName; - private String typeClassName; @Mock private Template template; @@ -36,9 +35,7 @@ public class RemoteDatabaseRequestTest { @Before public void setUp() { instanceName = "PESEL"; - typeClassName = "typeClassName"; - remoteDatabaseRequest = new RemoteDatabaseRequest( - typeClassName, + remoteDatabaseRequest = new RemoteDatabaseRequest( template, instanceName ); @@ -48,7 +45,6 @@ public void setUp() { public void testDefaultConstructor() throws Exception { // when RemoteDatabaseRequest actual = new RemoteDatabaseRequest( - typeClassName, template, instanceName ); diff --git a/cascades-junit4/src/test/java/pl/gov/coi/cascades/junit4/CascadesRuleTest.java b/cascades-junit4/src/test/java/pl/gov/coi/cascades/junit4/CascadesRuleTest.java index 87911d2..3150991 100644 --- a/cascades-junit4/src/test/java/pl/gov/coi/cascades/junit4/CascadesRuleTest.java +++ b/cascades-junit4/src/test/java/pl/gov/coi/cascades/junit4/CascadesRuleTest.java @@ -15,14 +15,16 @@ @Ignore public class CascadesRuleTest { - private String id; + private long id; + private String generatedId; private String serverId; private String version; private String name; @Before public void setUp() { - id = "gw45223"; + id = 123L; + generatedId = "gw45223"; serverId = "898693"; version = "0.0.1"; name = "oracle_template"; @@ -69,6 +71,7 @@ public void testBefore() { CascadesRule rule = CascadesRule.builder() .driver(new Driver(DATABASE_TYPE_STUB, new Template( id, + generatedId, name, TemplateIdStatus.CREATED, false, diff --git a/cascades-server/README.md b/cascades-server/README.md new file mode 100644 index 0000000..ab5b024 --- /dev/null +++ b/cascades-server/README.md @@ -0,0 +1,9 @@ +# Example usage + +* Run PostgreSQL server in docker +`docker run --name cascades-postgres -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres:10.4` + +* Build project with profile `-Ppostgresql` +It adds PostgreSQL driver. + +* Run application with profile `mvn spring-boot:run --Dspring.profiles.activeproduction,hibernate,postgresqldocker` diff --git a/cascades-server/app/pom.xml b/cascades-server/app/pom.xml index 407c666..8e55118 100644 --- a/cascades-server/app/pom.xml +++ b/cascades-server/app/pom.xml @@ -12,6 +12,23 @@ Cascades :: Server :: Spring Application + + org.apache.commons + commons-io + 1.3.2 + + + postgresql + postgresql + 9.0-801.jdbc4 + + + com.oracle + ojdbc + 12.1.0.2 + system + ${basedir}/src/main/resources/ojdbc7.jar + org.slf4j slf4j-api @@ -98,4 +115,17 @@ + + + postgresql + + + postgresql + postgresql + 9.0-801.jdbc4 + + + + + diff --git a/cascades-server/app/src/main/java/pl/gov/coi/cascades/server/CustomizationBean.java b/cascades-server/app/src/main/java/pl/gov/coi/cascades/server/CustomizationBean.java new file mode 100644 index 0000000..6e6d507 --- /dev/null +++ b/cascades-server/app/src/main/java/pl/gov/coi/cascades/server/CustomizationBean.java @@ -0,0 +1,15 @@ +package pl.gov.coi.cascades.server; + +import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; +import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; +import org.springframework.stereotype.Component; + +@Component +public class CustomizationBean implements EmbeddedServletContainerCustomizer { + + @Override + public void customize(ConfigurableEmbeddedServletContainer container) { + container.setPort(8085); + // Use port of your choice that is available + } +} diff --git a/cascades-server/app/src/main/resources/application-development.properties b/cascades-server/app/src/main/resources/application-development.properties index 51b6055..965a0bd 100644 --- a/cascades-server/app/src/main/resources/application-development.properties +++ b/cascades-server/app/src/main/resources/application-development.properties @@ -1 +1,18 @@ spring.datasource.url=jdbc:h2:mem:CASCADES;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + +cascades.managed-servers[0].serverId=rgey65getg +cascades.managed-servers[0].type=pqsql +cascades.managed-servers[0].dbname=postgres +cascades.managed-servers[0].user=root +cascades.managed-servers[0].password=passwrd +cascades.managed-servers[0].host=172.17.0.3 +cascades.managed-servers[0].port=5432 + +cascades.managed-servers[1].serverId=dgrt45gtyt +cascades.managed-servers[1].type=stub +cascades.managed-servers[1].dbname=postgres +cascades.managed-servers[1].user=root +cascades.managed-servers[1].password=passwrd +cascades.managed-servers[1].host=cascades.example.org +cascades.managed-servers[1].port=443 + diff --git a/cascades-server/app/src/main/resources/application-production.properties b/cascades-server/app/src/main/resources/application-production.properties new file mode 100644 index 0000000..a599e56 --- /dev/null +++ b/cascades-server/app/src/main/resources/application-production.properties @@ -0,0 +1,36 @@ +spring.datasource.url=jdbc:h2:mem:CASCADES;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + +cascades.managed-servers[0].serverId=rgey65getg +cascades.managed-servers[0].type=pgsql +cascades.managed-servers[0].dbname=postgres +cascades.managed-servers[0].user=root +cascades.managed-servers[0].password=passwrd +cascades.managed-servers[0].host=cascades.example.org +cascades.managed-servers[0].port=553 + + +cascades.managed-servers[2].serverId=hdx234rd +cascades.managed-servers[2].type=pgsql +cascades.managed-servers[2].dbname=postgres +cascades.managed-servers[2].user=root +cascades.managed-servers[2].password=passwrd +cascades.managed-servers[2].host=172.17.0.3 +cascades.managed-servers[2].port=5432 + + +cascades.managed-servers[1].serverId=dgrt45gtyt +cascades.managed-servers[1].type=pgsql +cascades.managed-servers[1].dbname=postgres +cascades.managed-servers[1].user=root +cascades.managed-servers[1].password=passwrd +cascades.managed-servers[1].host=cascades.example.org +cascades.managed-servers[1].port=443 + + +cascades.managed-servers[3].serverId=asdq3 +cascades.managed-servers[3].type=ora12c +cascades.managed-servers[3].dbname=orcl12c +cascades.managed-servers[3].user=sys as sysdba +cascades.managed-servers[3].password=oracle +cascades.managed-servers[3].host=127.0.0.1 +cascades.managed-servers[3].port=1521 diff --git a/cascades-server/app/src/main/resources/ojdbc7.jar b/cascades-server/app/src/main/resources/ojdbc7.jar new file mode 100644 index 0000000..fd38a6c Binary files /dev/null and b/cascades-server/app/src/main/resources/ojdbc7.jar differ diff --git a/cascades-server/app/src/test/java/pl/gov/coi/cascades/server/GeneralDatabaseOperationGatewayTestIT.java b/cascades-server/app/src/test/java/pl/gov/coi/cascades/server/GeneralDatabaseOperationGatewayTestIT.java new file mode 100644 index 0000000..f41ecf7 --- /dev/null +++ b/cascades-server/app/src/test/java/pl/gov/coi/cascades/server/GeneralDatabaseOperationGatewayTestIT.java @@ -0,0 +1,155 @@ +package pl.gov.coi.cascades.server; + +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import pl.gov.coi.cascades.contract.domain.DatabaseId; +import pl.gov.coi.cascades.contract.domain.Template; +import pl.gov.coi.cascades.contract.domain.TemplateIdStatus; +import pl.gov.coi.cascades.server.domain.DatabaseInstance; +import pl.gov.coi.cascades.server.domain.DatabaseStatus; +import pl.gov.coi.cascades.server.domain.DatabaseTypeImpl; +import pl.gov.coi.cascades.server.domain.launchdatabase.UsernameAndPasswordCredentialsImpl; + +import javax.inject.Inject; +import java.io.File; +import java.io.IOException; +import java.util.Date; + +/** + * @author Łukasz Małek + */ +@RunWith(SpringRunner.class) +@SpringBootTest +@ProductionHibernateTest +public class GeneralDatabaseOperationGatewayTestIT { + + private static final String TEMPLATE_NAME = "examplee"; + private static final String SERVER_ID_ORACLE = "asdq3"; + private static final String SERVER_ID_POSTGRES = "hdx234rd"; + private static final String ID_DATABASE = "a123xqw2"; + private static final String DATABASE_NAME = "databasenamee"; + private static final String MY_DATABASE = "my_database"; + private static final String FILE_NAME = "tempFile.txt"; + private static final String USERNAME = "exampleUsernamee"; + private static final String PASSWORD = "examplePassword"; + private static final String ORACLE = "ora12c"; + private static final String POSTGRES = "pgsql"; + + private Template template; + private ServerConfigurationService serverConfigurationService; + private DatabaseManager databaseManager; + private GeneralTemplateGateway generalTemplateGateway; + private GeneralDatabaseOperationGateway generalDatabaseOperationGateway; + private GeneralUserGateway generalUserGateway; + private DatabaseInstance databaseInstance; + + + @Inject + public void setServerConfigurationService(ServerConfigurationService serverConfigurationService) { + this.serverConfigurationService = serverConfigurationService; + } + + @Inject + public void setDatabaseManager(DatabaseManager databaseManager) { + this.databaseManager = databaseManager; + } + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + @Before + public void init() { + generalUserGateway = new GeneralUserGateway(databaseManager); + generalTemplateGateway = new GeneralTemplateGateway(databaseManager); + generalDatabaseOperationGateway = new GeneralDatabaseOperationGateway(serverConfigurationService, databaseManager); + } + + @After + public void afterTest() { + generalTemplateGateway.deleteTemplate(template); + // TODO: write implementation - remove database + generalUserGateway.deleteUser(databaseInstance); + } + + //Ignored test because Travis does not have an integrated database. Only for local test. + @Ignore + @Test + public void shouldCreateOracleDatabase() throws IOException { + //given + File tempFile = tempFolder.newFile(FILE_NAME); + FileUtils.writeStringToFile(tempFile, "CREATE TABLE employees (\n" + + " emp_id number(38) unique not null,\n" + + " name varchar2(32),\n" + + " department number not null,\n" + + " hire_date date not null);\n" + + "\n"); + + template = createTemplate(SERVER_ID_ORACLE); + databaseInstance = createDatabaseInstance(template, ORACLE); + + //when + generalTemplateGateway.createTemplate(template, tempFile.toPath()); + generalDatabaseOperationGateway.createDatabase(databaseInstance); + + //then + generalUserGateway.createUser(databaseInstance); + } + + //Ignored test because Travis does not have an integrated database. Only for local test. + @Ignore + @Test + public void shouldCreatePostgresDatabase() throws IOException { + //given + File tempFile = tempFolder.newFile(FILE_NAME); + FileUtils.writeStringToFile(tempFile, "CREATE TABLE COMPANY(\n" + + " ID INT PRIMARY KEY NOT NULL,\n" + + " NAME TEXT NOT NULL,\n" + + " AGE INT NOT NULL,\n" + + " ADDRESS CHAR(50),\n" + + " SALARY REAL\n" + + ");"); + + template = createTemplate(SERVER_ID_POSTGRES); + databaseInstance = createDatabaseInstance(template, POSTGRES); + + //when + generalTemplateGateway.createTemplate(template, tempFile.toPath()); + generalDatabaseOperationGateway.createDatabase(databaseInstance); + + //then + generalUserGateway.createUser(databaseInstance); + } + + + private DatabaseInstance createDatabaseInstance(Template template, String databaseType) { + return DatabaseInstance.builder() + .databaseId(new DatabaseId(ID_DATABASE)) + .status(DatabaseStatus.LAUNCHED) + .created(new Date()) + .credentials(new UsernameAndPasswordCredentialsImpl(USERNAME, PASSWORD.toCharArray())) + .databaseName(DATABASE_NAME) + .databaseType(new DatabaseTypeImpl(databaseType)) + .instanceName(MY_DATABASE) + .networkBind(null) + .reuseTimes(1) + .template(template) + .build(); + } + + private Template createTemplate(String serverId) { + return Template.builder() + .name(TEMPLATE_NAME) + .serverId(serverId) + .isDefault(false) + .status(TemplateIdStatus.CREATED) + .build(); + } +} diff --git a/cascades-server/app/src/test/java/pl/gov/coi/cascades/server/TemplateGatewayImplFunctionalIT.java b/cascades-server/app/src/test/java/pl/gov/coi/cascades/server/TemplateGatewayImplFunctionalIT.java index 66affb9..87c105b 100644 --- a/cascades-server/app/src/test/java/pl/gov/coi/cascades/server/TemplateGatewayImplFunctionalIT.java +++ b/cascades-server/app/src/test/java/pl/gov/coi/cascades/server/TemplateGatewayImplFunctionalIT.java @@ -43,23 +43,23 @@ public void shouldExecutePersistNewTemplate() { //when templateIdGateway.addTemplate(template); - Optional result = templateIdGateway.find(template.getId()); + Optional result = templateIdGateway.find(template.getGeneratedId()); //then assertNotNull(result); pl.gov.coi.cascades.contract.domain.Template resultTemplate = result.orElse(null); assertNotNull(resultTemplate); - assertEquals(template.getId(), resultTemplate.getId()); - assertEquals(template.getName(), resultTemplate.getName()); - assertEquals(template.getServerId(), resultTemplate.getServerId()); - assertEquals(template.getVersion(), resultTemplate.getVersion()); - assertEquals(template.getStatus(), resultTemplate.getStatus()); + assertEquals("1", resultTemplate.getGeneratedId()); + assertEquals("newDatabase", resultTemplate.getName()); + assertEquals("1234", resultTemplate.getServerId()); + assertEquals("0.0.1", resultTemplate.getVersion()); + assertEquals(TemplateIdStatus.CREATED, resultTemplate.getStatus()); } private pl.gov.coi.cascades.contract.domain.Template createTemplate() { return pl.gov.coi.cascades.contract.domain.Template.builder() - .id(ID) + .generatedId(ID) .name(NAME) .isDefault(IS_DEFAULT) .serverId(SERVER_ID) diff --git a/cascades-server/app/src/test/java/pl/gov/coi/cascades/server/domain/launchdatabase/FunctionalIT.java b/cascades-server/app/src/test/java/pl/gov/coi/cascades/server/domain/launchdatabase/FunctionalIT.java index 9b08b9a..f56d8b3 100644 --- a/cascades-server/app/src/test/java/pl/gov/coi/cascades/server/domain/launchdatabase/FunctionalIT.java +++ b/cascades-server/app/src/test/java/pl/gov/coi/cascades/server/domain/launchdatabase/FunctionalIT.java @@ -23,7 +23,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import pl.gov.coi.cascades.server.StubDevelopmentTest; -import pl.gov.coi.cascades.server.persistance.stub.DatabaseTypeStub; import pl.gov.coi.cascades.server.persistance.stub.TemplateIdGatewayStub; import javax.inject.Inject; @@ -64,7 +63,7 @@ public void setup() { @After public void after() { TemplateIdGatewayStub.getAllTemplates().put( - TemplateIdGatewayStub.TEMPLATE_ID3.getId(), + TemplateIdGatewayStub.TEMPLATE_ID3.getGeneratedId(), TemplateIdGatewayStub.TEMPLATE_ID3 ); } @@ -135,16 +134,13 @@ private Description buildDescription(MockHttpServletResponse response) } private String requestWithNoTemplateId() throws JSONException { - DatabaseTypeStub stub = new DatabaseTypeStub(); return new JSONObject() - .put("type", stub.getName()) + .put("instanceName", "dfasd") .toString(); } private String requestWithTemplateId(String templateId) throws JSONException { - DatabaseTypeStub stub = new DatabaseTypeStub(); return new JSONObject() - .put("type", stub.getName()) .put("templateId", templateId) .toString(); } diff --git a/cascades-server/configuration/pom.xml b/cascades-server/configuration/pom.xml index 98e47c4..e35bbf1 100644 --- a/cascades-server/configuration/pom.xml +++ b/cascades-server/configuration/pom.xml @@ -13,6 +13,11 @@ Cascades :: Server :: Configuration + + org.apache.commons + commons-lang3 + 3.0 + org.slf4j slf4j-api diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ConnectionConfiguration.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ConnectionConfiguration.java index 7cd08bc..5dab936 100644 --- a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ConnectionConfiguration.java +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ConnectionConfiguration.java @@ -12,6 +12,6 @@ @AllArgsConstructor @RequiredArgsConstructor class ConnectionConfiguration { - private String driver; - private String url; + private String driverClass; + private String jdbcUrlTemplate; } diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ConnectionConfigurator.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ConnectionConfigurator.java index 605662d..4deea07 100644 --- a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ConnectionConfigurator.java +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ConnectionConfigurator.java @@ -8,27 +8,27 @@ */ public class ConnectionConfigurator { - ConnectionConfiguration getConnectionConfiguration(ServerDef serverDef) { - String driver; - String url; - switch (serverDef.getType()) { + ConnectionConfiguration getConnectionConfiguration(String databaseType) { + String driverClass; + String jdbdUrlTemplate; + switch (databaseType) { case "ora12c": - driver = "oracle.jdbc.driver.OracleDriver"; - url = "jdbc:oracle:thin:@//%s:%d/%s"; + driverClass = "oracle.jdbc.OracleDriver"; + jdbdUrlTemplate = "jdbc:oracle:thin:@//%s:%d/%s"; break; case "pgsql": - driver = "org.postgresql.Driver"; - url = "jdbc:postgresql://%s:%d/%s"; + driverClass = "org.postgresql.Driver"; + jdbdUrlTemplate = "jdbc:postgresql://%s:%d/%s"; break; default: throw new EidIllegalArgumentException( "20170728:150904", - "Given driver hasn't been recognised." + String.format("Given database type '%s' hasn't been recognised.", databaseType) ); } return new ConnectionConfiguration( - driver, - url + driverClass, + jdbdUrlTemplate ); } diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseEndpointConfiguration.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseEndpointConfiguration.java index 63dc852..9c9addd 100644 --- a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseEndpointConfiguration.java +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseEndpointConfiguration.java @@ -4,9 +4,10 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import pl.gov.coi.cascades.server.domain.DatabaseOperationsGateway; import pl.gov.coi.cascades.server.domain.DatabaseTemplateGateway; +import pl.gov.coi.cascades.server.domain.DatabaseUserGateway; -import java.util.HashMap; import java.util.Map; /** @@ -18,29 +19,30 @@ public class DatabaseEndpointConfiguration { @Bean - Map produceDriverManagerDataSource(ServerConfigurationService service, - ConnectionConfigurator connectionConfigurator) { - Map managers = new HashMap<>(); - for (ServerDef serverDef : service.getManagedServers()) { - ConnectionConfiguration configuration = connectionConfigurator.getConnectionConfiguration(serverDef); - DriverManagerDataSource manager = new DriverManagerDataSource(); - manager.setDriverClassName(configuration.getDriver()); - manager.setUrl(String.format( - configuration.getUrl(), - serverDef.getHost(), - serverDef.getPort(), - serverDef.getDbname()) - ); - manager.setPassword(serverDef.getPassword()); - manager.setUsername(serverDef.getUser()); - managers.put(serverDef.getServerId(), manager); - } - return managers; + Map produceDriverManagerDataSource(DriverManagerDataSourceHelper driverManagerDataSourceHelper) { + return driverManagerDataSourceHelper.getManagersMap(); } @Bean - DatabaseManager produceDatabaseManager(Map driver) { - return new DatabaseEndpointManager(driver); + DriverManagerDataSourceProvider produceDriverManagerDataSourceProvider() { + return new DriverManagerDataSourceProviderImpl(); + } + + @Bean + DriverManagerDataSourceHelper produceDriverManagerDataSourceHelper(ConnectionConfigurator connectionConfigurator, + ServerConfigurationService serverConfigurationService, + DriverManagerDataSourceProvider driverManagerDataSourceProvider) { + return new DriverManagerDataSourceHelper( + connectionConfigurator, + serverConfigurationService, + driverManagerDataSourceProvider + ); + } + + @Bean + DatabaseManager produceDatabaseManager(Map driverManagerMap, + DriverManagerDataSourceHelper driverManagerDataSourceHelper) { + return new DatabaseEndpointManager(driverManagerMap, driverManagerDataSourceHelper); } @Bean @@ -48,9 +50,18 @@ DatabaseTemplateGateway produceDatabaseTemplateGateway(DatabaseManager manager) return new GeneralTemplateGateway(manager); } + @Bean + DatabaseUserGateway produceDatabaseUserGateway(DatabaseManager manager) { + return new GeneralUserGateway(manager); + } + @Bean ConnectionConfigurator produceConnectionConfiguration() { return new ConnectionConfigurator(); } + @Bean + DatabaseOperationsGateway produceDatabaseOperationGateway(ServerConfigurationService serverConfigurationService, DatabaseManager databaseManager) { + return new GeneralDatabaseOperationGateway(serverConfigurationService, databaseManager); + } } diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseEndpointManager.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseEndpointManager.java index 46a553f..1897060 100644 --- a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseEndpointManager.java +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseEndpointManager.java @@ -5,7 +5,6 @@ import pl.wavesoftware.eid.exceptions.EidIllegalArgumentException; import javax.inject.Inject; -import java.sql.SQLException; import java.util.Map; /** @@ -15,14 +14,17 @@ public class DatabaseEndpointManager implements DatabaseManager { private final Map managers; + private final DriverManagerDataSourceHelper driverManagerDataSourceHelper; @Inject - DatabaseEndpointManager(Map managers) { + DatabaseEndpointManager(Map managers, + DriverManagerDataSourceHelper driverManagerDataSourceHelper) { this.managers = managers; + this.driverManagerDataSourceHelper = driverManagerDataSourceHelper; } @Override - public ConnectionDatabase get(String serverId) throws SQLException { + public ConnectionDatabase getConnectionToServer(String serverId) { DriverManagerDataSource manager = managers.get(serverId); if (manager == null) { @@ -38,4 +40,13 @@ public ConnectionDatabase get(String serverId) throws SQLException { ); } + @Override + public ConnectionDatabase getConnectionToDatabase(String serverId, String templateName) { + DriverManagerDataSource manager = driverManagerDataSourceHelper.getManager(serverId, templateName); + return new ConnectionDatabase( + new JdbcTemplate(manager), + manager.getUrl() + ); + } + } diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseManager.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseManager.java index cfdf0aa..f31e798 100644 --- a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseManager.java +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DatabaseManager.java @@ -8,6 +8,19 @@ */ public interface DatabaseManager { - ConnectionDatabase get(String serverId) throws SQLException; + /** + * Returns connection to database with sepcified serverId. + * @param serverId server ID + * @return connection to database + */ + ConnectionDatabase getConnectionToServer(String serverId) throws SQLException; + + /** + * Returns connection to template in database with sepcified serverId. + * @param serverId server ID + * @param templateName template name + * @return connection to database + */ + ConnectionDatabase getConnectionToDatabase(String serverId, String templateName) throws SQLException; } diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DriverManagerDataSourceHelper.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DriverManagerDataSourceHelper.java new file mode 100644 index 0000000..b2f4082 --- /dev/null +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DriverManagerDataSourceHelper.java @@ -0,0 +1,76 @@ +package pl.gov.coi.cascades.server; + +import lombok.AllArgsConstructor; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import pl.wavesoftware.eid.exceptions.EidIllegalStateException; + +import javax.inject.Inject; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** + * @author Mariusz Wyszomierski + */ +@AllArgsConstructor +public class DriverManagerDataSourceHelper { + + private final ConnectionConfigurator connectionConfigurator; + private final ServerConfigurationService serverConfigurationService; + private final DriverManagerDataSourceProvider driverManagerDataSourceProvider; + + /** + * Returns connection to database with given database name on server with given serverId + * defined in application configuration {@link ServerConfigurationService}. + * + * @param serverId server ID + * @param databaseName database name + * @return {@link DriverManagerDataSource} + */ + DriverManagerDataSource getManager(String serverId, String databaseName) { + ServerDef serverConfiguration = getServerDef(serverId); + ConnectionConfiguration connectionConfiguration = connectionConfigurator.getConnectionConfiguration(serverConfiguration.getType()); + ServerDef newServerConfiguration = serverConfiguration.getWithNewDatabaseName(databaseName); + return createDriverManagerDataSource(connectionConfiguration, newServerConfiguration); + } + + /** + * Returns map of connections to servers defined in application configuration {@link ServerConfigurationService}. + * @return map of connections, serverId is the key + */ + Map getManagersMap() { + Map managers = new HashMap<>(); + for (ServerDef serverDef : serverConfigurationService.getManagedServers()) { + ConnectionConfiguration configuration = connectionConfigurator.getConnectionConfiguration(serverDef.getType()); + DriverManagerDataSource manager = createDriverManagerDataSource(configuration, serverDef); + managers.put(serverDef.getServerId(), manager); + } + return managers; + } + + private DriverManagerDataSource createDriverManagerDataSource(ConnectionConfiguration connectionConfiguration, + ServerDef serverConfiguration) { + DriverManagerDataSource manager = driverManagerDataSourceProvider.produce(); + manager.setDriverClassName(connectionConfiguration.getDriverClass()); + manager.setUrl(String.format( + connectionConfiguration.getJdbcUrlTemplate(), + serverConfiguration.getHost(), + serverConfiguration.getPort(), + serverConfiguration.getDbname()) + ); + manager.setPassword(serverConfiguration.getPassword()); + manager.setUsername(serverConfiguration.getUser()); + return manager; + } + + private ServerDef getServerDef(String serverId) { + Optional matchingServerConfiguration = serverConfigurationService.getManagedServers().stream() + .filter(server -> serverId.equals(server.getServerId())) + .findFirst(); + if (!matchingServerConfiguration.isPresent()) { + String errorMessage = String.format("There is no configuration for serverId: %s", serverId); + throw new EidIllegalStateException("20180625:205951", errorMessage); + } + return matchingServerConfiguration.get(); + } +} diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DriverManagerDataSourceProvider.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DriverManagerDataSourceProvider.java new file mode 100644 index 0000000..e09df0c --- /dev/null +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DriverManagerDataSourceProvider.java @@ -0,0 +1,15 @@ +package pl.gov.coi.cascades.server; + +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +/** + * @author Mariusz Wyszomierski + */ +public interface DriverManagerDataSourceProvider { + + /** + * Provides instance of {@link DriverManagerDataSource}. + * @return {@link DriverManagerDataSource} + */ + DriverManagerDataSource produce(); +} diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DriverManagerDataSourceProviderImpl.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DriverManagerDataSourceProviderImpl.java new file mode 100644 index 0000000..6c55466 --- /dev/null +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/DriverManagerDataSourceProviderImpl.java @@ -0,0 +1,14 @@ +package pl.gov.coi.cascades.server; + +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +/** + * @author Mariusz Wyszomierski + */ +public class DriverManagerDataSourceProviderImpl implements DriverManagerDataSourceProvider { + + @Override + public DriverManagerDataSource produce() { + return new DriverManagerDataSource(); + } +} diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/GeneralDatabaseOperationGateway.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/GeneralDatabaseOperationGateway.java new file mode 100644 index 0000000..59bc9e6 --- /dev/null +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/GeneralDatabaseOperationGateway.java @@ -0,0 +1,155 @@ +package pl.gov.coi.cascades.server; + +import lombok.AllArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; +import pl.gov.coi.cascades.contract.domain.DatabaseType; +import pl.gov.coi.cascades.contract.domain.NetworkBind; +import pl.gov.coi.cascades.contract.domain.Template; +import pl.gov.coi.cascades.server.domain.DatabaseInstance; +import pl.gov.coi.cascades.server.domain.DatabaseOperationsGateway; +import pl.gov.coi.cascades.server.domain.DatabaseTypeImpl; +import pl.wavesoftware.eid.exceptions.EidIllegalArgumentException; + +import java.sql.SQLException; +import java.util.Optional; + +/** + * @author Łukasz Małek + */ +@AllArgsConstructor +public class GeneralDatabaseOperationGateway implements DatabaseOperationsGateway { + + private static final String ORACLE = "ora12c"; + private static final String POSTGRESQL = "pgsql"; + + private ServerConfigurationService serverConfigurationService; + private DatabaseManager databaseManager; + + @Override + public DatabaseInstance createDatabase(DatabaseInstance databaseInstance) { + Template template = databaseInstance.getTemplate(); + if (template != null) { + DatabaseInstance databaseInstanceWithSettings = databaseInstance + .setNetworkBind(getNetworkBind(template)) + .setDatabaseType(getDatabaseType(template)); + + createDatabseInstance(databaseInstanceWithSettings); + + return databaseInstanceWithSettings; + } + + throw new EidIllegalArgumentException( + "20180706:151316", + "Template hasn't been found." + ); + } + + private void createDatabseInstance(DatabaseInstance databaseInstance) { + String databaseType = databaseInstance.getDatabaseType().getName(); + ConnectionDatabase connectionDatabase = createConnectionToServer(databaseInstance.getTemplate()); + + if (databaseType.contains(POSTGRESQL)) { + String postgresCreateCommands = getPostgresCreateCommands(databaseInstance); + runSemicolonSeperatedSQL(connectionDatabase, postgresCreateCommands); + } else if (databaseType.contains(ORACLE)) { + String oracleCreateCommands = getOracleCreateCommands(databaseInstance); + runSemicolonSeperatedSQL(connectionDatabase, oracleCreateCommands); + + } else { + throw new EidIllegalArgumentException( + "20180711:120816", + "Hasn't been found database type." + ); + } + } + + private String getPostgresCreateCommands(DatabaseInstance databaseInstance) { + String templateName = databaseInstance.getTemplate().getName(); + String databaseName = databaseInstance.getDatabaseName(); + + return String.format("CREATE DATABASE %s TEMPLATE %s", + databaseName, + templateName + ); + } + + private String getOracleCreateCommands(DatabaseInstance databaseInstance) { + String templateName = databaseInstance.getTemplate().getName(); + String databaseName = databaseInstance.getDatabaseName(); + return new StringBuilder() + .append("ALTER SESSION SET container = CDB$ROOT;") + .append(String.format("CREATE PLUGGABLE DATABASE %s from %s", + databaseName, + templateName)) + .append(String.format( + " file_name_convert = ('/u01/app/oracle/oradata/orcl12c/%s', '/u01/app/oracle/oradata/orcl12c/%s');", + templateName, + databaseName + )).append(String.format( + "ALTER PLUGGABLE DATABASE %s OPEN READ WRITE;", + databaseName + )).toString(); + } + + @Override + @Deprecated + public void deleteDatabase(DatabaseInstance databaseInstance) { + // TODO: write implementation + throw new UnsupportedOperationException("Not yet implemented!"); + } + + private NetworkBind getNetworkBind(Template template) { + ServerDef serverDef = findServerDef(template); + String host = serverDef.getHost(); + int port = serverDef.getPort(); + + if (StringUtils.isNotBlank(host) && port != 0) { + return new NetworkBindImpl(host, port); + } + + throw new EidIllegalArgumentException( + "20180628:191916", + "Hasn't been found connection settings." + ); + } + + private DatabaseType getDatabaseType(Template template) { + ServerDef serverDef = findServerDef(template); + if (serverDef != null && StringUtils.isNotBlank(serverDef.getType())) { + return new DatabaseTypeImpl(serverDef.getType()); + } + + throw new EidIllegalArgumentException( + "20180706:151716", + "Hasn't been found database type." + ); + } + + private ServerDef findServerDef(Template template) { + Optional correctServerDef = serverConfigurationService + .getManagedServers() + .stream() + .filter(p -> p.getServerId() + .equalsIgnoreCase(template.getServerId()) + ) + .findFirst(); + + return correctServerDef.orElse(null); + } + + private ConnectionDatabase createConnectionToServer(Template template) { + try { + return databaseManager.getConnectionToServer(template.getServerId()); + } catch (SQLException e) { + throw new EidIllegalArgumentException("20180711:114808", e); + } + } + + private void runSemicolonSeperatedSQL(ConnectionDatabase connectionDatabase, String createDatabaseCommand) { + String[] queries = createDatabaseCommand.split(";"); + for (String str : queries) { + connectionDatabase.getJdbcTemplate().execute(str); + } + } +} diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/GeneralTemplateGateway.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/GeneralTemplateGateway.java index c7cf476..84a1a5b 100644 --- a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/GeneralTemplateGateway.java +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/GeneralTemplateGateway.java @@ -21,6 +21,8 @@ public class GeneralTemplateGateway implements DatabaseTemplateGateway { private static final Logger DEFAULT_LOGGER = LoggerFactory.getLogger(GeneralTemplateGateway.class); + private static final String ORACLE = "oracle"; + private static final String POSTGRESQL = "postgresql"; private Logger logger; private DatabaseManager databaseManager; @@ -41,58 +43,72 @@ public class GeneralTemplateGateway implements DatabaseTemplateGateway { @Override public void createTemplate(Template template, Path deploySQLScriptPath) { try { - ConnectionDatabase connectionDatabase = databaseManager.get(template.getServerId()); - StringBuilder commands = new StringBuilder(); - String script = readFileAsString(deploySQLScriptPath); - - if (connectionDatabase.getType().contains("oracle")) { - commands.append(getOracleStartCommands(template)); - } else if (connectionDatabase.getType().contains("postgresql")) { - commands.append(getPostgresStartCommands(template)); - } - String[] queries = commands - .append(script) - .toString() - .split(";"); - for (String str : queries) { - connectionDatabase.getJdbcTemplate().execute(str); - } + ConnectionDatabase connectionDatabase = databaseManager.getConnectionToServer(template.getServerId()); + runCreateDatabaseCommand(connectionDatabase, template); + ConnectionDatabase connectionToTemplate = databaseManager.getConnectionToDatabase(template.getServerId(), template.getName()); + runDeployScript(connectionToTemplate, deploySQLScriptPath); + runAfterDeployScript(connectionToTemplate, template); } catch (SQLException e) { throw new EidIllegalArgumentException("20170711:151221", e); } } + private void runDeployScript(ConnectionDatabase connectionToTemplate, Path deploySQLScriptPath) { + String deployScript = readFileAsString(deploySQLScriptPath); + runSemicolonSeperatedSQL(connectionToTemplate, deployScript); + } + + private void runAfterDeployScript(ConnectionDatabase connectionToTemplate, Template template) { + if (connectionToTemplate.getType().contains(POSTGRESQL)) { + runSemicolonSeperatedSQL(connectionToTemplate, String.format( + "UPDATE pg_database SET datistemplate = TRUE WHERE datname = '%s';" + + "UPDATE pg_database SET datallowconn = FALSE WHERE datname = '%s'", + template.getName(), template.getName() + )); + } + } + + private void runCreateDatabaseCommand(ConnectionDatabase connectionDatabase, Template template) { + String createDatabaseCommand = ""; + if (connectionDatabase.getType().contains(ORACLE)) { + createDatabaseCommand = getOracleStartCommands(template.getName()); + } else if (connectionDatabase.getType().contains(POSTGRESQL)) { + createDatabaseCommand = getPostgresStartCommands(template.getName()); + } + runSemicolonSeperatedSQL(connectionDatabase, createDatabaseCommand); + } + + private void runSemicolonSeperatedSQL(ConnectionDatabase connectionDatabase, String createDatabaseCommand) { + String[] queries = createDatabaseCommand.split(";"); + for (String str : queries) { + connectionDatabase.getJdbcTemplate().execute(str); + } + } + @Override public void deleteTemplate(Template template) { try { - ConnectionDatabase connectionDatabase = databaseManager.get(template.getServerId()); + ConnectionDatabase connectionDatabase = databaseManager.getConnectionToServer(template.getServerId()); StringBuilder commands = new StringBuilder(); - if (connectionDatabase.getType().contains("ora12c")) { - commands.append(getOracleFinishCommands(template)); - } else if (connectionDatabase.getType().contains("pgsql")) { - commands.append(getPostgresFinishCommands(template)); + if (connectionDatabase.getType().contains(ORACLE)) { + commands.append(getOracleFinishCommands(template.getName())); + } else if (connectionDatabase.getType().contains(POSTGRESQL)) { + commands.append(getPostgresFinishCommands(template.getName())); } - String[] queries = commands - .toString() - .split(";"); - for (String str : queries) { - connectionDatabase.getJdbcTemplate().execute(str); - } + runSemicolonSeperatedSQL(connectionDatabase, commands + .toString()); } catch (SQLException e) { throw new EidIllegalArgumentException("20170726:135511", e); } } - private static StringBuilder getPostgresFinishCommands(Template template) { - StringBuilder commands = new StringBuilder(); - String deleteQuery = String.format( + private static String getPostgresFinishCommands(String templateName) { + return String.format( "DROP DATABASE %s;", - template.getName() + templateName ); - commands.append(deleteQuery); - return commands; } private static String readFileAsString(Path deploySQLScriptPath) { @@ -106,46 +122,42 @@ private static String readFileAsString(Path deploySQLScriptPath) { return fileData.toString(); } - private static StringBuilder getOracleStartCommands(Template template) { - StringBuilder commands = new StringBuilder(); - String createQuery = String.format( - "CREATE PLUGGABLE DATABASE %s ADMIN USER admin IDENTIFIED BY ksdn#2Hd;", - template.getName() - ); - String alterQuery = String.format( - "ALTER PLUGGABLE DATABASE %s OPEN READ WRITE;", - template.getName() - ); - commands.append(createQuery).append(alterQuery); - return commands; + private static String getOracleStartCommands(String templateName) { + return new StringBuilder().append("ALTER SESSION SET container = CDB$ROOT;") + .append(String.format( + "CREATE PLUGGABLE DATABASE %s ADMIN USER admin IDENTIFIED BY ksdn#2Hd", + templateName + )).append(String.format( + " file_name_convert = ('/u01/app/oracle/oradata/orcl12c/pdbseed', '/u01/app/oracle/oradata/orcl12c/%s');", + templateName + )).append(String.format( + "ALTER PLUGGABLE DATABASE %s OPEN READ WRITE;", + templateName + )).toString(); } - private static StringBuilder getPostgresStartCommands(Template template) { - StringBuilder commands = new StringBuilder(); - String createQuery = String.format( + private static String getPostgresStartCommands(String templateName) { + return String.format( "CREATE DATABASE %s TEMPLATE template0;", - template.getName() + templateName ); - commands.append(createQuery); - return commands; } - private static StringBuilder getOracleFinishCommands(Template template) { - StringBuilder commands = new StringBuilder(); - String disconnectQuery = String.format( - "ALTER PLUGGABLE DATABASE %s CLOSE IMMEDIATE;", - template.getName() - ); - String deleteQuery = String.format( - "DROP PLUGGABLE DATABASE %s INCLUDING DATAFILES;", - template.getName() - ); - commands.append(disconnectQuery).append(deleteQuery); - return commands; + private static String getOracleFinishCommands(String templateName) { + return new StringBuilder() + .append(String.format( + "ALTER PLUGGABLE DATABASE %s CLOSE IMMEDIATE;", + templateName + )).append(String.format( + "DROP PLUGGABLE DATABASE %s INCLUDING DATAFILES;", + templateName + )).toString(); } @Override + @Deprecated public boolean canBeRemoved(Template template) { - return false; + //TODO: implement this + throw new UnsupportedOperationException(); } } diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/GeneralUserGateway.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/GeneralUserGateway.java new file mode 100644 index 0000000..f1bd5ef --- /dev/null +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/GeneralUserGateway.java @@ -0,0 +1,171 @@ +package pl.gov.coi.cascades.server; + +import lombok.AllArgsConstructor; +import pl.gov.coi.cascades.contract.domain.Template; +import pl.gov.coi.cascades.contract.domain.UsernameAndPasswordCredentials; +import pl.gov.coi.cascades.server.domain.DatabaseInstance; +import pl.gov.coi.cascades.server.domain.DatabaseUserGateway; +import pl.wavesoftware.eid.exceptions.EidIllegalArgumentException; + +import java.sql.SQLException; + +/** + * @author Łukasz Małek + */ +@AllArgsConstructor +public class GeneralUserGateway implements DatabaseUserGateway { + + private static final String ORACLE = "ora12c"; + private static final String POSTGRESQL = "pgsql"; + private DatabaseManager databaseManager; + + @Override + public void createUser(DatabaseInstance databaseInstance) { + String databaseType = databaseInstance.getDatabaseType().getName(); + + if (databaseType.contains(POSTGRESQL)) { + ConnectionDatabase connectionDatabase = createConnectionToServer(databaseInstance.getTemplate()); + String postgresCommands = getPostgresCreateUserCommands(databaseInstance); + runSemicolonSeperatedSQL(connectionDatabase, postgresCommands); + + } else if (databaseType.contains(ORACLE)) { + ConnectionDatabase connectionDatabase = createConnectionToDatabase(databaseInstance); + String oracleCommands = getOracleCreateUserCommands(databaseInstance); + runSemicolonSeperatedSQL(connectionDatabase, oracleCommands); + } else { + throw new EidIllegalArgumentException( + "20180711:110816", + "Hasn't been found database type." + ); + } + } + + @Override + public void deleteUser(DatabaseInstance databaseInstance) { + String databaseType = databaseInstance.getDatabaseType().getName(); + + if (databaseType.contains(POSTGRESQL)) { + ConnectionDatabase connectionDatabase = createConnectionToServer(databaseInstance.getTemplate()); + String postgresCommands = getPostgresDeleteUserCommands( + databaseInstance.getDatabaseName(), + databaseInstance.getCredentials().getUsername() + ); + + runSemicolonSeperatedSQL(connectionDatabase, postgresCommands); + + } else if (databaseType.contains(ORACLE)) { + ConnectionDatabase connectionDatabase = createConnectionToDatabase(databaseInstance); + String oracleCommands = getOracleDeleteUserCommands( + databaseInstance.getCredentials().getUsername() + ); + + runSemicolonSeperatedSQL(connectionDatabase, oracleCommands); + } + + } + + private ConnectionDatabase createConnectionToServer(Template template) { + try { + return databaseManager.getConnectionToServer(template.getServerId()); + } catch (SQLException e) { + throw new EidIllegalArgumentException("20180704:102108", e); + } + } + + private ConnectionDatabase createConnectionToDatabase(DatabaseInstance databaseInstance) { + try { + return databaseManager.getConnectionToDatabase(databaseInstance.getTemplate().getServerId(), databaseInstance.getDatabaseName()); + } catch (SQLException e) { + throw new EidIllegalArgumentException("20180711:095808", e); + } + } + + private String getPostgresCreateUserCommands(DatabaseInstance databaseInstance) { + StringBuilder command = new StringBuilder(); + UsernameAndPasswordCredentials credentials = databaseInstance.getCredentials(); + + command.append(getPostgresCreateUser(credentials)); + command.append(getPostgresPermissions( + databaseInstance.getDatabaseName(), + credentials.getUsername()) + ); + + return command.toString(); + } + + private String getOracleCreateUserCommands(DatabaseInstance databaseInstance) { + StringBuilder command = new StringBuilder(); + UsernameAndPasswordCredentials credentials = databaseInstance.getCredentials(); + + command.append(getOracleCreateUser(credentials)); + command.append(getOraclePermissions( + credentials.getUsername()) + ); + + return command.toString(); + } + + + private String getPostgresCreateUser(UsernameAndPasswordCredentials credentials) { + return String.format( + "CREATE USER %s WITH ENCRYPTED PASSWORD '%s';", + credentials.getUsername(), + credentials.getPassword() + ); + } + + private String getPostgresPermissions(String databaseName, String username) { + return String.format( + "GRANT ALL PRIVILEGES ON DATABASE %s TO %s;", + databaseName, + username + ); + } + + private String getOracleCreateUser(UsernameAndPasswordCredentials credentials) { + return String.format( + "CREATE USER %s IDENTIFIED BY \"%s\";", + credentials.getUsername(), + credentials.getPassword() + ); + } + + private String getOraclePermissions(String username) { + return String.format( + "GRANT DBA TO %s;", + username + ); + } + + private String getPostgresDeleteUserCommands(String databaseName, String username) { + StringBuilder commands = new StringBuilder(); + commands.append(String.format( + "REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM %s;", + username + )).append(String.format( + "REVOKE ALL ON DATABASE %s FROM %s;", + databaseName, + username + )).append(String.format( + "DROP USER %s;", + username + )); + + return commands.toString(); + } + + private String getOracleDeleteUserCommands(String username) { + return String.format( + "DROP USER %s;", + username + ); + + } + + private void runSemicolonSeperatedSQL(ConnectionDatabase connectionDatabase, String createDatabaseCommand) { + String[] queries = createDatabaseCommand.split(";"); + for (String str : queries) { + connectionDatabase.getJdbcTemplate().execute(str); + } + } +} diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/NetworkBindImpl.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/NetworkBindImpl.java new file mode 100644 index 0000000..4802500 --- /dev/null +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/NetworkBindImpl.java @@ -0,0 +1,16 @@ +package pl.gov.coi.cascades.server; + + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import pl.gov.coi.cascades.contract.domain.NetworkBind; + +@AllArgsConstructor +@Getter +@Setter +public class NetworkBindImpl implements NetworkBind { + + private String host; + private int port; +} diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ServerDef.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ServerDef.java index cdf717c..0b9dd5e 100644 --- a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ServerDef.java +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/ServerDef.java @@ -2,19 +2,15 @@ import lombok.AllArgsConstructor; import lombok.Data; -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import lombok.Setter; +import lombok.NoArgsConstructor; /** * @author Agnieszka Celuch * @since 26.07.17 */ @Data -@Getter -@Setter +@NoArgsConstructor @AllArgsConstructor -@RequiredArgsConstructor public class ServerDef { private String serverId; private String type; @@ -23,4 +19,21 @@ public class ServerDef { private String password; private String host; private int port; + + /** + * Get new {@link ServerDef} instance with the same data expect database name. + * @param newDatabaseName new database name + * @return new instance with new database name + */ + public ServerDef getWithNewDatabaseName(String newDatabaseName) { + return new ServerDef( + this.serverId, + this.type, + newDatabaseName, + this.user, + this.password, + this.host, + this.port + ); + } } diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/domain/DomainConfiguration.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/domain/DomainConfiguration.java index 2eaaa61..afc043c 100644 --- a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/domain/DomainConfiguration.java +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/domain/DomainConfiguration.java @@ -36,12 +36,16 @@ UseCase produceLaunchNewDatabaseUseCase(LaunchNewDatabaseGatewayFacade launchNew LaunchNewDatabaseGatewayFacade produceGateways(TemplateIdGateway templateIdGateway, UserGateway userGateway, DatabaseLimitGateway databaseLimitGateway, - DatabaseInstanceGateway databaseInstanceGateway) { + DatabaseInstanceGateway databaseInstanceGateway, + DatabaseOperationsGateway databaseOperationsGateway, + DatabaseUserGateway databaseUserGateway) { return new LaunchNewDatabaseGatewayFacade( templateIdGateway, userGateway, databaseLimitGateway, - databaseInstanceGateway + databaseInstanceGateway, + databaseOperationsGateway, + databaseUserGateway ); } diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/domain/OsgiDatabaseTypeClassNameService.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/domain/OsgiDatabaseTypeClassNameService.java index 2846437..882cc1a 100644 --- a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/domain/OsgiDatabaseTypeClassNameService.java +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/domain/OsgiDatabaseTypeClassNameService.java @@ -5,6 +5,7 @@ import org.slf4j.LoggerFactory; import pl.gov.coi.cascades.contract.domain.DatabaseType; import pl.gov.coi.cascades.server.OsgiBeanLocator; +import pl.gov.coi.cascades.server.persistance.stub.DatabaseTypeStub; import pl.wavesoftware.eid.exceptions.Eid; import javax.inject.Inject; diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/persistance/hibernate/HibernateConfiguration.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/persistance/hibernate/HibernateConfiguration.java index 092a345..131d00f 100644 --- a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/persistance/hibernate/HibernateConfiguration.java +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/persistance/hibernate/HibernateConfiguration.java @@ -37,8 +37,8 @@ DatabaseIdGateway createDatabaseIdGateway(DatabaseInstanceMapper databaseInstanc } @Bean - DatabaseInstanceGateway createDatabaseInstanceGateway() { - return new DatabaseInstanceGatewayImpl(); + DatabaseInstanceGateway createDatabaseInstanceGateway(DatabaseInstanceMapper databaseInstanceMapper) { + return new DatabaseInstanceGatewayImpl(databaseInstanceMapper); } @Bean diff --git a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/persistance/stub/PersistanceStubByDefaultOnDevelopmentAutoConfiguration.java b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/persistance/stub/PersistanceStubByDefaultOnDevelopmentAutoConfiguration.java index 9d5618b..4f4228c 100644 --- a/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/persistance/stub/PersistanceStubByDefaultOnDevelopmentAutoConfiguration.java +++ b/cascades-server/configuration/src/main/java/pl/gov/coi/cascades/server/persistance/stub/PersistanceStubByDefaultOnDevelopmentAutoConfiguration.java @@ -9,7 +9,9 @@ import pl.gov.coi.cascades.server.domain.DatabaseIdGateway; import pl.gov.coi.cascades.server.domain.DatabaseInstanceGateway; import pl.gov.coi.cascades.server.domain.DatabaseLimitGateway; +import pl.gov.coi.cascades.server.domain.DatabaseOperationsGateway; import pl.gov.coi.cascades.server.domain.DatabaseTemplateGateway; +import pl.gov.coi.cascades.server.domain.DatabaseUserGateway; import pl.gov.coi.cascades.server.domain.TemplateIdGateway; import pl.gov.coi.cascades.server.domain.User; import pl.gov.coi.cascades.server.domain.UserGateway; @@ -40,6 +42,12 @@ DatabaseTemplateGateway produceDatabaseTemplateGateway() { return new DatabaseTemplateGatewayStub(); } + @ConditionalOnMissingBean + @Bean + DatabaseUserGateway produceDatabaseUserGateway() { + return new DatabaseUserGatewayStub(); + } + @ConditionalOnMissingBean @Bean TemplateIdGateway produceTemplateIdGateway() { @@ -52,6 +60,12 @@ DatabaseInstanceGateway produceDatabaseInstanceGateway() { return new DatabaseInstanceGatewayStub(); } + @ConditionalOnMissingBean + @Bean + DatabaseOperationsGateway produceDatabaseOperations() { + return new DatabaseOperationsStub(); + } + @ConditionalOnMissingBean @Bean UserGateway produceUserGateway(@Named(STUB_DATABASE) Map database) { diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ConnectionConfigurationTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ConnectionConfigurationTest.java index e708388..b76cfc9 100644 --- a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ConnectionConfigurationTest.java +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ConnectionConfigurationTest.java @@ -32,7 +32,7 @@ public void testGetDriver() throws Exception { ); // when - String actual = connectionConfiguration.getDriver(); + String actual = connectionConfiguration.getDriverClass(); // then assertThat(actual).isNotNull(); @@ -50,7 +50,7 @@ public void testGetUrl() throws Exception { ); // when - String actual = connectionConfiguration.getUrl(); + String actual = connectionConfiguration.getJdbcUrlTemplate(); // then assertThat(actual).isNotNull(); diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ConnectionConfiguratorTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ConnectionConfiguratorTest.java index c13c35e..acf2457 100644 --- a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ConnectionConfiguratorTest.java +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ConnectionConfiguratorTest.java @@ -3,7 +3,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import pl.wavesoftware.eid.exceptions.EidIllegalArgumentException; @@ -16,101 +15,54 @@ */ public class ConnectionConfiguratorTest { - @Mock - private ServerConfigurationService service; - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Rule public ExpectedException expectedException = ExpectedException.none(); + private ConnectionConfigurator connectionConfigurator = new ConnectionConfigurator(); + @Test - public void testGetConnectionConfigurationWhenThereIsError() throws Exception { + public void testGetConnectionConfigurationForNotSupportedType() { // given - String serverId = "Baza_dla_testu_C2DEV"; - String type = "mysql"; - String dbname = "C2DEV"; - String user = "C##DEPLOY"; - String password = "ksSdf#231n#dD"; - String host = "172.31.20.24"; - int port = 1521; - ServerDef serverDef = new ServerDef( - serverId, - type, - dbname, - user, - password, - host, - port - ); - ConnectionConfigurator connectionConfigurator = new ConnectionConfigurator(); + String notSupportedType = "mysql"; // then expectedException.expect(EidIllegalArgumentException.class); expectedException.expectMessage("20170728:150904"); - expectedException.expectMessage("Given driver hasn't been recognised."); + expectedException.expectMessage("Given database type 'mysql' hasn't been recognised."); // when - connectionConfigurator.getConnectionConfiguration(serverDef); + connectionConfigurator.getConnectionConfiguration(notSupportedType); } @Test - public void testGetConnectionConfigurationWhenThereIsOracleDriver() throws Exception { + public void testGetConnectionConfigurationForOracle() { // given - String serverId = "Baza_dla_testu_C2DEV"; - String type = "ora12c"; - String dbname = "C2DEV"; - String user = "C##DEPLOY"; - String password = "ksSdf#231n#dD"; - String host = "172.31.20.24"; - int port = 1521; - ServerDef serverDef = new ServerDef( - serverId, - type, - dbname, - user, - password, - host, - port - ); - ConnectionConfigurator connectionConfigurator = new ConnectionConfigurator(); + String oracleType = "ora12c"; // when - ConnectionConfiguration actual = connectionConfigurator.getConnectionConfiguration(serverDef); + ConnectionConfiguration actual = connectionConfigurator.getConnectionConfiguration(oracleType); // then assertThat(actual).isNotNull(); - assertThat(actual.getUrl()).contains("oracle"); + assertThat(actual.getDriverClass()).isEqualTo("oracle.jdbc.OracleDriver"); + assertThat(actual.getJdbcUrlTemplate()).isEqualTo("jdbc:oracle:thin:@//%s:%d/%s"); } @Test - public void testGetConnectionConfigurationWhenThereIsPostgresDriver() throws Exception { + public void testGetConnectionConfigurationForPostgreSQL() { // given - String serverId = "Baza_dla_testu_postgres"; - String type = "pgsql"; - String dbname = "postgres"; - String user = "postgres"; - String password = "12345678"; - String host = "localhost"; - int port = 1521; - ServerDef serverDef = new ServerDef( - serverId, - type, - dbname, - user, - password, - host, - port - ); - ConnectionConfigurator connectionConfigurator = new ConnectionConfigurator(); + String postgreSQLType = "pgsql"; // when - ConnectionConfiguration actual = connectionConfigurator.getConnectionConfiguration(serverDef); + ConnectionConfiguration actual = connectionConfigurator.getConnectionConfiguration(postgreSQLType); // then assertThat(actual).isNotNull(); - assertThat(actual.getUrl()).contains("postgres"); + assertThat(actual.getDriverClass()).isEqualTo("org.postgresql.Driver"); + assertThat(actual.getJdbcUrlTemplate()).isEqualTo("jdbc:postgresql://%s:%d/%s"); } } diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DatabaseEndpointConfigurationTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DatabaseEndpointConfigurationTest.java index 98bed68..da32a59 100644 --- a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DatabaseEndpointConfigurationTest.java +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DatabaseEndpointConfigurationTest.java @@ -6,12 +6,14 @@ import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import pl.gov.coi.cascades.server.domain.DatabaseOperationsGateway; import pl.gov.coi.cascades.server.domain.DatabaseTemplateGateway; import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; /** * @author Agnieszka Celuch @@ -22,71 +24,107 @@ public class DatabaseEndpointConfigurationTest { @Mock private DatabaseManager databaseManager; + @Mock + private DriverManagerDataSourceHelper driverManagerDataSourceHelper; + @Mock private ConnectionConfigurator connectionConfigurator; @Mock - private ServerConfigurationService service; + private ServerConfigurationService serverConfigurationService; + + @Mock + private DriverManagerDataSourceProvider driverManagerDataSourceProvider; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Test - public void testProduceConnectionConfiguration() throws Exception { - // given - DatabaseEndpointConfiguration conf = new DatabaseEndpointConfiguration(); + private DatabaseEndpointConfiguration databaseEndpointConfiguration = new DatabaseEndpointConfiguration(); + @Test + public void testProduceConnectionConfiguration() { // when - ConnectionConfigurator actual = conf.produceConnectionConfiguration(); + ConnectionConfigurator actual = databaseEndpointConfiguration.produceConnectionConfiguration(); // then assertThat(actual).isNotNull(); } @Test - public void testProduceDriverManagerDataSourceWhenMapIsEmpty() throws Exception { + public void testProduceDriverManagerDataSourceWhenMapIsEmpty() { // given - DatabaseEndpointConfiguration conf = new DatabaseEndpointConfiguration(); + Map expectedMap = new HashMap<>(); + when(driverManagerDataSourceHelper.getManagersMap()).thenReturn(expectedMap); // when - Map actual = conf.produceDriverManagerDataSource( - service, - connectionConfigurator + Map actual = databaseEndpointConfiguration.produceDriverManagerDataSource( + driverManagerDataSourceHelper ); // then - assertThat(actual).isEmpty(); + assertThat(actual).isEqualTo(expectedMap); } @Test - public void testProduceDatabaseTemplateGateway() throws Exception { - // given - DatabaseEndpointConfiguration conf = new DatabaseEndpointConfiguration(); - + public void testProduceDatabaseTemplateGateway() { // when - DatabaseTemplateGateway actual = conf.produceDatabaseTemplateGateway( + DatabaseTemplateGateway actual = databaseEndpointConfiguration.produceDatabaseTemplateGateway( databaseManager ); // then assertThat(actual).isNotNull(); - assertThat(actual).isInstanceOf(DatabaseTemplateGateway.class); + assertThat(actual).isInstanceOf(GeneralTemplateGateway.class); } @Test - public void testProduceDatabaseManager() throws Exception { + public void testProduceDatabaseManager() { // given - DatabaseEndpointConfiguration conf = new DatabaseEndpointConfiguration(); Map drivers = new HashMap<>(); // when - DatabaseManager actual = conf.produceDatabaseManager( - drivers + DatabaseManager actual = databaseEndpointConfiguration.produceDatabaseManager( + drivers, + driverManagerDataSourceHelper + ); + + // then + assertThat(actual).isNotNull(); + assertThat(actual).isInstanceOf(DatabaseEndpointManager.class); + } + + @Test + public void testProduceDriverManagerDataSourceHelper() { + // when + DriverManagerDataSourceHelper actual = databaseEndpointConfiguration.produceDriverManagerDataSourceHelper( + connectionConfigurator, + serverConfigurationService, + driverManagerDataSourceProvider + ); + + // then + assertThat(actual).isNotNull(); + } + + @Test + public void testProduceDriverManagerDataSourceProvider() { + // when + DriverManagerDataSourceProvider actual = databaseEndpointConfiguration.produceDriverManagerDataSourceProvider(); + + // then + assertThat(actual).isNotNull(); + } + + @Test + public void shouldProduceDatabaseOperationsGateway() { + // when + DatabaseOperationsGateway actual = databaseEndpointConfiguration.produceDatabaseOperationGateway( + serverConfigurationService, + databaseManager ); // then assertThat(actual).isNotNull(); - assertThat(actual).isInstanceOf(DatabaseManager.class); } } diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DatabaseEndpointManagerTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DatabaseEndpointManagerTest.java index c834b23..17953c0 100644 --- a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DatabaseEndpointManagerTest.java +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DatabaseEndpointManagerTest.java @@ -1,5 +1,6 @@ package pl.gov.coi.cascades.server; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -13,6 +14,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; /** * @author Agnieszka Celuch @@ -23,44 +25,62 @@ public class DatabaseEndpointManagerTest { @Mock private DriverManagerDataSource driverManagerDataSource; + @Mock + private DriverManagerDataSourceHelper driverManagerDataSourceHelper; + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Rule public ExpectedException expectedException = ExpectedException.none(); - @Test - public void testGetWhenErrorOccurred() throws Exception { - // given + private DatabaseEndpointManager databaseEndpointManager; + + @Before + public void setup() { Map managerDataSourceMap = new HashMap<>(); managerDataSourceMap.put("test", driverManagerDataSource); - DatabaseEndpointManager databaseEndpointManager = new DatabaseEndpointManager( - managerDataSourceMap + databaseEndpointManager = new DatabaseEndpointManager( + managerDataSourceMap, + driverManagerDataSourceHelper ); + when(driverManagerDataSource.getUrl()).thenReturn("jdbc://database:123"); + } + @Test + public void testGetWhenErrorOccurred() { // then expectedException.expect(EidIllegalArgumentException.class); expectedException.expectMessage("20170726:121616"); expectedException.expectMessage("Given serverId hasn't been found."); // when - databaseEndpointManager.get("not_existing_key"); + databaseEndpointManager.getConnectionToServer("not_existing_key"); } @Test - public void testGet() throws Exception { + public void testGetConnectionToServer() { + // when + ConnectionDatabase actual = databaseEndpointManager.getConnectionToServer("test"); + + // then + assertThat(actual).isNotNull(); + assertThat(actual.getType()).isEqualTo("jdbc://database:123"); + assertThat(actual.getJdbcTemplate().getDataSource()).isEqualTo(driverManagerDataSource); + } + + @Test + public void testGetConnectionToTemplate() { // given - Map managerDataSourceMap = new HashMap<>(); - managerDataSourceMap.put("test", driverManagerDataSource); - DatabaseEndpointManager databaseEndpointManager = new DatabaseEndpointManager( - managerDataSourceMap - ); + when(driverManagerDataSourceHelper.getManager("serverId", "templateName")).thenReturn(driverManagerDataSource); // when - ConnectionDatabase actual = databaseEndpointManager.get("test"); + ConnectionDatabase actual = databaseEndpointManager.getConnectionToDatabase("serverId", "templateName"); // then assertThat(actual).isNotNull(); + assertThat(actual.getType()).isEqualTo("jdbc://database:123"); + assertThat(actual.getJdbcTemplate().getDataSource()).isEqualTo(driverManagerDataSource); } } diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DriverManagerDataSourceHelperTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DriverManagerDataSourceHelperTest.java new file mode 100644 index 0000000..37c5760 --- /dev/null +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DriverManagerDataSourceHelperTest.java @@ -0,0 +1,129 @@ +package pl.gov.coi.cascades.server; + +import org.assertj.core.util.Lists; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import pl.wavesoftware.eid.exceptions.EidIllegalStateException; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * @author Mariusz Wyszomierski + */ +public class DriverManagerDataSourceHelperTest { + + @InjectMocks + private DriverManagerDataSourceHelper dataSourceHelper; + + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Mock + private ServerConfigurationService serverConfigurationService; + + @Mock + private DriverManagerDataSourceProvider driverManagerDataSourceProvider; + + @Mock + private DriverManagerDataSource driverManagerDataSource; + + @Mock + private ConnectionConfigurator connectionConfigurator; + + private static ServerDef SERVER_DEF; + private static ConnectionConfiguration CONNECTION_CONFIGURATION; + + @Before + public void setup() { + String serverId = "serverId"; + String type = "oracle"; + String dbname = "dev"; + String user = "user"; + String password = "password"; + String host = "host.db"; + int port = 123; + SERVER_DEF = new ServerDef( + serverId, + type, + dbname, + user, + password, + host, + port + ); + String urlTemplate = "jdbc://%s:%s/%s"; + String driverClass = "db.driver.class"; + CONNECTION_CONFIGURATION = new ConnectionConfiguration(driverClass, urlTemplate); + when(serverConfigurationService.getManagedServers()).thenReturn(Lists.newArrayList( + SERVER_DEF + )); + when(connectionConfigurator.getConnectionConfiguration(type)).thenReturn(CONNECTION_CONFIGURATION); + when(driverManagerDataSourceProvider.produce()).thenReturn(driverManagerDataSource); + } + + @Test + public void testGetManager() { + //when + DriverManagerDataSource result = dataSourceHelper.getManager("serverId", "databaseName"); + + //then + assertDriverManagerDataSource(result, "jdbc://host.db:123/databaseName"); + } + + @Test + public void testGetManagerWhenServerIdDoesntExists() { + //then + expectedException.expect(EidIllegalStateException.class); + expectedException.expectMessage("20180625:205951"); + expectedException.expectMessage("There is no configuration for serverId: NotExistingServerId"); + + //when + dataSourceHelper.getManager("NotExistingServerId", "databaseName"); + } + + @Test + public void testGetManagersMap() { + //when + Map resultMap = dataSourceHelper.getManagersMap(); + + //then + assertThat(resultMap.size()).isEqualTo(1); + DriverManagerDataSource dataSource = resultMap.get("serverId"); + assertDriverManagerDataSource(dataSource, "jdbc://host.db:123/dev"); + } + + private void assertDriverManagerDataSource(DriverManagerDataSource dataSource, String url) { + assertThat(dataSource).isNotNull(); + assertThat(dataSource).isEqualTo(driverManagerDataSource); + verify(driverManagerDataSource).setDriverClassName(CONNECTION_CONFIGURATION.getDriverClass()); + verify(driverManagerDataSource).setUrl(url); + verify(driverManagerDataSource).setPassword(SERVER_DEF.getPassword()); + verify(driverManagerDataSource).setUsername(SERVER_DEF.getUser()); + } + + @Test + public void testGetManagersMapReturnEmptyMap() { + //given + when(serverConfigurationService.getManagedServers()).thenReturn(Lists.emptyList()); + + //when + Map resultMap = dataSourceHelper.getManagersMap(); + + //then + assertThat(resultMap.size()).isEqualTo(0); + } +} diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DriverManagerDataSourceProviderImplTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DriverManagerDataSourceProviderImplTest.java new file mode 100644 index 0000000..796a851 --- /dev/null +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/DriverManagerDataSourceProviderImplTest.java @@ -0,0 +1,20 @@ +package pl.gov.coi.cascades.server; + +import org.junit.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DriverManagerDataSourceProviderImplTest { + + private DriverManagerDataSourceProviderImpl provider = new DriverManagerDataSourceProviderImpl(); + + @Test + public void produce() { + //when + DriverManagerDataSource result = provider.produce(); + + //then + assertThat(result).isNotNull(); + } +} diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/GeneralDatabaseOperationGatewayTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/GeneralDatabaseOperationGatewayTest.java new file mode 100644 index 0000000..68c45a7 --- /dev/null +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/GeneralDatabaseOperationGatewayTest.java @@ -0,0 +1,251 @@ +package pl.gov.coi.cascades.server; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.springframework.jdbc.core.JdbcTemplate; +import pl.gov.coi.cascades.contract.domain.DatabaseId; +import pl.gov.coi.cascades.contract.domain.Template; +import pl.gov.coi.cascades.server.domain.DatabaseInstance; +import pl.gov.coi.cascades.server.domain.DatabaseOperationsGateway; +import pl.gov.coi.cascades.server.domain.DatabaseStatus; +import pl.gov.coi.cascades.server.domain.launchdatabase.UsernameAndPasswordCredentialsImpl; +import pl.gov.coi.cascades.server.persistance.stub.DatabaseTypeStub; +import pl.wavesoftware.eid.exceptions.EidIllegalArgumentException; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.verify; + +/** + * @author Łukasz Małek + */ +public class GeneralDatabaseOperationGatewayTest { + + private static final String TEMPLATE_GENERATED_ID = "4563462"; + private static final long TEMPLATE_ID = 123L; + private static final String SERVER_ID = "serverId"; + private static final String EXAMPLE_HOST = "example.host"; + private static final int PORT = 5342; + private static final String ID = "a123xqw2"; + private static final String PGSQL = "pgsql"; + private static final String ORACLE = "ora12c"; + private static final String TEMPLATE_NAME = "templateName"; + private DatabaseInstance databaseInstance; + private DatabaseOperationsGateway databaseOperations; + private Template template; + private ServerDef serverDef; + + @Mock + private ServerConfigurationService serverConfigurationService; + + @Mock + private ConnectionDatabase connectionDatabase; + + @Mock + private DatabaseManager databaseManager; + + @Mock + private JdbcTemplate jdbcTemplate; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Before + public void init() { + databaseOperations = new GeneralDatabaseOperationGateway( + serverConfigurationService, + databaseManager + ); + + template = Template.builder().id(TEMPLATE_ID).name(TEMPLATE_NAME).generatedId(TEMPLATE_GENERATED_ID).serverId(SERVER_ID).build(); + databaseInstance = createDatabaseInstance(template); + given(connectionDatabase.getJdbcTemplate()).willReturn(jdbcTemplate); + + serverDef = new ServerDef(); + serverDef.setHost(EXAMPLE_HOST); + serverDef.setPort(PORT); + serverDef.setType(PGSQL); + serverDef.setServerId(SERVER_ID); + } + + @Test + public void shouldCreateDatabaseFindNetworkBind() throws SQLException { + //given + List serverDefList = new ArrayList<>(); + serverDef.setType(ORACLE); + serverDefList.add(serverDef); + + given(serverConfigurationService.getManagedServers()).willReturn(serverDefList); + given(databaseManager.getConnectionToServer(anyString())).willReturn(connectionDatabase); + + //when + DatabaseInstance result = databaseOperations.createDatabase(databaseInstance); + + //then + assertNotNull(result); + assertNotNull(result.getNetworkBind()); + assertEquals("example.host", result.getNetworkBind().getHost()); + assertEquals(5342, result.getNetworkBind().getPort()); + } + + @Test + public void shouldCreateDatabaseFindDatabaseType() throws SQLException { + //given + List serverDefList = new ArrayList<>(); + serverDef.setType(ORACLE); + serverDefList.add(serverDef); + + given(serverConfigurationService.getManagedServers()).willReturn(serverDefList); + given(databaseManager.getConnectionToServer(anyString())).willReturn(connectionDatabase); + + + //when + DatabaseInstance result = databaseOperations.createDatabase(databaseInstance); + + //then + assertNotNull(result); + assertNotNull(result.getDatabaseType()); + assertEquals("ora12c", result.getDatabaseType().getName()); + } + + @Test(expected = EidIllegalArgumentException.class) + public void shouldCreateDatabaseNoFindDatabaseType() { + //given + serverDef.setType(null); + + List serverDefList = new ArrayList<>(); + serverDefList.add(serverDef); + + given(serverConfigurationService.getManagedServers()).willReturn(serverDefList); + + //when + databaseOperations.createDatabase(databaseInstance); + + //then + expectedException.expectMessage("20180706:151716"); + expectedException.expectMessage("Hasn't been found database type."); + } + + @Test(expected = EidIllegalArgumentException.class) + public void shouldCreateDatabaseNotFindTemplate() { + //when + databaseOperations.createDatabase(createDatabaseInstance(null)); + + //then + expectedException.expectMessage("20180706:151316"); + expectedException.expectMessage("Hasn't been found database type."); + } + + @Test(expected = EidIllegalArgumentException.class) + public void shouldCreateDatabaseNotFindHost() { + //given + serverDef.setHost(null); + + List serverDefList = new ArrayList<>(); + serverDefList.add(serverDef); + + given(serverConfigurationService.getManagedServers()).willReturn(serverDefList); + + //when + databaseOperations.createDatabase(databaseInstance); + + //then + expectedException.expectMessage("20180628:191916"); + expectedException.expectMessage("Hasn't been found connection settings."); + } + + @Test(expected = EidIllegalArgumentException.class) + public void shouldCreateDatabaseNoFindPort() { + //given + serverDef.setPort(0); + + List serverDefList = new ArrayList<>(); + serverDefList.add(serverDef); + + given(serverConfigurationService.getManagedServers()).willReturn(serverDefList); + + //when + databaseOperations.createDatabase(databaseInstance); + + //then + expectedException.expectMessage("20180628:191916"); + expectedException.expectMessage("Hasn't been found connection settings."); + } + + @Test(expected = UnsupportedOperationException.class) + public void shouldExecuteDeleteDatabase() { + //when + databaseOperations.deleteDatabase(databaseInstance); + } + + @Test + public void shouldCreateOracleDatabase() throws SQLException { + //given + List serverDefList = new ArrayList<>(); + serverDef.setType(ORACLE); + serverDefList.add(serverDef); + + given(serverConfigurationService.getManagedServers()).willReturn(serverDefList); + given(databaseManager.getConnectionToServer(anyString())).willReturn(connectionDatabase); + + //when + databaseOperations.createDatabase(databaseInstance); + + //then + verify(jdbcTemplate).execute("ALTER SESSION SET container = CDB$ROOT"); + verify(jdbcTemplate).execute("CREATE PLUGGABLE DATABASE exampleDatabaseName from templateName " + + "file_name_convert = ('/u01/app/oracle/oradata/orcl12c/templateName', '/u01/app/oracle/oradata/orcl12c/exampleDatabaseName')"); + verify(jdbcTemplate).execute("ALTER PLUGGABLE DATABASE exampleDatabaseName OPEN READ WRITE"); + } + + @Test + public void shouldCreatePostgresDatabase() throws SQLException { + //given + List serverDefList = new ArrayList<>(); + serverDef.setType(PGSQL); + serverDefList.add(serverDef); + + given(serverConfigurationService.getManagedServers()).willReturn(serverDefList); + given(databaseManager.getConnectionToServer(anyString())).willReturn(connectionDatabase); + + //when + databaseOperations.createDatabase(databaseInstance); + + //then + verify(jdbcTemplate).execute("CREATE DATABASE exampleDatabaseName TEMPLATE templateName"); + } + + + + private DatabaseInstance createDatabaseInstance(Template template) { + String databaseName = "exampleDatabaseName"; + String instanceName = "my_database"; + return DatabaseInstance.builder() + .databaseId(new DatabaseId(ID)) + .status(DatabaseStatus.LAUNCHED) + .created(new Date()) + .credentials(new UsernameAndPasswordCredentialsImpl(null, null)) + .databaseName(databaseName) + .databaseType(new DatabaseTypeStub()) + .instanceName(instanceName) + .networkBind(null) + .reuseTimes(1) + .template(template) + .build(); + } +} diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/GeneralTemplateGatewayTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/GeneralTemplateGatewayTest.java new file mode 100644 index 0000000..58a0d4c --- /dev/null +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/GeneralTemplateGatewayTest.java @@ -0,0 +1,188 @@ +package pl.gov.coi.cascades.server; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.springframework.jdbc.core.JdbcTemplate; +import pl.gov.coi.cascades.contract.domain.Template; +import pl.gov.coi.cascades.server.domain.DatabaseTemplateGateway; +import pl.wavesoftware.eid.exceptions.EidIllegalArgumentException; +import pl.wavesoftware.eid.exceptions.EidIllegalStateException; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.SQLException; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * @author Mariusz Wyszomierski + */ +public class GeneralTemplateGatewayTest { + + private static final String POSTGRESQL = "postgresql"; + private static final String SERVER_ID = "serverId"; + private static final String ORACLE = "oracle"; + private static final String DEPLOY_SCRIPT_CONTENT = "insert into some_table values ('test')"; + + + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Mock + private DatabaseManager databaseManager; + + @Mock + private ConnectionDatabase connectionDatabase; + + @Mock + private JdbcTemplate jdbcTemplate; + + private DatabaseTemplateGateway databaseTemplateGateway; + private Template template = Template.builder().serverId(SERVER_ID).name("templateName").build(); + private Path deployScript = Paths.get("src","test","resources", "deploy.sql"); + + @Before + public void setup() throws SQLException { + databaseTemplateGateway = new GeneralTemplateGateway(databaseManager); + when(databaseManager.getConnectionToServer(SERVER_ID)).thenReturn(connectionDatabase); + when(connectionDatabase.getJdbcTemplate()).thenReturn(jdbcTemplate); + when(databaseManager.getConnectionToDatabase(SERVER_ID, "templateName")).thenReturn(connectionDatabase); + } + + @Test + public void shouldRunCreateDatabaseCommandInPostgreSQL() { + //given + when(connectionDatabase.getType()).thenReturn(POSTGRESQL); + + //when + databaseTemplateGateway.createTemplate(template, deployScript); + + //then + verify(jdbcTemplate).execute("CREATE DATABASE templateName TEMPLATE template0"); + } + + @Test + public void shouldRunDeployScriptInPostgreSQL() { + //given + when(connectionDatabase.getType()).thenReturn(POSTGRESQL); + + //when + databaseTemplateGateway.createTemplate(template, deployScript); + + //then + verify(jdbcTemplate).execute(DEPLOY_SCRIPT_CONTENT); + } + + @Test + public void shouldChangeTemplateAttributesInPostgreSQL() { + //given + when(connectionDatabase.getType()).thenReturn(POSTGRESQL); + + //when + databaseTemplateGateway.createTemplate(template, deployScript); + + //then + verify(jdbcTemplate).execute("UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'templateName'"); + verify(jdbcTemplate).execute("UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'templateName'"); + } + + @Test + public void shouldRunCreateDatabaseCommandInOracle() { + //given + when(connectionDatabase.getType()).thenReturn(ORACLE); + + //when + databaseTemplateGateway.createTemplate(template, deployScript); + + //then + verify(jdbcTemplate).execute("ALTER SESSION SET container = CDB$ROOT"); + verify(jdbcTemplate).execute("CREATE PLUGGABLE DATABASE templateName ADMIN USER admin IDENTIFIED " + + "BY ksdn#2Hd file_name_convert = ('/u01/app/oracle/oradata/orcl12c/pdbseed'," + + " '/u01/app/oracle/oradata/orcl12c/templateName')"); + verify(jdbcTemplate).execute("ALTER PLUGGABLE DATABASE templateName OPEN READ WRITE"); + } + + @Test + public void shouldRunDeployScriptInOracle() { + //given + when(connectionDatabase.getType()).thenReturn(ORACLE); + + //when + databaseTemplateGateway.createTemplate(template, deployScript); + + //then + verify(jdbcTemplate).execute(DEPLOY_SCRIPT_CONTENT); + } + + @Test(expected = EidIllegalArgumentException.class) + public void shouldThrowIllegalArgumentExceptionCreateTemplate() throws SQLException { + //given + when(databaseManager.getConnectionToServer(SERVER_ID)).thenThrow(new SQLException()); + + //when + databaseTemplateGateway.createTemplate(template, deployScript); + + //then + expectedException.expectMessage("20170711:151221"); + } + + @Test + public void deleteTemplatePostgreSQL() { + //given + when(connectionDatabase.getType()).thenReturn(POSTGRESQL); + + //when + databaseTemplateGateway.deleteTemplate(template); + + //then + verify(jdbcTemplate).execute("DROP DATABASE templateName"); + } + + @Test + public void deleteTemplateOracle() { + //given + when(connectionDatabase.getType()).thenReturn(ORACLE); + + //when + databaseTemplateGateway.deleteTemplate(template); + + //then + verify(jdbcTemplate).execute("ALTER PLUGGABLE DATABASE templateName CLOSE IMMEDIATE"); + verify(jdbcTemplate).execute("DROP PLUGGABLE DATABASE templateName INCLUDING DATAFILES"); + } + + @Test(expected = EidIllegalArgumentException.class) + public void deleteTemplateShouldThrowIllegalArgumentException() throws SQLException { + //given + when(databaseManager.getConnectionToServer(SERVER_ID)).thenThrow(new SQLException()); + + //when + databaseTemplateGateway.deleteTemplate(template); + + //then + expectedException.expectMessage("20170726:135511"); + } + + @Test(expected = UnsupportedOperationException.class) + public void canBeRemoved() { + databaseTemplateGateway.canBeRemoved(template); + } + + @Test(expected = EidIllegalStateException.class) + public void shouldThrowExceptionWhenDeployScriptDoesntExistsCreateTemplate() { + //given + when(connectionDatabase.getType()).thenReturn(POSTGRESQL); + + //when + databaseTemplateGateway.createTemplate(template, Paths.get("incorrectPath")); + } +} diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/GeneralUserGatewayTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/GeneralUserGatewayTest.java new file mode 100644 index 0000000..5fccb14 --- /dev/null +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/GeneralUserGatewayTest.java @@ -0,0 +1,259 @@ +package pl.gov.coi.cascades.server; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; +import org.springframework.jdbc.core.JdbcTemplate; +import pl.gov.coi.cascades.contract.domain.Template; +import pl.gov.coi.cascades.contract.domain.UsernameAndPasswordCredentials; +import pl.gov.coi.cascades.server.domain.DatabaseInstance; +import pl.gov.coi.cascades.server.domain.DatabaseTypeImpl; +import pl.gov.coi.cascades.server.domain.DatabaseUserGateway; +import pl.gov.coi.cascades.server.domain.launchdatabase.UsernameAndPasswordCredentialsImpl; +import pl.wavesoftware.eid.exceptions.EidIllegalArgumentException; + +import java.sql.SQLException; + +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +/** + * @author Łukasz Małek + */ +public class GeneralUserGatewayTest { + + private static final String SERVER_ID = "serverId"; + private static final String ORACLE = "ora12c"; + private static final String EXAMPLE_USERNAME = "exampleUsername"; + private static final String EXAMPLE_PASS = "examplePassword"; + private static final String TEMPLATE_NAME = "templateName"; + private static final String PGSQL = "pgsql"; + private static final String DATABASE_NAME = "databaseName"; + private static final String STUB = "STUB"; + + @Mock + private DatabaseManager databaseManager; + + @Mock + private ConnectionDatabase connectionDatabase; + + @Mock + private JdbcTemplate jdbcTemplate; + + @Mock + private UsernameAndPasswordCredentials credentials2; + + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + private DatabaseUserGateway databaseUserGateway; + + @Before + public void init() throws SQLException { + databaseUserGateway = new GeneralUserGateway(databaseManager); + given(databaseManager.getConnectionToServer(SERVER_ID)).willReturn(connectionDatabase); + given(connectionDatabase.getJdbcTemplate()).willReturn(jdbcTemplate); + } + + @Test + public void shouldCreateUserPostgres() { + //given + char[] examplePass = EXAMPLE_PASS.toCharArray(); + given(credentials2.getPassword()).willReturn(examplePass); + given(credentials2.getUsername()).willReturn(EXAMPLE_USERNAME); + + Template template = createTemplate(); + DatabaseInstance databaseInstance = DatabaseInstance.builder() + .template(template) + .databaseType(new DatabaseTypeImpl(PGSQL)) + .credentials(credentials2) + .build(); + + //when + databaseUserGateway.createUser(databaseInstance); + + //then + verify(jdbcTemplate).execute("CREATE USER exampleUsername WITH ENCRYPTED PASSWORD '" + examplePass + "'"); + } + + @Test + public void shouldCreateUserOracle() throws SQLException { + //given + char[] examplePass = EXAMPLE_PASS.toCharArray(); + given(credentials2.getPassword()).willReturn(examplePass); + given(credentials2.getUsername()).willReturn(EXAMPLE_USERNAME); + + Template template = createTemplate(); + DatabaseInstance databaseInstance = DatabaseInstance.builder() + .template(template) + .databaseType(new DatabaseTypeImpl(ORACLE)) + .credentials(credentials2) + .build(); + + given(databaseManager.getConnectionToDatabase(SERVER_ID, databaseInstance.getDatabaseName())).willReturn(connectionDatabase); + + //when + databaseUserGateway.createUser(databaseInstance); + + //then + verify(jdbcTemplate).execute("CREATE USER exampleUsername IDENTIFIED BY \"" + examplePass + "\""); + } + + @Test + public void shouldCreateAddPermissionsPostgres() { + //given + UsernameAndPasswordCredentials credentials = createUsernameAndPasswordCredentials(); + Template template = createTemplate(); + + DatabaseInstance databaseInstance = DatabaseInstance.builder() + .template(template) + .credentials(credentials) + .databaseName(DATABASE_NAME) + .databaseType(new DatabaseTypeImpl(PGSQL)) + .build(); + + //when + databaseUserGateway.createUser(databaseInstance); + + //then + verify(jdbcTemplate).execute("GRANT ALL PRIVILEGES ON DATABASE databaseName TO exampleUsername"); + } + + @Test + public void shouldCreateAddPermissionsOracle() throws SQLException { + //given + UsernameAndPasswordCredentials credentials = createUsernameAndPasswordCredentials(); + Template template = createTemplate(); + + DatabaseInstance databaseInstance = DatabaseInstance.builder() + .template(template) + .credentials(credentials) + .databaseName(DATABASE_NAME) + .databaseType(new DatabaseTypeImpl(ORACLE)) + .build(); + + given(databaseManager.getConnectionToDatabase(SERVER_ID, databaseInstance.getDatabaseName())).willReturn(connectionDatabase); + + //when + databaseUserGateway.createUser(databaseInstance); + + //then + verify(jdbcTemplate).execute("GRANT DBA TO exampleUsername"); + } + + @Test + public void shouldDeleteUserPostgres() { + //given + UsernameAndPasswordCredentials credentials = createUsernameAndPasswordCredentials(); + Template template = createTemplate(); + + DatabaseInstance databaseInstance = DatabaseInstance.builder() + .template(template) + .databaseName(DATABASE_NAME) + .databaseType(new DatabaseTypeImpl(PGSQL)) + .credentials(credentials) + .build(); + + //when + databaseUserGateway.deleteUser(databaseInstance); + + //then + verify(jdbcTemplate).execute("REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM exampleUsername"); + verify(jdbcTemplate).execute("REVOKE ALL ON DATABASE databaseName FROM exampleUsername"); + verify(jdbcTemplate).execute("DROP USER exampleUsername"); + } + + @Test + public void shouldDeleteUserOracle() throws SQLException { + //given + UsernameAndPasswordCredentials credentials = createUsernameAndPasswordCredentials(); + Template template = createTemplate(); + + DatabaseInstance databaseInstance = DatabaseInstance.builder() + .template(template) + .databaseName(DATABASE_NAME) + .databaseType(new DatabaseTypeImpl(ORACLE)) + .credentials(credentials) + .build(); + + given(databaseManager.getConnectionToDatabase(SERVER_ID, databaseInstance.getDatabaseName())).willReturn(connectionDatabase); + + //when + databaseUserGateway.deleteUser(databaseInstance); + + //then + verify(jdbcTemplate).execute("DROP USER exampleUsername"); + } + + @Test(expected = EidIllegalArgumentException.class) + public void shouldDeleteUserOracleThrowIllegalArgumentException() throws SQLException { + //given + Template template = createTemplate(); + DatabaseInstance databaseInstance = DatabaseInstance.builder() + .template(template) + .databaseName(DATABASE_NAME) + .databaseType(new DatabaseTypeImpl(ORACLE)) + .build(); + + given(databaseManager.getConnectionToDatabase(SERVER_ID, databaseInstance.getDatabaseName())).willThrow(new SQLException()); + + //when + databaseUserGateway.deleteUser(databaseInstance); + + //then + expectedException.expectMessage("20180711:095808"); + } + + @Test(expected = EidIllegalArgumentException.class) + public void shouldDeleteUserPostgresThrowIllegalArgumentException() throws SQLException { + //given + Template template = createTemplate(); + DatabaseInstance databaseInstance = DatabaseInstance.builder() + .template(template) + .databaseType(new DatabaseTypeImpl(PGSQL)) + .build(); + + given(databaseManager.getConnectionToServer(SERVER_ID)).willThrow(new SQLException()); + + //when + databaseUserGateway.deleteUser(databaseInstance); + + //then + expectedException.expectMessage("20180704:102108"); + } + + @Test(expected = EidIllegalArgumentException.class) + public void shouldThrowIllegalArgumentExceptionWhenCreateUser() throws SQLException { + //given + DatabaseInstance databaseInstance = DatabaseInstance.builder() + .databaseType(new DatabaseTypeImpl(STUB)) + .build(); + + //when + databaseUserGateway.createUser(databaseInstance); + + //then + expectedException.expectMessage("20180711:110816"); + } + + private UsernameAndPasswordCredentials createUsernameAndPasswordCredentials() { + return new UsernameAndPasswordCredentialsImpl( + EXAMPLE_USERNAME, + EXAMPLE_PASS.toCharArray() + ); + } + + private Template createTemplate() { + return Template.builder() + .serverId(SERVER_ID) + .name(TEMPLATE_NAME) + .build(); + } +} diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/NetworkBindImplTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/NetworkBindImplTest.java new file mode 100644 index 0000000..9d1d99a --- /dev/null +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/NetworkBindImplTest.java @@ -0,0 +1,79 @@ +package pl.gov.coi.cascades.server; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Łukasz Małek + */ +public class NetworkBindImplTest { + + private static final int PORT = 8080; + private static final String HOST = "localhost"; + + private NetworkBindImpl networkBind; + + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Before + public void setUp() { + networkBind = new NetworkBindImpl( + HOST, + PORT + ); + } + + @Test + public void shouldGetHost() { + // when + String actual = networkBind.getHost(); + + // then + assertThat(actual).isNotNull(); + assertThat(actual).isEqualTo("localhost"); + } + + @Test + public void shouldSetHost() { + // given + String host = "db.internal"; + + // when + networkBind.setHost(host); + String actual = networkBind.getHost(); + + // then + assertThat(actual).isNotNull(); + assertThat(actual).isEqualTo("db.internal"); + } + + @Test + public void shouldGetPort() { + // when + int actual = networkBind.getPort(); + + // then + assertThat(actual).isNotNull(); + assertThat(actual).isEqualTo(8080); + } + + @Test + public void shouldSetPort() { + // given + int port = 1234; + + // when + networkBind.setPort(port); + int actual = networkBind.getPort(); + + // then + assertThat(actual).isNotNull(); + assertThat(actual).isEqualTo(1234); + } +} diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ServerDefTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ServerDefTest.java index 5a134ef..04fad43 100644 --- a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ServerDefTest.java +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/ServerDefTest.java @@ -13,21 +13,25 @@ public class ServerDefTest { @Test public void testConstructorWithParameters() { // when - ServerDef serverDef = new ServerDef( - "test", - "ora12c", - "db_name", - "admin", - "pass123", - "172.0.0.1", - 1234 - ); + ServerDef serverDef = createFullServerDef(); // then assertThat(serverDef).isNotNull(); } + private ServerDef createFullServerDef() { + return new ServerDef( + "test", + "ora12c", + "db_name", + "admin", + "pass123", + "172.0.0.1", + 1234 + ); + } + @Test - public void testEquals() throws Exception { + public void testEquals() { // given ServerDef serverDef = new ServerDef(); ServerDef otherServerDef = new ServerDef(); @@ -41,7 +45,7 @@ public void testEquals() throws Exception { } @Test - public void testHashCode() throws Exception { + public void testHashCode() { // given ServerDef serverDef = new ServerDef(); ServerDef otherServerDef = new ServerDef(); @@ -55,7 +59,7 @@ public void testHashCode() throws Exception { } @Test - public void testCanEqual() throws Exception { + public void testCanEqual() { // given ServerDef serverDef = new ServerDef(); ServerDef otherServerDef = new ServerDef(); @@ -68,7 +72,7 @@ public void testCanEqual() throws Exception { } @Test - public void testToString() throws Exception { + public void testToString() { // given ServerDef serverDef = new ServerDef(); serverDef.setServerId("test"); @@ -92,7 +96,7 @@ public void testToString() throws Exception { } @Test - public void testSetServerId() throws Exception { + public void testSetServerId() { // given ServerDef serverDef = new ServerDef(); @@ -104,7 +108,7 @@ public void testSetServerId() throws Exception { } @Test - public void testSetDbname() throws Exception { + public void testSetDbname() { // given ServerDef serverDef = new ServerDef(); @@ -116,7 +120,7 @@ public void testSetDbname() throws Exception { } @Test - public void testSetUser() throws Exception { + public void testSetUser() { // given ServerDef serverDef = new ServerDef(); @@ -128,7 +132,7 @@ public void testSetUser() throws Exception { } @Test - public void testSetPassword() throws Exception { + public void testSetPassword() { // given ServerDef serverDef = new ServerDef(); @@ -140,7 +144,7 @@ public void testSetPassword() throws Exception { } @Test - public void testSetHost() throws Exception { + public void testSetHost() { // given ServerDef serverDef = new ServerDef(); @@ -152,7 +156,7 @@ public void testSetHost() throws Exception { } @Test - public void testSetPort() throws Exception { + public void testSetPort() { // given ServerDef serverDef = new ServerDef(); @@ -164,7 +168,7 @@ public void testSetPort() throws Exception { } @Test - public void testGetServerId() throws Exception { + public void testGetServerId() { // given ServerDef serverDef = new ServerDef(); @@ -176,7 +180,7 @@ public void testGetServerId() throws Exception { } @Test - public void testGetDbname() throws Exception { + public void testGetDbname() { // given ServerDef serverDef = new ServerDef(); serverDef.setDbname("db_name"); @@ -189,7 +193,7 @@ public void testGetDbname() throws Exception { } @Test - public void testGetUser() throws Exception { + public void testGetUser() { // given ServerDef serverDef = new ServerDef(); serverDef.setUser("admin"); @@ -202,7 +206,7 @@ public void testGetUser() throws Exception { } @Test - public void testGetPassword() throws Exception { + public void testGetPassword() { // given ServerDef serverDef = new ServerDef(); serverDef.setPassword("pass123"); @@ -215,7 +219,7 @@ public void testGetPassword() throws Exception { } @Test - public void testGetHost() throws Exception { + public void testGetHost() { // given ServerDef serverDef = new ServerDef(); serverDef.setHost("172.0.0.1"); @@ -228,7 +232,7 @@ public void testGetHost() throws Exception { } @Test - public void testGetPort() throws Exception { + public void testGetPort() { // given ServerDef serverDef = new ServerDef(); serverDef.setPort(1234); @@ -240,4 +244,16 @@ public void testGetPort() throws Exception { assertThat(actual).isEqualTo(1234); } + @Test + public void testGetWithNewDatabaseName() { + //given + ServerDef fullServerDef = createFullServerDef(); + + //when + ServerDef result = fullServerDef.getWithNewDatabaseName("NEW DATABASE NAME"); + + //then + assertThat(result.toString()).isEqualTo("ServerDef(serverId=test, type=ora12c, dbname=NEW DATABASE NAME, user=admin, password=pass123, host=172.0.0.1, port=1234)"); + } + } diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/domain/DomainConfigurationTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/domain/DomainConfigurationTest.java index cd72d3c..a6df146 100644 --- a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/domain/DomainConfigurationTest.java +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/domain/DomainConfigurationTest.java @@ -39,6 +39,9 @@ public class DomainConfigurationTest { @Mock private TemplateIdGateway templateIdGateway; + @Mock + private DatabaseUserGateway databaseUserGateway; + @Mock private DatabaseTemplateGateway databaseTemplateGateway; @@ -57,6 +60,9 @@ public class DomainConfigurationTest { @Mock private TemplateIdGeneratorService templateIdGeneratorService; + @Mock + private DatabaseOperationsGateway databaseOperationsGateway; + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @@ -104,7 +110,9 @@ public void testProduceGateways() throws Exception { templateIdGateway, userGateway, databaseLimitGateway, - databaseInstanceGateway + databaseInstanceGateway, + databaseOperationsGateway, + databaseUserGateway ); // then diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/persistance/hibernate/HibernateConfigurationTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/persistance/hibernate/HibernateConfigurationTest.java index e5287f9..28d5cc7 100644 --- a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/persistance/hibernate/HibernateConfigurationTest.java +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/persistance/hibernate/HibernateConfigurationTest.java @@ -5,9 +5,12 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; +import pl.gov.coi.cascades.server.DatabaseManager; +import pl.gov.coi.cascades.server.ServerConfigurationService; import pl.gov.coi.cascades.server.domain.DatabaseIdGateway; import pl.gov.coi.cascades.server.domain.DatabaseInstanceGateway; import pl.gov.coi.cascades.server.domain.DatabaseLimitGateway; +import pl.gov.coi.cascades.server.domain.DatabaseOperationsGateway; import pl.gov.coi.cascades.server.domain.DatabaseTypeClassNameService; import pl.gov.coi.cascades.server.domain.TemplateIdGateway; import pl.gov.coi.cascades.server.domain.UserGateway; @@ -31,6 +34,12 @@ public class HibernateConfigurationTest { @Mock private DatabaseTypeClassNameService databaseTypeClassNameService; + @Mock + private ServerConfigurationService serverConfigurationService; + + @Mock + private DatabaseManager databaseManager; + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @@ -70,7 +79,9 @@ public void testCreateDatabaseIdGateway() throws Exception { @Test public void testDatabaseInstanceGateway() throws Exception { // when - DatabaseInstanceGateway actual = hibernateConfiguration.createDatabaseInstanceGateway(); + DatabaseInstanceGateway actual = hibernateConfiguration.createDatabaseInstanceGateway( + databaseInstanceMapper + ); // then assertThat(actual).isNotNull(); diff --git a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/persistance/stub/PersistanceStubByDefaultOnDevelopmentAutoConfigurationTest.java b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/persistance/stub/PersistanceStubByDefaultOnDevelopmentAutoConfigurationTest.java index 7e3f752..61d0264 100644 --- a/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/persistance/stub/PersistanceStubByDefaultOnDevelopmentAutoConfigurationTest.java +++ b/cascades-server/configuration/src/test/java/pl/gov/coi/cascades/server/persistance/stub/PersistanceStubByDefaultOnDevelopmentAutoConfigurationTest.java @@ -1,11 +1,15 @@ package pl.gov.coi.cascades.server.persistance.stub; import org.junit.Test; +import org.mockito.Mock; import pl.gov.coi.cascades.contract.domain.DatabaseType; +import pl.gov.coi.cascades.contract.domain.NetworkBind; import pl.gov.coi.cascades.server.domain.DatabaseIdGateway; -import pl.gov.coi.cascades.server.domain.DatabaseInstanceGateway; +import pl.gov.coi.cascades.server.domain.DatabaseInstance; import pl.gov.coi.cascades.server.domain.DatabaseLimitGateway; +import pl.gov.coi.cascades.server.domain.DatabaseOperationsGateway; import pl.gov.coi.cascades.server.domain.DatabaseTemplateGateway; +import pl.gov.coi.cascades.server.domain.DatabaseUserGateway; import pl.gov.coi.cascades.server.domain.TemplateIdGateway; import pl.gov.coi.cascades.server.domain.User; import pl.gov.coi.cascades.server.domain.UserGateway; @@ -54,7 +58,6 @@ public void testProduceTemplateIdGateway() throws Exception { // then assertThat(actual).isNotNull(); - assertThat(actual).isInstanceOf(TemplateIdGatewayStub.class); } @Test @@ -63,11 +66,10 @@ public void testProduceDatabaseInstanceGateway() throws Exception { PersistanceStubByDefaultOnDevelopmentAutoConfiguration stubs = new PersistanceStubByDefaultOnDevelopmentAutoConfiguration(); // when - DatabaseInstanceGateway actual = stubs.produceDatabaseInstanceGateway(); + DatabaseOperationsGateway actual = stubs.produceDatabaseOperations(); // then assertThat(actual).isNotNull(); - assertThat(actual).isInstanceOf(DatabaseInstanceGatewayStub.class); } @Test @@ -82,7 +84,6 @@ public void testProduceUserGateway() throws Exception { // then assertThat(actual).isNotNull(); - assertThat(actual).isInstanceOf(UserGatewayStub.class); } @Test @@ -95,7 +96,6 @@ public void testProduceDatabaseLimitGateway() throws Exception { // then assertThat(actual).isNotNull(); - assertThat(actual).isInstanceOf(DatabaseLimitGatewayStub.class); } @Test @@ -108,7 +108,6 @@ public void testProduceDatabaseIdGateway() throws Exception { // then assertThat(actual).isNotNull(); - assertThat(actual).isInstanceOf(DatabaseIdGatewayStub.class); } @Test @@ -121,7 +120,29 @@ public void testProduceDatabaseType() throws Exception { // then assertThat(actual).isNotNull(); - assertThat(actual).isInstanceOf(DatabaseTypeStub.class); } + @Test + public void testProduceDatabaseOperations() throws Exception { + // given + PersistanceStubByDefaultOnDevelopmentAutoConfiguration stubs = new PersistanceStubByDefaultOnDevelopmentAutoConfiguration(); + + // when + DatabaseOperationsGateway actual = stubs.produceDatabaseOperations(); + + // then + assertThat(actual).isNotNull(); + } + + @Test + public void testProduceDatabaseUserGateway() throws Exception { + // given + PersistanceStubByDefaultOnDevelopmentAutoConfiguration stubs = new PersistanceStubByDefaultOnDevelopmentAutoConfiguration(); + + // when + DatabaseUserGateway actual = stubs.produceDatabaseUserGateway(); + + // then + assertThat(actual).isNotNull(); + } } diff --git a/cascades-server/configuration/src/test/resources/deploy.sql b/cascades-server/configuration/src/test/resources/deploy.sql new file mode 100644 index 0000000..6767bba --- /dev/null +++ b/cascades-server/configuration/src/test/resources/deploy.sql @@ -0,0 +1 @@ +insert into some_table values ('test'); diff --git a/cascades-server/domain/contract/src/main/java/pl/gov/coi/cascades/server/domain/launchdatabase/Request.java b/cascades-server/domain/contract/src/main/java/pl/gov/coi/cascades/server/domain/launchdatabase/Request.java index 75ad605..65c12c7 100644 --- a/cascades-server/domain/contract/src/main/java/pl/gov/coi/cascades/server/domain/launchdatabase/Request.java +++ b/cascades-server/domain/contract/src/main/java/pl/gov/coi/cascades/server/domain/launchdatabase/Request.java @@ -15,8 +15,6 @@ @Builder public class Request { - @Getter - private final String type; @Getter private final User user; @Nullable @@ -27,16 +25,13 @@ public class Request { /** * Default argument constructor. * - * @param type Name of type class. * @param user User of the database. * @param template Given id of template (Optional). * @param instanceName Given name of database instance (Optional). */ - public Request(String type, - User user, + public Request(User user, @Nullable Template template, @Nullable String instanceName) { - this.type = EidPreconditions.checkNotNull(type, "20170228:153927"); this.user = EidPreconditions.checkNotNull(user, "20170228:153954"); this.template = template; this.instanceName = instanceName; @@ -49,7 +44,7 @@ public Request(String type, */ public Optional getTemplateId() { String idAsString = Optional.ofNullable(template) - .map(Template::getId) + .map(Template::getGeneratedId) .orElse(null); return Optional.ofNullable(idAsString); } diff --git a/cascades-server/domain/contract/src/test/java/pl/gov/coi/cascades/server/domain/launchdatabase/RequestTest.java b/cascades-server/domain/contract/src/test/java/pl/gov/coi/cascades/server/domain/launchdatabase/RequestTest.java index b12583d..4200385 100644 --- a/cascades-server/domain/contract/src/test/java/pl/gov/coi/cascades/server/domain/launchdatabase/RequestTest.java +++ b/cascades-server/domain/contract/src/test/java/pl/gov/coi/cascades/server/domain/launchdatabase/RequestTest.java @@ -21,9 +21,9 @@ */ public class RequestTest { - private final static String typeClassName = "Type"; private final static String instanceName = "PESEL"; - private final static String ID = "453v4c4c"; + private final static long ID = 12L; + private final static String GENERATED_ID = "453v4c4c"; private final static String NAME = "dg5nj69s"; private final static TemplateIdStatus TEMPLATE_ID_STATUS = TemplateIdStatus.CREATED; private final static boolean IS_DEFAULT = true; @@ -45,6 +45,7 @@ public class RequestTest { public void setUp() { template = new Template( ID, + GENERATED_ID, NAME, TEMPLATE_ID_STATUS, IS_DEFAULT, @@ -52,7 +53,6 @@ public void setUp() { VERSION ); request = new Request( - typeClassName, user, template, instanceName @@ -63,7 +63,6 @@ public void setUp() { public void testDefaultConstructor() throws Exception { // when Request actual = new Request( - typeClassName, user, template, instanceName @@ -79,7 +78,7 @@ public void testGetTemplateId() throws Exception { Optional actual = request.getTemplateId(); // then - assertThat(actual).isEqualTo(Optional.of(ID)); + assertThat(actual).isEqualTo(Optional.of(GENERATED_ID)); } @Test @@ -97,7 +96,6 @@ public void testBuilder() { Request requestBuilder = Request.builder() .instanceName(instanceName) .user(user) - .type(typeClassName) .template(template) .build(); @@ -113,14 +111,4 @@ public void testGetUser() throws Exception { // then assertThat(actual).isNotNull(); } - - @Test - public void testGetType() { - // when - String actual = request.getType(); - - // then - assertThat(actual).isNotNull(); - } - } diff --git a/cascades-server/domain/logic/pom.xml b/cascades-server/domain/logic/pom.xml index d320a4e..54386fa 100644 --- a/cascades-server/domain/logic/pom.xml +++ b/cascades-server/domain/logic/pom.xml @@ -75,6 +75,11 @@ org.json json + + org.apache.commons + commons-lang3 + 3.1 + diff --git a/cascades-server/domain/logic/src/main/java/pl/gov/coi/cascades/server/domain/DatabaseTypeImpl.java b/cascades-server/domain/logic/src/main/java/pl/gov/coi/cascades/server/domain/DatabaseTypeImpl.java new file mode 100644 index 0000000..6631b9e --- /dev/null +++ b/cascades-server/domain/logic/src/main/java/pl/gov/coi/cascades/server/domain/DatabaseTypeImpl.java @@ -0,0 +1,60 @@ +package pl.gov.coi.cascades.server.domain; + +import lombok.AllArgsConstructor; +import pl.gov.coi.cascades.contract.domain.ConnectionStringProducer; +import pl.gov.coi.cascades.contract.domain.DatabaseType; +import pl.gov.coi.cascades.contract.domain.NetworkBind; +import pl.wavesoftware.eid.exceptions.EidIllegalArgumentException; +import pl.wavesoftware.eid.exceptions.EidIllegalStateException; + +@AllArgsConstructor +public class DatabaseTypeImpl implements DatabaseType { + + private static final String ORACLE_DATABASE = "jdbc:oracle:thin:@//%s:%d/%s"; + private static final String POSTGRES_DATABASE = "jdbc:postgresql://%s:%d/%s"; + private static final String PGPSQL = "pgpsql"; + private static final String ORA12C = "ora12c"; + + private String name; + + @Override + public String getName() { + return name; + } + + @Override + public ConnectionStringProducer getConnectionStringProducer() { + if (name.equalsIgnoreCase(PGPSQL)) { + createProduce(POSTGRES_DATABASE); + + } else if (name.equalsIgnoreCase(ORA12C)) { + createProduce(ORACLE_DATABASE); + } + + throw new EidIllegalArgumentException( + "20180706:154716", + String.format("Given database type '%s' hasn't been recognised.", name) + ); + } + + private ConnectionStringProducer createProduce(String databaseType) { + new ConnectionStringProducer() { + @Override + public String produce(NetworkBind bind, String databaseName) { + return String.format( + databaseType, + bind.getHost(), + bind.getPort(), + databaseName + ); + } + }; + + throw new EidIllegalStateException( + "20180706:154616", + "Can't create connection string producer" + ); + } +} + + diff --git a/cascades-server/domain/logic/src/main/java/pl/gov/coi/cascades/server/domain/launchdatabase/LaunchNewDatabaseGatewayFacade.java b/cascades-server/domain/logic/src/main/java/pl/gov/coi/cascades/server/domain/launchdatabase/LaunchNewDatabaseGatewayFacade.java index a89f7c3..49db564 100644 --- a/cascades-server/domain/logic/src/main/java/pl/gov/coi/cascades/server/domain/launchdatabase/LaunchNewDatabaseGatewayFacade.java +++ b/cascades-server/domain/logic/src/main/java/pl/gov/coi/cascades/server/domain/launchdatabase/LaunchNewDatabaseGatewayFacade.java @@ -1,45 +1,31 @@ package pl.gov.coi.cascades.server.domain.launchdatabase; +import lombok.AllArgsConstructor; import pl.gov.coi.cascades.contract.domain.Template; import pl.gov.coi.cascades.server.domain.DatabaseInstance; import pl.gov.coi.cascades.server.domain.DatabaseInstanceGateway; import pl.gov.coi.cascades.server.domain.DatabaseLimitGateway; +import pl.gov.coi.cascades.server.domain.DatabaseOperationsGateway; +import pl.gov.coi.cascades.server.domain.DatabaseUserGateway; import pl.gov.coi.cascades.server.domain.TemplateIdGateway; import pl.gov.coi.cascades.server.domain.User; import pl.gov.coi.cascades.server.domain.UserGateway; -import javax.inject.Inject; import java.util.Optional; /** * @author Agnieszka Celuch * @since 05.04.17. */ +@AllArgsConstructor public class LaunchNewDatabaseGatewayFacade { private TemplateIdGateway templateIdGateway; private UserGateway userGateway; private DatabaseLimitGateway databaseLimitGateway; private DatabaseInstanceGateway databaseInstanceGateway; - - /** - * Default parameter constructor. - * - * @param templateIdGateway Given gateway of templateId. - * @param userGateway Given gateway of user. - * @param databaseLimitGateway Given gateway of database limit. - * @param databaseInstanceGateway Given gateway of database instance. - */ - @Inject - public LaunchNewDatabaseGatewayFacade(TemplateIdGateway templateIdGateway, - UserGateway userGateway, - DatabaseLimitGateway databaseLimitGateway, - DatabaseInstanceGateway databaseInstanceGateway) { - this.templateIdGateway = templateIdGateway; - this.userGateway = userGateway; - this.databaseLimitGateway = databaseLimitGateway; - this.databaseInstanceGateway = databaseInstanceGateway; - } + private DatabaseOperationsGateway databaseOperationsGateway; + private DatabaseUserGateway databaseUserGateway; Optional