Added database initialization logic

This commit is contained in:
Rohan Sircar 2019-10-04 15:40:26 +05:30
parent 3ea46b584a
commit bb9a4c9b3a
16 changed files with 694 additions and 269 deletions

0
chatto/.attach_pid5778 Normal file
View File

View File

@ -0,0 +1,7 @@
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/chatto_db2?useSSL=false
spring.datasource.username = chatto_user
spring.datasource.password = password
database-name = chatto_db2
website-url = 192.168.1.13

View File

@ -1,13 +1,29 @@
package org.ros.chatto;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.modelmapper.ModelMapper;
import org.ros.chatto.security.AuthenticationSuccessHandlerImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
@PropertySource(value = "classpath:queries.properties")
@Configuration
public class BeanConfigurations {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
@ -20,4 +36,10 @@ public class BeanConfigurations {
return modelMapper;
}
// @Bean
// public Connection connection() throws SQLException
// {
// return DriverManager.getConnection(url, userName, password);
// }
}

View File

@ -10,8 +10,14 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer
@SpringBootApplication
public class ChattoApplication extends SpringBootServletInitializer {
// @Value("${spring.datasource.url}")
// private static String url;
public static void main(String[] args) {
SpringApplication.run(ChattoApplication.class, args);
SpringApplication application = new SpringApplication(ChattoApplication.class);
addInitHooks(application);
// SpringApplication.run(ChattoApplication.class, args);
application.run(args);
}
@ -19,6 +25,13 @@ public class ChattoApplication extends SpringBootServletInitializer {
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ChattoApplication.class);
}
static void addInitHooks(SpringApplication application) {
// TBD
// System.out.println("Hello world very loooooooooooooooooooooooooooooooooooooong string");
// String url = environment.getProperty("spring.datasource.url");
// System.out.println("URL = " + url);
}
}
//public class Application extends SpringBootServletInitializer {

View File

@ -1,8 +1,10 @@
package org.ros.chatto.controller;
import java.security.Principal;
import java.sql.SQLException;
import org.ros.chatto.dto.ChatMessageDTO;
import org.ros.chatto.service.DBInitializerService;
import org.ros.chatto.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
@ -12,7 +14,6 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/*
@Controller
@RequestMapping(value = "/test")
@ -32,13 +33,24 @@ public class TestController {
public class Home {
@Autowired
UserService userService;
private UserService userService;
@Autowired
private DBInitializerService dbInitializerService;
private boolean installationChecked = false;
@RequestMapping("/")
public ModelAndView showPage(Principal principal) {
public ModelAndView showPage(Principal principal) throws SQLException {
ModelAndView mv = new ModelAndView("home");
mv.addObject("message", "Welcome!");
// mv.addObject("userNames", userService.findAllOtherUsers(principal.getName()));
if (!installationChecked) {
dbInitializerService.connectDB();
if(dbInitializerService.getNumTables() == 0)
dbInitializerService.populateDB();
dbInitializerService.closeConnection();
installationChecked = true;
}
return mv;
}

View File

@ -20,6 +20,6 @@ public interface ChatMessageRepository extends JpaRepository<ChatMessage, Long>
@Query("select m from ChatMessage m where (m.toUser.userName = ?1 or m.toUser.userName = ?2) and "
+ "(m.fromUser.userName = ?1 or m.fromUser.userName = ?2) and"
+ "(m.messageTime >= ?3) order by m.messageTime asc")
+ "(m.messageTime > ?3) order by m.messageTime asc")
public List<ChatMessage> getNewMessages(String fromUser, String toUser, Date lastMessageTime);
}

View File

@ -0,0 +1,9 @@
//package org.ros.chatto.repository;
//
//import org.springframework.data.jpa.repository.JpaRepository;
//import org.springframework.stereotype.Repository;
//
//@Repository
//public interface DBInitializerRepostory extends JpaRepository<Integer, Integer>{
//
//}

View File

@ -1,187 +0,0 @@
-- Database: `chatto_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `admins`
--
CREATE TABLE `admins` (
`admin_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `admins`
--
-- --------------------------------------------------------
--
-- Table structure for table `chatmessage`
--
CREATE TABLE `chatmessage` (
`Id` int(10) UNSIGNED NOT NULL,
`Message` varchar(4000) NOT NULL,
`userName` varchar(100) NOT NULL,
`MsgTime` varchar(45) NOT NULL,
`colorSelected` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `chatmessage`
--
-- --------------------------------------------------------
--
-- Table structure for table `chat_messages`
--
CREATE TABLE `chat_messages` (
`m_id` bigint(20) NOT NULL,
`from_user` int(11) NOT NULL,
`to_user` int(11) NOT NULL,
`message` int(10) NOT NULL,
`message_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `chat_messages`
--
-- --------------------------------------------------------
--
-- Table structure for table `total_messages`
--
CREATE TABLE `total_messages` (
`t_id` int(101) NOT NULL,
`from_user` int(11) NOT NULL,
`to_user` int(11) NOT NULL,
`total_messages` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`name` varchar(10) NOT NULL,
`password` varchar(80) NOT NULL,
`join_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `users`
--
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admins`
--
ALTER TABLE `admins`
ADD PRIMARY KEY (`admin_id`),
ADD UNIQUE KEY `user_id_2` (`user_id`),
ADD KEY `admin_id` (`admin_id`),
ADD KEY `user_id` (`user_id`);
--
-- Indexes for table `chatmessage`
--
ALTER TABLE `chatmessage`
ADD PRIMARY KEY (`Id`);
--
-- Indexes for table `chat_messages`
--
ALTER TABLE `chat_messages`
ADD PRIMARY KEY (`m_id`),
ADD UNIQUE KEY `identifier_message_number` (`m_id`),
ADD KEY `identifier_message_number_2` (`m_id`),
ADD KEY `from_user` (`from_user`,`to_user`),
ADD KEY `message` (`message`),
ADD KEY `FOREIGN KEY TO USER IN MESSAGES TABLE` (`to_user`);
--
-- Indexes for table `total_messages`
--
ALTER TABLE `total_messages`
ADD PRIMARY KEY (`t_id`),
ADD UNIQUE KEY `identifier` (`t_id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`),
ADD UNIQUE KEY `name` (`name`),
ADD KEY `user_id` (`user_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `admins`
--
ALTER TABLE `admins`
MODIFY `admin_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `chatmessage`
--
ALTER TABLE `chatmessage`
MODIFY `Id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=402;
--
-- AUTO_INCREMENT for table `chat_messages`
--
ALTER TABLE `chat_messages`
MODIFY `m_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30;
--
-- AUTO_INCREMENT for table `total_messages`
--
ALTER TABLE `total_messages`
MODIFY `t_id` int(101) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `admins`
--
ALTER TABLE `admins`
ADD CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE;
--
-- Constraints for table `chat_messages`
--
ALTER TABLE `chat_messages`
ADD CONSTRAINT `FOREIGN KEY ENC MESSAGE TABLE` FOREIGN KEY (`message`) REFERENCES `message_ciphers` (`id`) ON UPDATE CASCADE,
ADD CONSTRAINT `FOREIGN KEY FROM USER IN MESSAGES TABLE` FOREIGN KEY (`from_user`) REFERENCES `users` (`user_id`) ON UPDATE CASCADE,
ADD CONSTRAINT `FOREIGN KEY TO USER IN MESSAGES TABLE` FOREIGN KEY (`to_user`) REFERENCES `users` (`user_id`) ON UPDATE CASCADE;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

View File

@ -0,0 +1,146 @@
package org.ros.chatto.service;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Service;
@Service
//@PropertySource(name = "myProperties", value = "example.properties")
//@PropertySource(name = "appProperties", value="classpath:myapp.properties")
@PropertySource(value = "classpath:queries.properties")
public class DBInitializerService {
// @Autowired
// private Environment environment;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
@Value("${database-name}")
private String dbName;
@Value("${num-tables}")
private String numTablesQuery;
private Connection connection;
// public DBInitializerService(Connection connection) {
// this.connection = connection;
// // TODO Auto-generated constructor stub
// }
// Run this method when application started
// @EventListener(ApplicationReadyEvent.class)
// public ResultSet getConnection()
// {
//// String url = environment.getProperty("spring.datasource.url");
// System.out.println("URL = " + url);
////
//// //Connect to Database
//// Connection connection = null;
//// String QUERY="your sql query";
//// try {
//// DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//// connection = DriverManager.getConnection(url, userName, password );
//// } catch (SQLException e) {
//// }
////
////
//// //Run your query
//// Statement stmt = null;
//// try {
//// stmt = connection.createStatement();
//// } catch (SQLException e1) {
//// e1.printStackTrace();
//// }
//// ResultSet rs = null;
//// try {
//// rs = stmt.executeQuery(QUERY);
//// } catch (SQLException e1) {
//// e1.printStackTrace();
//// }
////
//// return rs;
// return null;
// }
// @BeforeClass
// public static void initializeJiraDataBaseForSla() throws SQLException {
// final DataSource datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null);
// final Connection connection = datasource.getConnection();
// try {
// ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/sla/jira-create.sql"), StandardCharsets.UTF_8));
// ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/sla/jira.sql"), StandardCharsets.UTF_8));
// } finally {
// connection.close();
// }
// }
public void connectDB() throws SQLException {
connection = DriverManager.getConnection(url, userName, password);
}
public int getNumTables() throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(numTablesQuery);
// preparedStatement.get
preparedStatement.setString(1, dbName);
ResultSet resultSet = preparedStatement.executeQuery();
// while(resultSet.next())
// {
// System.out.println(resultSet.get);
// }
resultSet.next();
int numTables = resultSet.getInt("num_tables");
// System.out.println(numTables);
return numTables;
}
public void populateDB() throws SQLException {
// System.out.println("Database name = " + dbName);
// String sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '" + dbName + "' and TABLE_TYPE='BASE TABLE' ";
// String sql = numTablesQuery;
// System.out.println(numTablesQuery);
// System.out.println(sql);
// connection = DriverManager.getConnection(url, userName, password);
// PreparedStatement preparedStatement = connection.prepareStatement(numTablesQuery);
//// preparedStatement.get
// preparedStatement.setString(1, dbName);
// ResultSet resultSet = preparedStatement.executeQuery();
//// while(resultSet.next())
//// {
//// System.out.println(resultSet.get);
//// }
// resultSet.next();
// int numTables = resultSet.getInt("num_tables");
// System.out.println(numTables);
// if (numTables == 0) {
ScriptUtils.executeSqlScript(connection,
new EncodedResource(new ClassPathResource("scheme.sql"), StandardCharsets.UTF_8));
ScriptUtils.executeSqlScript(connection,
new EncodedResource(new ClassPathResource("datae.sql"), StandardCharsets.UTF_8));
// }
// connection.close();
}
public void closeConnection() throws SQLException {
connection.close();
}
}

View File

@ -1,8 +1,8 @@
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/chatto_db?useSSL=false
spring.datasource.username = chatto_user
spring.datasource.password = password
#
### Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
#spring.datasource.url = jdbc:mysql://localhost:3306/chatto_db?useSSL=false
#spring.datasource.username = chatto_user
#spring.datasource.password = password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
## Hibernate Properties
@ -11,7 +11,7 @@ spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDial
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = validate
spring.jpa.hibernate.ddl-auto = none
logging.level.org.springframework.web=DEBUG
logging.level.web=DEBUG

View File

@ -37,3 +37,10 @@
--(6, 'novo', '$2a$10$nLhkNrGu0/2ahSlULoQ0ROvUK2sRTEZBV014BLB/W9nBSMxy0rTGy', '2019-09-23 07:45:06'),
--(8, 'hmm', '$2a$10$k4tASmvqJ1mPA7avuzAnSO1KmWOmNhp7K8Y5Yg.dV/VXMX2L73/Ma', '2019-09-23 07:40:56'),
--(13, 'hmm2', '$2a$10$F.lMGPDXOguXWehMf1fvq.7XqzbFZWweLv3DYwB.1zpDEuPDcKBv6', '2019-09-23 13:46:33');
-- INSERT INTO `status` (`status`) values (true);
INSERT INTO `roles` (`role_id`, `role_name`, `description`) VALUES
(0, 'SUPER_USER', 'Most privileged'),
(1, 'ADMIN', 'Administrator'),
(2, 'USER', 'Regular user');

View File

@ -0,0 +1 @@
num-tables = SELECT COUNT(*) as num_tables FROM information_schema.tables WHERE table_schema = ? and TABLE_TYPE='BASE TABLE'

View File

@ -0,0 +1,345 @@
-- -- MySQL dump 10.15 Distrib 10.0.38-MariaDB, for debian-linux-gnu (x86_64)
-- --
-- -- Host: localhost Database: chatto_db
-- -- ------------------------------------------------------
-- -- Server version 10.0.38-MariaDB-0ubuntu0.16.04.1
-- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
-- /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
-- /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
-- /*!40101 SET NAMES utf8mb4 */;
-- /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
-- /*!40103 SET TIME_ZONE='+00:00' */;
-- /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
-- /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
-- /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
-- --
-- -- Table structure for table `admins`
-- --
-- --DROP TABLE IF EXISTS `admins`;
-- /*!40101 SET @saved_cs_client = @@character_set_client */;
-- /*!40101 SET character_set_client = utf8 */;
-- -- CREATE TABLE IF NOT EXISTS `admins` (
-- -- `admin_id` int(11) NOT NULL AUTO_INCREMENT,
-- -- `user_id` int(11) NOT NULL,
-- -- PRIMARY KEY (`admin_id`),
-- -- UNIQUE KEY `user_id_2` (`user_id`),
-- -- KEY `admin_id` (`admin_id`),
-- -- KEY `user_id` (`user_id`),
-- -- CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE
-- -- ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
-- /*!40101 SET character_set_client = @saved_cs_client */;
-- --
-- -- Table structure for table `chat_messages`
-- --
-- /*!40101 SET character_set_client = @saved_cs_client */;
-- --
-- -- Table structure for table `chatmessage`
-- --
-- --DROP TABLE IF EXISTS `chatmessage`;
-- /*!40101 SET @saved_cs_client = @@character_set_client */;
-- /*!40101 SET character_set_client = utf8 */;
-- CREATE TABLE IF NOT EXISTS `chatmessage` (
-- `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
-- `Message` varchar(4000) NOT NULL,
-- `userName` varchar(100) NOT NULL,
-- `MsgTime` varchar(45) NOT NULL,
-- `colorSelected` varchar(45) NOT NULL,
-- PRIMARY KEY (`Id`)
-- ) ENGINE=InnoDB AUTO_INCREMENT=402 DEFAULT CHARSET=latin1;
-- /*!40101 SET character_set_client = @saved_cs_client */;
-- --
-- -- Table structure for table `message_ciphers`
-- --
-- --DROP TABLE IF EXISTS `message_ciphers`;
-- /*!40101 SET @saved_cs_client = @@character_set_client */;
-- /*!40101 SET character_set_client = utf8 */;
-- CREATE TABLE IF NOT EXISTS `message_ciphers` (
-- `id` int(11) NOT NULL AUTO_INCREMENT,
-- `iv` varchar(30) NOT NULL,
-- `v` int(2) NOT NULL,
-- `iterations` int(11) NOT NULL,
-- `key_size` int(11) NOT NULL,
-- `tag_size` int(11) NOT NULL,
-- `mode` varchar(11) NOT NULL,
-- `adata` varchar(11) NOT NULL,
-- `cipher` varchar(11) NOT NULL,
-- `salt` varchar(100) NOT NULL,
-- `cipher_text` varchar(600) NOT NULL,
-- PRIMARY KEY (`id`)
-- ) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8mb4;
-- /*!40101 SET character_set_client = @saved_cs_client */;
-- --
-- -- Table structure for table `roles`
-- --
-- --DROP TABLE IF EXISTS `roles`;
-- /*!40101 SET @saved_cs_client = @@character_set_client */;
-- /*!40101 SET character_set_client = utf8 */;
-- CREATE TABLE IF NOT EXISTS `roles` (
-- `role_id` int(5) NOT NULL,
-- `role_name` varchar(15) NOT NULL,
-- `description` varchar(20) NOT NULL,
-- PRIMARY KEY (`role_id`)
-- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- /*!40101 SET character_set_client = @saved_cs_client */;
-- --
-- -- Table structure for table `total_messages`
-- --
-- --DROP TABLE IF EXISTS `total_messages`;
-- /*!40101 SET @saved_cs_client = @@character_set_client */;
-- /*!40101 SET character_set_client = utf8 */;
-- CREATE TABLE IF NOT EXISTS `total_messages` (
-- `t_id` int(101) NOT NULL AUTO_INCREMENT,
-- `from_user` int(11) NOT NULL,
-- `to_user` int(11) NOT NULL,
-- `total_messages` int(11) NOT NULL,
-- PRIMARY KEY (`t_id`),
-- UNIQUE KEY `identifier` (`t_id`)
-- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- /*!40101 SET character_set_client = @saved_cs_client */;
-- --
-- -- Table structure for table `users`
-- --
-- --DROP TABLE IF EXISTS `users`;
-- /*!40101 SET @saved_cs_client = @@character_set_client */;
-- /*!40101 SET character_set_client = utf8 */;
-- CREATE TABLE IF NOT EXISTS `users` (
-- `user_id` int(11) NOT NULL AUTO_INCREMENT,
-- `name` varchar(10) NOT NULL,
-- `password` varchar(80) NOT NULL,
-- `join_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- PRIMARY KEY (`user_id`),
-- UNIQUE KEY `name` (`name`),
-- KEY `user_id` (`user_id`)
-- ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4;
-- /*!40101 SET character_set_client = @saved_cs_client */;
-- --
-- -- Table structure for table `users_roles`
-- --
-- --DROP TABLE IF EXISTS `users_roles`;
-- /*!40101 SET @saved_cs_client = @@character_set_client */;
-- /*!40101 SET character_set_client = utf8 */;
-- CREATE TABLE IF NOT EXISTS `users_roles` (
-- `id` int(11) NOT NULL AUTO_INCREMENT,
-- `user_id` int(11) NOT NULL,
-- `role_id` int(11) NOT NULL,
-- PRIMARY KEY (`id`),
-- KEY `user` (`user_id`),
-- KEY `role` (`role_id`),
-- CONSTRAINT `FOREIGN KEY USER IN USERS-ROLES TABLE` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
-- CONSTRAINT `fk_roles_roleAssignments` FOREIGN KEY (`role_id`) REFERENCES `roles` (`role_id`) ON DELETE CASCADE ON UPDATE CASCADE
-- ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
-- /*!40101 SET character_set_client = @saved_cs_client */;
-- /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
-- /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
-- /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
-- /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
-- /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
-- /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
-- /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
-- /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- -- Dump completed on 2019-10-03 12:37:23
-- --DROP TABLE IF EXISTS `chat_messages`;
-- /*!40101 SET @saved_cs_client = @@character_set_client */;
-- /*!40101 SET character_set_client = utf8 */;
-- CREATE TABLE IF NOT EXISTS `chat_messages` (
-- `m_id` bigint(20) NOT NULL AUTO_INCREMENT,
-- `from_user` int(11) NOT NULL,
-- `to_user` int(11) NOT NULL,
-- `message` int(10) NOT NULL,
-- `message_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- PRIMARY KEY (`m_id`),
-- UNIQUE KEY `identifier_message_number` (`m_id`),
-- KEY `identifier_message_number_2` (`m_id`),
-- KEY `from_user` (`from_user`,`to_user`),
-- KEY `message` (`message`),
-- KEY `FOREIGN KEY TO USER IN MESSAGES TABLE` (`to_user`),
-- CONSTRAINT `FOREIGN KEY ENC MESSAGE TABLE` FOREIGN KEY (`message`) REFERENCES `message_ciphers` (`id`) ON UPDATE CASCADE,
-- CONSTRAINT `FOREIGN KEY FROM USER IN MESSAGES TABLE` FOREIGN KEY (`from_user`) REFERENCES `users` (`user_id`) ON UPDATE CASCADE,
-- CONSTRAINT `FOREIGN KEY TO USER IN MESSAGES TABLE` FOREIGN KEY (`to_user`) REFERENCES `users` (`user_id`) ON UPDATE CASCADE
-- ) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8mb4;
-- MySQL dump 10.15 Distrib 10.0.38-MariaDB, for debian-linux-gnu (x86_64)
--
-- Host: localhost Database: chatto_db
-- ------------------------------------------------------
-- Server version 10.0.38-MariaDB-0ubuntu0.16.04.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `chat_messages`
--
--DROP TABLE IF EXISTS `chat_messages`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `chatmessage`
--
--DROP TABLE IF EXISTS `chatmessage`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `chatmessage` (
`Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Message` varchar(4000) NOT NULL,
`userName` varchar(100) NOT NULL,
`MsgTime` varchar(45) NOT NULL,
`colorSelected` varchar(45) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `message_ciphers`
--
--DROP TABLE IF EXISTS `message_ciphers`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `message_ciphers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`iv` varchar(30) NOT NULL,
`v` int(2) NOT NULL,
`iterations` int(11) NOT NULL,
`key_size` int(11) NOT NULL,
`tag_size` int(11) NOT NULL,
`mode` varchar(11) NOT NULL,
`adata` varchar(11) NOT NULL,
`cipher` varchar(11) NOT NULL,
`salt` varchar(100) NOT NULL,
`cipher_text` varchar(600) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `roles`
--
--DROP TABLE IF EXISTS `roles`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `roles` (
`role_id` int(5) NOT NULL,
`role_name` varchar(15) NOT NULL,
`description` varchar(20) NOT NULL,
PRIMARY KEY (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `total_messages`
--
--DROP TABLE IF EXISTS `total_messages`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `total_messages` (
`t_id` int(101) NOT NULL AUTO_INCREMENT,
`from_user` int(11) NOT NULL,
`to_user` int(11) NOT NULL,
`total_messages` int(11) NOT NULL,
PRIMARY KEY (`t_id`),
UNIQUE KEY `identifier` (`t_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `users`
--
--DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) NOT NULL,
`password` varchar(80) NOT NULL,
`join_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`),
UNIQUE KEY `name` (`name`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `users_roles`
--
--DROP TABLE IF EXISTS `users_roles`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `users_roles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`role_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `user` (`user_id`),
KEY `role` (`role_id`),
CONSTRAINT `FOREIGN KEY USER IN USERS-ROLES TABLE` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_roles_roleAssignments` FOREIGN KEY (`role_id`) REFERENCES `roles` (`role_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `chat_messages` (
`m_id` bigint(20) NOT NULL AUTO_INCREMENT,
`from_user` int(11) NOT NULL,
`to_user` int(11) NOT NULL,
`message` int(10) NOT NULL,
`message_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`m_id`),
UNIQUE KEY `identifier_message_number` (`m_id`),
KEY `identifier_message_number_2` (`m_id`),
KEY `from_user` (`from_user`,`to_user`),
KEY `message` (`message`),
KEY `FOREIGN KEY TO USER IN MESSAGES TABLE` (`to_user`),
CONSTRAINT `FOREIGN KEY ENC MESSAGE TABLE` FOREIGN KEY (`message`) REFERENCES `message_ciphers` (`id`) ON UPDATE CASCADE,
CONSTRAINT `FOREIGN KEY FROM USER IN MESSAGES TABLE` FOREIGN KEY (`from_user`) REFERENCES `users` (`user_id`) ON UPDATE CASCADE,
CONSTRAINT `FOREIGN KEY TO USER IN MESSAGES TABLE` FOREIGN KEY (`to_user`) REFERENCES `users` (`user_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2019-10-03 12:37:23

View File

@ -15,9 +15,9 @@ var toUserRadios = document.getElementsByName('toUser');
var isCheckedUser = false;
var chatTextArea = document.getElementById('chatTextArea');
var passphraseInput = document.getElementById('passphrase');
var postNewMessageUrl = "http://192.168.1.8:8080/api/chat/post/message";
var getAllMessagesUrl = "http://192.168.1.8:8080/api/chat/get/messages/";
var getNewMessagesUrl = "http://192.168.1.8:8080/api/chat/get/messages/";
var postNewMessageUrl = "http://localhost:8080/api/chat/post/message";
var getAllMessagesUrl = "http://localhost:8080/api/chat/get/messages/";
var getNewMessagesUrl = "http://localhost:8080/api/chat/get/messages/";
// var messageLog = [];
var username = sessionStorage.getItem('username');
var password = sessionStorage.getItem('password');
@ -58,7 +58,7 @@ function handleChatForm() {
// console.log('second user = ' + user);
let messageContent = chatInput.value;
let localDate = new Date();
let messageLine = sprintf('%s %s %s: %s', localDate.toLocaleDateString(), localDate.toLocaleTimeString() ,username, messageContent);
let messageLine = sprintf('%s %s %s: %s', localDate.toLocaleDateString(), localDate.toLocaleTimeString(), username, messageContent);
chatTextArea.append(messageLine + "\n");
// let messageCipher = sjcl.encrypt("password", messageContent);
let messageCipher = sjcl.encrypt(passphraseInput.value, messageContent);
@ -191,6 +191,13 @@ parent.addDelegatedListener("click", "input[type='radio']", function (event) {
let i = 0;
let messageLog = [];
let lastMessageTimeStamp;
// console.log("Json length = " + json.length);
//
// if(json.length == 0)
// {
// console.log("JSON LENGTH IS 0")
// }
if (json.length > 0) {
json.forEach(function (obj) {
// console.log(obj.toUser);
messageCipher = JSON.stringify(obj.messageCipher);
@ -208,13 +215,17 @@ parent.addDelegatedListener("click", "input[type='radio']", function (event) {
// chatTextArea.append(obj.fromUser + ": " + message + "\n");
chatTextArea.append(messageLine + '\n');
messageLog[i++] = messageLine;
// console.log('Message log = ' + messageLog);
});
// console.log('Message log = ' + messageLog);
sessionStorage.setItem(this.value, JSON.stringify(messageLog));
// sessionStorage.clear();
console.log('Last message time = ' + lastMessageTimeStamp);
sessionStorage.setItem(this.value + '-time', lastMessageTimeStamp);
}
});
}
else {
@ -222,11 +233,14 @@ parent.addDelegatedListener("click", "input[type='radio']", function (event) {
console.log("Stored messages = " + sessionStorage.getItem(this.value));
let storedMessages = JSON.parse(sessionStorage.getItem(this.value));
getNewMessages(this.value, sessionStorage.getItem(this.value + '-time'))
let lastMessageTime = sessionStorage.getItem(this.value + '-time');
console.log("last message time stamp = " + lastMessageTime);
if (lastMessageTime != null) {
getNewMessages(this.value, lastMessageTime)
.then(json => {
console.log(json)
json.forEach(function (obj)
{
if (json.length > 0) {
json.forEach(function (obj) {
let messageCipher = JSON.stringify(obj.messageCipher);
let message = sjcl.decrypt(passphraseInput.value, messageCipher);
// console.log(message);
@ -241,17 +255,30 @@ parent.addDelegatedListener("click", "input[type='radio']", function (event) {
console.log(messageLine);
// chatTextArea.append(obj.fromUser + ": " + message + "\n");
chatTextArea.append(messageLine + '\n');
storedMessages.push(messageLine);
})
});
// sessionStorage.clear();
// chatTextArea.append(JSON.stringify(storedMessages));
sessionStorage.setItem(this.value + '-time', lastMessageTimeStamp);
sessionStorage.setItem(this.value, JSON.stringify(storedMessages));
console.log("this value stored" + sessionStorage.getItem(this.value))
console.log("last message time stamp = " + lastMessageTimeStamp);
console.log(sessionStorage.getItem(this.value + '-time'));
chatTextArea.textContent = '';
console.log("Stored messages 2 = " + storedMessages);
storedMessages.forEach(function (messageLine) {
chatTextArea.append(messageLine + '\n');
})
}
});
}
// sessionStorage.clear();
// chatTextArea.append(JSON.stringify(storedMessages));
}
// sessionStorage.setItem('status', 'ready');
// sessionStorage.setItem('this.value', messageLog);
// console.log('Message log = ' + messageLog);

View File

@ -20,23 +20,23 @@ import static org.mockito.Mockito.when;
@SpringBootTest
public class ChattoApplicationTests {
@Autowired
ChatMessageRepository chatMessageRepository;
@Mock
ChatMessageRepository mockChatMessageRepository;
@Autowired
UserRepository userRepository;
// @Autowired
// ChatMessageRepository chatMessageRepository;
//
// @Mock
// ChatMessageRepository mockChatMessageRepository;
//
// @Autowired
// UserRepository userRepository;
//
@Test
public void contextLoads() {
}
@Test
public void testMessageRepo() {
chatMessageRepository.findAll().toString();
}
//
// @Test
// public void testMessageRepo() {
// chatMessageRepository.findAll().toString();
// }
// @Test
// public void testSave() {

View File

@ -0,0 +1,23 @@
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/chatto_db?useSSL=false
spring.datasource.username = chatto_user
spring.datasource.password = password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = validate
logging.level.org.springframework.web=DEBUG
logging.level.web=DEBUG
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
spring.http.log-request-details=true
#spring.jackson.date-format=yyyy-MM-d
spring.jackson.serialization.write-dates-as-timestamps=false
#spring.mvc.static-path-pattern=/static/**