diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/Controllers/CollaborativeEditingController.cs b/Server side with database/ASP.NET Core/Using MS SQL Server/Controllers/CollaborativeEditingController.cs deleted file mode 100644 index 3ade8ea..0000000 --- a/Server side with database/ASP.NET Core/Using MS SQL Server/Controllers/CollaborativeEditingController.cs +++ /dev/null @@ -1,481 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Syncfusion.EJ2.DocumentEditor; -using Microsoft.AspNetCore.Cors; -using Microsoft.AspNetCore.SignalR; -using WebApplication1.Hubs; -using Microsoft.Data.SqlClient; -using System.Data; -using Microsoft.CodeAnalysis; - -namespace WebApplication1.Controllers -{ - [Route("api/[controller]")] - [ApiController] - public class CollaborativeEditingController : ControllerBase - { - private readonly IWebHostEnvironment _hostingEnvironment; - private readonly IHubContext _hubContext; - private static string connectionString; - private static string fileLocation; - private static byte saveThreshold = 200; - - public CollaborativeEditingController(IWebHostEnvironment hostingEnvironment, IHubContext hubContext, IConfiguration config) - { - _hostingEnvironment = hostingEnvironment; - _hubContext = hubContext; - //Database connection string - connectionString = config.GetConnectionString("DocumentEditorDatabase"); - fileLocation = _hostingEnvironment.WebRootPath; - } - - //Import document from wwwroot folder in web server. - [HttpPost] - [Route("ImportFile")] - [EnableCors("AllowAllOrigins")] - public string ImportFile([FromBody] FileInfo param) - { - DocumentContent content = new DocumentContent(); - WordDocument document = GetSourceDocument(param.fileName); - int lastSyncedVersion = 0; - List actions = CreatedTable(param.roomName, out lastSyncedVersion); - if (actions != null) - { - //Updated pending edit from database to source document. - document.UpdateActions(actions); - } - string json = Newtonsoft.Json.JsonConvert.SerializeObject(document); - content.version = lastSyncedVersion; - content.sfdt = json; - return Newtonsoft.Json.JsonConvert.SerializeObject(content); - } - - [HttpPost] - [Route("UpdateAction")] - [EnableCors("AllowAllOrigins")] - public async Task UpdateAction([FromBody] ActionInfo param) - { - try - { - ActionInfo modifiedAction = AddOperationsToTable(param); - await _hubContext.Clients.Group(param.RoomName).SendAsync("dataReceived", "action", modifiedAction); - return modifiedAction; - } - catch - { - return null; - } - } - - [HttpPost] - [Route("GetActionsFromServer")] - [EnableCors("AllowAllOrigins")] - public string GetActionsFromServer([FromBody] ActionInfo param) - { - string tableName = param.RoomName; - string getOperation = "SELECT * FROM \"" + tableName + "\" WHERE version > " + param.Version; - using (SqlConnection connection = new SqlConnection(connectionString)) - { - try - { - SqlCommand command2 = new SqlCommand(getOperation, connection); - SqlCommand updateCommand = new SqlCommand(getOperation, connection); - connection.Open(); - SqlDataReader reader = updateCommand.ExecuteReader(); - DataTable table = new DataTable(); - table.Load(reader); - DataTable oldTable = table; - if (table.Rows.Count > 0) - { - int startVersion = int.Parse(table.Rows[0]["version"].ToString()); - int lowestVersion = GetLowestClientVersion(table); - if (startVersion > lowestVersion) - { - string updatedOperation = "SELECT * FROM \"" + tableName + "\" WHERE version >= " + lowestVersion; - SqlCommand command = new SqlCommand(updatedOperation, connection); - SqlDataReader reader2 = command.ExecuteReader(); - table = new DataTable(); - table.Load(reader2); - } - List actions = GetOperationsQueue(table); - foreach (ActionInfo info in actions) - { - if (!info.IsTransformed) - { - CollaborativeEditingHandler.TransformOperation(info, actions); - } - } - actions = actions.Where(x => x.Version > param.Version).ToList(); - return Newtonsoft.Json.JsonConvert.SerializeObject(actions); - } - } - catch - { - return "{}"; - } - } - return "{}"; - } - - private static WordDocument GetSourceDocument(string fileName) - { - string path = fileLocation + "\\" + fileName; - int index = fileName.LastIndexOf('.'); - string type = index > -1 && index < fileName.Length - 1 ? - fileName.Substring(index) : ".docx"; - Stream stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); - WordDocument document = Syncfusion.EJ2.DocumentEditor.WordDocument.Load(stream, GetFormatType(type)); - stream.Dispose(); - return document; - } - - private List CreatedTable(string roomName, out int lastSyncedVersion) - { - lastSyncedVersion = 0; - string tableName = roomName; - if (!TableExists(tableName)) - { - - string queryString = "CREATE TABLE \"" + tableName + "\" (version int IDENTITY(1,1) PRIMARY KEY, operation nvarchar(max), clientVersion int)"; - using (SqlConnection connection = new SqlConnection(connectionString)) - { - - SqlCommand command = new SqlCommand(queryString, connection); - connection.Open(); - command.ExecuteNonQuery(); - // Create table to track the last saved version. - CreateRecordForVersionInfo(connection, roomName); - - } - } - else - { - - using (SqlConnection connection = new SqlConnection(connectionString)) - { - - connection.Open(); - lastSyncedVersion = GetLastedSyncedVersion(connection, tableName); - string queryString = "SELECT * FROM \"" + tableName + "\" WHERE version > " + lastSyncedVersion; - SqlCommand command = new SqlCommand(queryString, connection); - SqlDataReader reader = command.ExecuteReader(); - DataTable table = new DataTable(); - table.Load(reader); - List actions = GetOperationsQueue(table); - return actions; - - } - } - return null; - } - private void CreateRecordForVersionInfo(SqlConnection connection, String roomName) - { - string tableName = "de_version_info"; - - if (!TableExists(tableName)) - { - // If table doesn't exist, create it - string createTableQuery = $"CREATE TABLE \"{tableName}\" (roomName VARCHAR(MAX), lastSavedVersion INTEGER)"; - using (SqlCommand createTableCommand = new SqlCommand(createTableQuery, connection)) - { - createTableCommand.ExecuteNonQuery(); - } - } - - // Insert record into the table - string insertQuery = $"INSERT INTO \"{tableName}\" (roomName, lastSavedVersion) VALUES (@roomName, @lastSavedVersion)"; - using (SqlCommand insertCommand = new SqlCommand(insertQuery, connection)) - { - insertCommand.Parameters.AddWithValue("@roomName", roomName); - // Set initial version to 0 - insertCommand.Parameters.AddWithValue("@lastSavedVersion", 0); - insertCommand.ExecuteNonQuery(); - } - //} - - } - private bool TableExists(string tableName) - { - using (var connection = new SqlConnection(connectionString)) - { - var command = new SqlCommand($"SELECT CASE WHEN OBJECT_ID('{tableName}', 'U') IS NOT NULL THEN 1 ELSE 0 END", connection); - connection.Open(); - var result = (int)command.ExecuteScalar(); - return result == 1; - } - } - - private ActionInfo AddOperationsToTable(ActionInfo action) - { - int clientVersion = action.Version; - string tableName = action.RoomName; - string value = Newtonsoft.Json.JsonConvert.SerializeObject(action); - string query = "INSERT INTO \"" + tableName + "\" (operation, clientVersion) " + "VALUES (@Operation, @ClientVersion); ; SELECT SCOPE_IDENTITY() AS last_id"; - using (SqlConnection connection = new SqlConnection(connectionString)) - { - - SqlCommand command = new SqlCommand(query, connection); - command.Parameters.Add("@Operation", SqlDbType.NVarChar).Value = value; - command.Parameters.Add("@ClientVersion", SqlDbType.NVarChar).Value = action.Version; - connection.Open(); - int updateVersion = int.Parse(command.ExecuteScalar().ToString()); - if (updateVersion - clientVersion == 1) - { - action.Version = updateVersion; - UpdateCurrentActionToDB(tableName, action, connection); - } - else - { - DataTable table = GetOperationsToTransform(tableName, clientVersion + 1, updateVersion, connection); - int startVersion = int.Parse(table.Rows[0]["version"].ToString()); - int lowestVersion = GetLowestClientVersion(table); - if (startVersion > lowestVersion) - { - table = GetOperationsToTransform(tableName, lowestVersion, updateVersion, connection); - } - List actions = GetOperationsQueue(table); - foreach (ActionInfo info in actions) - { - if (!info.IsTransformed) - { - CollaborativeEditingHandler.TransformOperation(info, actions); - } - } - action = actions[actions.Count - 1]; - action.Version = updateVersion; - UpdateCurrentActionToDB(tableName, actions[actions.Count - 1], connection); - } - if (updateVersion % saveThreshold == 0) - { - UpdateOperationsToSourceDocument(tableName, HttpContext.Session.GetString("UserId"), true, updateVersion); - } - - - } - return action; - } - - private void UpdateCurrentActionToDB(string tableName, ActionInfo action, SqlConnection connection) - { - action.IsTransformed = true; - string updateQuery = "UPDATE \"" + tableName + "\" SET operation = @Operation WHERE version = " + action.Version.ToString(); - SqlCommand updateCommand = new SqlCommand(updateQuery, connection); - updateCommand.Parameters.Add("@Operation", SqlDbType.NVarChar).Value = Newtonsoft.Json.JsonConvert.SerializeObject(action); - updateCommand.ExecuteNonQuery(); - } - - private static DataTable GetOperationsToTransform(string tableName, int clientVersion, int currentVersion, SqlConnection connection) - { - string getOperation = "SELECT * FROM \"" + tableName + "\" WHERE version BETWEEN " + clientVersion + " AND " + currentVersion.ToString(); - SqlCommand command = new SqlCommand(getOperation, connection); - SqlDataReader reader = command.ExecuteReader(); - DataTable table = new DataTable(); - table.Load(reader); - return table; - } - - private static List GetOperationsQueue(DataTable table) - { - List actions = new List(); - foreach (DataRow row in table.Rows) - { - ActionInfo action = Newtonsoft.Json.JsonConvert.DeserializeObject(row["operation"].ToString()); - action.Version = int.Parse(row["version"].ToString()); - action.ClientVersion = int.Parse(row["clientVersion"].ToString()); - actions.Add(action); - } - return actions; - } - - private static int GetLowestClientVersion(DataTable table) - { - int clientVersion = int.Parse(table.Rows[0]["clientVersion"].ToString()); - foreach (DataRow row in table.Rows) - { - //TODO: Need to optimise version calculation for only untransformed operations - int version = int.Parse(row["clientVersion"].ToString()); - if (version < clientVersion) - { - clientVersion = version; - } - } - return clientVersion; - } - - internal static FormatType GetFormatType(string format) - { - if (string.IsNullOrEmpty(format)) - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - switch (format.ToLower()) - { - case ".dotx": - case ".docx": - case ".docm": - case ".dotm": - return FormatType.Docx; - case ".dot": - case ".doc": - return FormatType.Doc; - case ".rtf": - return FormatType.Rtf; - case ".txt": - return FormatType.Txt; - case ".xml": - return FormatType.WordML; - case ".html": - return FormatType.Html; - default: - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - } - } - - /// - /// Update editing operation to source document. - /// - public static void UpdateOperationsToSourceDocument(string fileName, string userId, bool partialSave, int endVersion) - { - try - { - SqlConnection connection = new SqlConnection(connectionString); - connection.Open(); - string tableName = fileName; - int lastSyncedVersion = GetLastedSyncedVersion(connection, fileName); - string getOperation = ""; - if (partialSave) - { - getOperation = "SELECT * FROM \"" + tableName + "\" WHERE version BETWEEN " + (lastSyncedVersion + 1).ToString() + " AND " + endVersion.ToString(); - //getOperation = "SELECT Top (" + saveThreshold.ToString() + ") * FROM \"" + tableName + "\""; - } - else - { - getOperation = "SELECT * FROM \"" + tableName + "\" WHERE version > " + lastSyncedVersion; - } - SqlCommand command = new SqlCommand(getOperation, connection); - SqlDataReader reader = command.ExecuteReader(); - DataTable table = new DataTable(); - table.Load(reader); - if (table.Rows.Count > 0) - { - List actions = GetOperationsQueue(table); - foreach (ActionInfo info in actions) - { - if (!info.IsTransformed) - { - CollaborativeEditingHandler.TransformOperation(info, actions); - } - } - //CollaborativeEditingHandler handler = new CollaborativeEditingHandler(GetDocumentFromDatabase(fileName, GetSelectedDocumentOwner(userId, fileName, connection))); - var currentDirectory = System.IO.Directory.GetCurrentDirectory(); - int index = fileName.LastIndexOf('.'); - string type = index > -1 && index < fileName.Length - 1 ? - fileName.Substring(index) : ".docx"; - Stream stream1 = System.IO.File.Open(currentDirectory + "\\" + fileName, FileMode.Open, FileAccess.ReadWrite); - Syncfusion.EJ2.DocumentEditor.WordDocument document = Syncfusion.EJ2.DocumentEditor.WordDocument.Load(stream1, GetFormatType(type)); - stream1.Close(); - CollaborativeEditingHandler handler = new CollaborativeEditingHandler(document); - for (int i = 0; i < actions.Count; i++) - { - //Console.WriteLine(i); - handler.UpdateAction(actions[i]); - } - MemoryStream stream = new MemoryStream(); - Syncfusion.DocIO.DLS.WordDocument doc = WordDocument.Save(Newtonsoft.Json.JsonConvert.SerializeObject(handler.Document)); - doc.Save(stream, Syncfusion.DocIO.FormatType.Docx); - stream.Position = 0; - byte[] data = stream.ToArray(); - System.IO.File.WriteAllBytes(currentDirectory + "\\output.docx", data); - stream.Close(); - if (!partialSave) - { - endVersion = actions[actions.Count - 1].Version; - } - doc.Close(); - } - if (!partialSave) - { - DeleteLastModifiedVersion(tableName, connection); - DropTable(fileName, connection); - - }else - { - UpdateModifiedVersion(tableName, connection, endVersion); - - } - - } - catch (Exception ex) - { - - } - - } - static void UpdateModifiedVersion(string roomName, SqlConnection connection, int lastSavedVersion) - { - string tableName = "de_version_info"; - string query = "UPDATE [" + tableName + "] SET lastSavedVersion = @lastSavedVersion WHERE roomName = @roomName"; - using (SqlCommand command = new SqlCommand(query, connection)) - { - - command.Parameters.AddWithValue("@lastSavedVersion", lastSavedVersion); - command.Parameters.AddWithValue("@roomName", roomName); - command.ExecuteNonQuery(); - } - } - static void DeleteLastModifiedVersion(string roomName, SqlConnection connection) - { - string tableName = "de_version_info"; - string query = "DELETE FROM [" + tableName + "] WHERE roomName = @roomName"; - - using (SqlCommand command = new SqlCommand(query, connection)) - { - command.Parameters.AddWithValue("@roomName", roomName); - command.ExecuteNonQuery(); - } - } - private static int GetLastedSyncedVersion(SqlConnection connection, string roomName) - { - string tableName = "de_version_info"; - string query = "SELECT lastSavedVersion FROM \"" + tableName + "\" WHERE roomName ='" + roomName + "'"; - var command = new SqlCommand(query, connection); - command.Parameters.Add("@roomName", SqlDbType.NVarChar).Value = roomName; - return int.Parse(command.ExecuteScalar().ToString()); - } - private static void DropTable(string documentId, SqlConnection connection) - { - try - { - //Delete operations record. - string sqlQuery = "drop table \"" + documentId + "\""; - var sqlCommand = new SqlCommand(sqlQuery, connection); - sqlCommand.ExecuteNonQuery(); - } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - } - - } - - - public class FileInfo - { - public string fileName - { - get; - set; - } - public string roomName - { - get; - set; - } - - } - - public class DocumentContent - { - public int version { get; set; } - - public string sfdt { get; set; } - } -} diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/Controllers/DocumentEditorController.cs b/Server side with database/ASP.NET Core/Using MS SQL Server/Controllers/DocumentEditorController.cs deleted file mode 100644 index 810f729..0000000 --- a/Server side with database/ASP.NET Core/Using MS SQL Server/Controllers/DocumentEditorController.cs +++ /dev/null @@ -1,197 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Syncfusion.EJ2.DocumentEditor; -using WFormatType = Syncfusion.DocIO.FormatType; -using Syncfusion.EJ2.SpellChecker; -using Microsoft.AspNetCore.Cors; - -namespace WebApplication1.Controllers -{ - [Route("api/[controller]")] - [ApiController] - public class DocumentEditorController : ControllerBase - { - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("Import")] - public string Import(IFormCollection data) - { - if (data.Files.Count == 0) - return null; - Stream stream1 = new MemoryStream(); - IFormFile file = data.Files[0]; - int index = file.FileName.LastIndexOf('.'); - string type = index > -1 && index < file.FileName.Length - 1 ? - file.FileName.Substring(index) : ".docx"; - file.CopyTo(stream1); - stream1.Position = 0; - - WordDocument document = WordDocument.Load(stream1, GetFormatType(type.ToLower())); - string json = Newtonsoft.Json.JsonConvert.SerializeObject(document); - document.Dispose(); - return json; - } - - public class CustomParams - { - public string fileName - { - get; - set; - } - } - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("SpellCheck")] - public string SpellCheck([FromBody] SpellCheckJsonData spellChecker) - { - try - { - SpellChecker spellCheck = new SpellChecker(); - spellCheck.GetSuggestions(spellChecker.LanguageID, spellChecker.TexttoCheck, spellChecker.CheckSpelling, spellChecker.CheckSuggestion, spellChecker.AddWord); - return Newtonsoft.Json.JsonConvert.SerializeObject(spellCheck); - } - catch - { - return "{\"SpellCollection\":[],\"HasSpellingError\":false,\"Suggestions\":null}"; - } - } - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("SpellCheckByPage")] - public string SpellCheckByPage([FromBody] SpellCheckJsonData spellChecker) - { - try - { - SpellChecker spellCheck = new SpellChecker(); - spellCheck.CheckSpelling(spellChecker.LanguageID, spellChecker.TexttoCheck); - return Newtonsoft.Json.JsonConvert.SerializeObject(spellCheck); - } - catch - { - return "{\"SpellCollection\":[],\"HasSpellingError\":false,\"Suggestions\":null}"; - } - } - - public class SpellCheckJsonData - { - public int LanguageID { get; set; } - public string TexttoCheck { get; set; } - public bool CheckSpelling { get; set; } - public bool CheckSuggestion { get; set; } - public bool AddWord { get; set; } - - } - - public class CustomParameter - { - public string content { get; set; } - public string type { get; set; } - } - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("SystemClipboard")] - public string SystemClipboard([FromBody] CustomParameter param) - { - if (param.content != null && param.content != "") - { - try - { - WordDocument document = WordDocument.LoadString(param.content, GetFormatType(param.type.ToLower())); - string json = Newtonsoft.Json.JsonConvert.SerializeObject(document); - document.Dispose(); - return json; - } - catch (Exception) - { - return ""; - } - } - return ""; - } - - public class CustomRestrictParameter - { - public string passwordBase64 { get; set; } - public string saltBase64 { get; set; } - public int spinCount { get; set; } - } - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("RestrictEditing")] - public string[] RestrictEditing([FromBody] CustomRestrictParameter param) - { - if (param.passwordBase64 == "" && param.passwordBase64 == null) - return null; - return WordDocument.ComputeHash(param.passwordBase64, param.saltBase64, param.spinCount); - } - - internal static FormatType GetFormatType(string format) - { - if (string.IsNullOrEmpty(format)) - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - switch (format.ToLower()) - { - case ".dotx": - case ".docx": - case ".docm": - case ".dotm": - return FormatType.Docx; - case ".dot": - case ".doc": - return FormatType.Doc; - case ".rtf": - return FormatType.Rtf; - case ".txt": - return FormatType.Txt; - case ".xml": - return FormatType.WordML; - case ".html": - return FormatType.Html; - default: - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - } - } - internal static WFormatType GetWFormatType(string format) - { - if (string.IsNullOrEmpty(format)) - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - switch (format.ToLower()) - { - case ".dotx": - return WFormatType.Dotx; - case ".docx": - return WFormatType.Docx; - case ".docm": - return WFormatType.Docm; - case ".dotm": - return WFormatType.Dotm; - case ".dot": - return WFormatType.Dot; - case ".doc": - return WFormatType.Doc; - case ".rtf": - return WFormatType.Rtf; - case ".html": - return WFormatType.Html; - case ".txt": - return WFormatType.Txt; - case ".xml": - return WFormatType.WordML; - case ".odt": - return WFormatType.Odt; - default: - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - } - } - - } -} diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/Hubs/DocumentEditorHub.cs b/Server side with database/ASP.NET Core/Using MS SQL Server/Hubs/DocumentEditorHub.cs deleted file mode 100644 index e8fa68a..0000000 --- a/Server side with database/ASP.NET Core/Using MS SQL Server/Hubs/DocumentEditorHub.cs +++ /dev/null @@ -1,76 +0,0 @@ -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.SignalR; -using Syncfusion.EJ2.DocumentEditor; -using WebApplication1.Controllers; - -namespace WebApplication1.Hubs -{ - public class DocumentEditorHub : Hub - { - - static Dictionary userManager = new Dictionary(); - internal static Dictionary> groupManager = new Dictionary>(); - - public async Task JoinGroup(ActionInfo info) - { - if (!userManager.ContainsKey(Context.ConnectionId)) - { - userManager.Add(Context.ConnectionId, info); - } - info.ConnectionId = Context.ConnectionId; - //Add to SignalR group - await Groups.AddToGroupAsync(Context.ConnectionId, info.RoomName); - if (groupManager.ContainsKey(info.RoomName)) - { - await Clients.Caller.SendAsync("dataReceived", "addUser", groupManager[info.RoomName]); - } - lock (groupManager) - { - if (groupManager.ContainsKey(info.RoomName)) - { - groupManager[info.RoomName].Add(info); - } - else - { - List actions = new List { info }; - groupManager.Add(info.RoomName, actions); - } - } - //Send information about new user joining to others - Clients.GroupExcept(info.RoomName, Context.ConnectionId).SendAsync("dataReceived", "addUser", info); - } - - public override Task OnConnectedAsync() - { - //Send connection id to client side - Clients.Caller.SendAsync("dataReceived", "connectionId", Context.ConnectionId); - return base.OnConnectedAsync(); - } - - public override System.Threading.Tasks.Task OnDisconnectedAsync(Exception? e) - { - string roomName = userManager[Context.ConnectionId].RoomName; - if (groupManager.ContainsKey(roomName)) - { - groupManager[roomName].Remove(userManager[Context.ConnectionId]); - - if (groupManager[roomName].Count == 0) - { - groupManager.Remove(roomName); - string userid = Context.GetHttpContext().Session.GetString("UserId"); - //Handle updating all editing operations for source document - CollaborativeEditingController.UpdateOperationsToSourceDocument(roomName, userid, false, 0); - } - } - - if (userManager.ContainsKey(Context.ConnectionId)) - { - //Send notification about user disconnection to other clients. - Clients.OthersInGroup(roomName).SendAsync("dataReceived", "removeUser", Context.ConnectionId); - Groups.RemoveFromGroupAsync(Context.ConnectionId, roomName); - userManager.Remove(Context.ConnectionId); - } - return base.OnDisconnectedAsync(e); - } - } -} diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/Program.cs b/Server side with database/ASP.NET Core/Using MS SQL Server/Program.cs deleted file mode 100644 index 721e9e1..0000000 --- a/Server side with database/ASP.NET Core/Using MS SQL Server/Program.cs +++ /dev/null @@ -1,43 +0,0 @@ -using WebApplication1.Hubs; -using Microsoft.Azure.SignalR; - -var builder = WebApplication.CreateBuilder(args); - -builder.Services.AddControllersWithViews(); - -builder.Services.AddSignalR(); - -builder.Services.AddCors(options => -{ - options.AddPolicy("AllowAllOrigins", builder => - { - builder.AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader(); - }); -}); - -builder.Services.AddEndpointsApiExplorer(); - -var app = builder.Build(); - -app.UseStaticFiles(); - -app.UseRouting(); - -app.UseCors(); - -app.MapHub("/documenteditorhub"); - -app.MapControllers(); - -app.UseAuthorization(); - -app.UseEndpoints(endpoints => -{ - endpoints.MapControllerRoute( - name: "default", - pattern: "{controller=Home}/{action=LogIn}/{userName?}/{id?}"); -}); - -app.Run(); diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/Properties/launchSettings.json b/Server side with database/ASP.NET Core/Using MS SQL Server/Properties/launchSettings.json deleted file mode 100644 index e4879bd..0000000 --- a/Server side with database/ASP.NET Core/Using MS SQL Server/Properties/launchSettings.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:38517", - "sslPort": 0 - } - }, - "profiles": { - "WebApplication1": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "applicationUrl": "http://localhost:5212", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/Views/Home/Error.cshtml b/Server side with database/ASP.NET Core/Using MS SQL Server/Views/Home/Error.cshtml deleted file mode 100644 index f56cacb..0000000 --- a/Server side with database/ASP.NET Core/Using MS SQL Server/Views/Home/Error.cshtml +++ /dev/null @@ -1,7 +0,0 @@ -@* - For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 -*@ -@{ -} - -
@ViewBag.errorMessage
\ No newline at end of file diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/WeatherForecast.cs b/Server side with database/ASP.NET Core/Using MS SQL Server/WeatherForecast.cs deleted file mode 100644 index d352e27..0000000 --- a/Server side with database/ASP.NET Core/Using MS SQL Server/WeatherForecast.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace WebApplication1 -{ - public class WeatherForecast - { - public DateTime Date { get; set; } - - public int TemperatureC { get; set; } - - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - - public string? Summary { get; set; } - } -} \ No newline at end of file diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/WebApplication1.csproj b/Server side with database/ASP.NET Core/Using MS SQL Server/WebApplication1.csproj deleted file mode 100644 index 7c61e4a..0000000 --- a/Server side with database/ASP.NET Core/Using MS SQL Server/WebApplication1.csproj +++ /dev/null @@ -1,29 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/WebApplication1.sln b/Server side with database/ASP.NET Core/Using MS SQL Server/WebApplication1.sln deleted file mode 100644 index eff9773..0000000 --- a/Server side with database/ASP.NET Core/Using MS SQL Server/WebApplication1.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.4.33213.308 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApplication1", "WebApplication1.csproj", "{4356F1ED-F73A-44BC-8FA8-40B267A79C70}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - Release-Xml|Any CPU = Release-Xml|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release|Any CPU.Build.0 = Release|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release-Xml|Any CPU.ActiveCfg = Release|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release-Xml|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {56EAA24C-30CF-403F-9733-BDD27FB18338} - EndGlobalSection -EndGlobal diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/appsettings.Development.json b/Server side with database/ASP.NET Core/Using MS SQL Server/appsettings.Development.json deleted file mode 100644 index 0c208ae..0000000 --- a/Server side with database/ASP.NET Core/Using MS SQL Server/appsettings.Development.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/appsettings.json b/Server side with database/ASP.NET Core/Using MS SQL Server/appsettings.json deleted file mode 100644 index 5a68542..0000000 --- a/Server side with database/ASP.NET Core/Using MS SQL Server/appsettings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*", - "ConnectionStrings": { - "DocumentEditorDatabase": "<>" - } -} \ No newline at end of file diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Character Formatting.docx b/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Character Formatting.docx deleted file mode 100644 index 5371ccc..0000000 Binary files a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Character Formatting.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Footnotes and Endnotes.docx b/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Footnotes and Endnotes.docx deleted file mode 100644 index da9c89e..0000000 Binary files a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Footnotes and Endnotes.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Getting Started.docx b/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Getting Started.docx deleted file mode 100644 index 4b7ea44..0000000 Binary files a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Getting Started.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Giant Panda.docx b/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Giant Panda.docx deleted file mode 100644 index f89bb27..0000000 Binary files a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Giant Panda.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Paragraph Formatting.docx b/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Paragraph Formatting.docx deleted file mode 100644 index 3f324d3..0000000 Binary files a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Paragraph Formatting.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Styles.docx b/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Styles.docx deleted file mode 100644 index 5668463..0000000 Binary files a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Styles.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Table Formatting.docx b/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Table Formatting.docx deleted file mode 100644 index e620881..0000000 Binary files a/Server side with database/ASP.NET Core/Using MS SQL Server/wwwroot/Table Formatting.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MySql Server/Controllers/CollaborativeEditingController.cs b/Server side with database/ASP.NET Core/Using MySql Server/Controllers/CollaborativeEditingController.cs deleted file mode 100644 index bdba227..0000000 --- a/Server side with database/ASP.NET Core/Using MySql Server/Controllers/CollaborativeEditingController.cs +++ /dev/null @@ -1,508 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Syncfusion.EJ2.DocumentEditor; -using Microsoft.AspNetCore.Cors; -using Microsoft.AspNetCore.SignalR; -using WebApplication1.Hubs; -using System.Data; -using Microsoft.CodeAnalysis; -using MySql.Data.MySqlClient; - -namespace WebApplication1.Controllers -{ - [Route("api/[controller]")] - [ApiController] - public class CollaborativeEditingController : ControllerBase - { - private readonly IWebHostEnvironment _hostingEnvironment; - private readonly IHubContext _hubContext; - private static string connectionString; - private static string fileLocation; - private static byte saveThreshold = 200; - - public CollaborativeEditingController(IWebHostEnvironment hostingEnvironment, IHubContext hubContext, IConfiguration config) - { - _hostingEnvironment = hostingEnvironment; - _hubContext = hubContext; - //Database connection string - connectionString = config.GetConnectionString("DocumentEditorDatabase"); - fileLocation = _hostingEnvironment.WebRootPath; - } - - //Import document from wwwroot folder in web server. - [HttpPost] - [Route("ImportFile")] - [EnableCors("AllowAllOrigins")] - public string ImportFile([FromBody] FileInfo param) - { - DocumentContent content = new DocumentContent(); - WordDocument document = GetSourceDocument(param.fileName); - int lastSyncedVersion = 0; - List actions = CreatedTable(param.roomName, out lastSyncedVersion); - if (actions != null) - { - //Updated pending edit from database to source document. - document.UpdateActions(actions); - } - string json = Newtonsoft.Json.JsonConvert.SerializeObject(document); - content.version = lastSyncedVersion; - content.sfdt = json; - return Newtonsoft.Json.JsonConvert.SerializeObject(content); - } - - [HttpPost] - [Route("UpdateAction")] - [EnableCors("AllowAllOrigins")] - public async Task UpdateAction([FromBody] ActionInfo param) - { - try - { - ActionInfo modifiedAction = AddOperationsToTable(param); - await _hubContext.Clients.Group(param.RoomName).SendAsync("dataReceived", "action", modifiedAction); - return modifiedAction; - } - catch - { - return null; - } - } - - [HttpPost] - [Route("GetActionsFromServer")] - [EnableCors("AllowAllOrigins")] - public string GetActionsFromServer([FromBody] ActionInfo param) - { - string tableName = param.RoomName; - string getOperation = "SELECT * FROM \"" + tableName + "\" WHERE version > " + param.Version; - using (MySqlConnection connection = new MySqlConnection(connectionString)) - { - try - { - MySqlCommand command2 = new MySqlCommand(getOperation, connection); - MySqlCommand updateCommand = new MySqlCommand(getOperation, connection); - connection.Open(); - MySqlDataReader reader = updateCommand.ExecuteReader(); - DataTable table = new DataTable(); - table.Load(reader); - DataTable oldTable = table; - if (table.Rows.Count > 0) - { - int startVersion = int.Parse(table.Rows[0]["version"].ToString()); - int lowestVersion = GetLowestClientVersion(table); - if (startVersion > lowestVersion) - { - string updatedOperation = "SELECT * FROM \"" + tableName + "\" WHERE version >= " + lowestVersion; - MySqlCommand command = new MySqlCommand(updatedOperation, connection); - MySqlDataReader reader2 = command.ExecuteReader(); - table = new DataTable(); - table.Load(reader2); - } - List actions = GetOperationsQueue(table); - foreach (ActionInfo info in actions) - { - if (!info.IsTransformed) - { - CollaborativeEditingHandler.TransformOperation(info, actions); - } - } - actions = actions.Where(x => x.Version > param.Version).ToList(); - return Newtonsoft.Json.JsonConvert.SerializeObject(actions); - } - } - catch - { - return "{}"; - } - } - return "{}"; - } - - private static WordDocument GetSourceDocument(string fileName) - { - string path = fileLocation + "\\" + fileName; - int index = fileName.LastIndexOf('.'); - string type = index > -1 && index < fileName.Length - 1 ? - fileName.Substring(index) : ".docx"; - Stream stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); - WordDocument document = Syncfusion.EJ2.DocumentEditor.WordDocument.Load(stream, GetFormatType(type)); - stream.Dispose(); - return document; - } - - private List CreatedTable(string roomName, out int lastSyncedVersion) - { - lastSyncedVersion = 0; - string tableName = roomName; - if (!TableExists(tableName)) - { - - string queryString = "CREATE TABLE `" + tableName + "` (" + "`version` INT AUTO_INCREMENT PRIMARY KEY, " + - "`operation` TEXT, " + - "`clientVersion` INT)"; - using (MySqlConnection connection = new MySqlConnection(connectionString)) - { - - MySqlCommand command = new MySqlCommand(queryString, connection); - connection.Open(); - command.ExecuteNonQuery(); - // Create table to track the last saved version. - CreateRecordForVersionInfo(connection, roomName); - - } - } - else - { - - using (MySqlConnection connection = new MySqlConnection(connectionString)) - { - - connection.Open(); - lastSyncedVersion = GetLastedSyncedVersion(connection, tableName); - string queryString = $"SELECT * FROM `{tableName}` WHERE version > @lastSyncedVersion"; - - using (MySqlCommand command = new MySqlCommand(queryString, connection)) - { - command.Parameters.AddWithValue("@lastSyncedVersion", lastSyncedVersion); - - using (MySqlDataReader reader = command.ExecuteReader()) - { - DataTable table = new DataTable(); - table.Load(reader); - - List actions = GetOperationsQueue(table); - return actions; - } - } - - } - } - return null; - } - private void CreateRecordForVersionInfo(MySqlConnection connection, String roomName) - { - string tableName = "de_version_info"; - - if (!TableExists(tableName)) - { - // If table doesn't exist, create it - string createTableQuery = $"CREATE TABLE `{tableName}` (`roomName` VARCHAR(255), `lastSavedVersion` INT);"; - using (MySqlCommand createTableCommand = new MySqlCommand(createTableQuery, connection)) - { - createTableCommand.ExecuteNonQuery(); - } - } - - // Insert record into the table - string insertQuery = $"INSERT INTO `{tableName}` (roomName, lastSavedVersion) VALUES (@roomName, @lastSavedVersion)"; - using (MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection)) - { - insertCommand.Parameters.AddWithValue("@roomName", roomName); - // Set initial version to 0 - insertCommand.Parameters.AddWithValue("@lastSavedVersion", 0); - insertCommand.ExecuteNonQuery(); - } - //} - - } - private bool TableExists(string tableName) - { - using (var connection = new MySqlConnection(connectionString)) - { - var command = new MySqlCommand($"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = '{tableName}'", connection); - connection.Open(); - var result = (long)command.ExecuteScalar(); - return result == 1; - } - } - - private ActionInfo AddOperationsToTable(ActionInfo action) - { - int clientVersion = action.Version; - string tableName = action.RoomName; - string value = Newtonsoft.Json.JsonConvert.SerializeObject(action); - string query = $"INSERT INTO `{tableName}` (operation, clientVersion) VALUES (@Operation, @ClientVersion); SELECT LAST_INSERT_ID();"; - - using (MySqlConnection connection = new MySqlConnection(connectionString)) - { - MySqlCommand command = new MySqlCommand(query, connection); - command.Parameters.Add("@Operation", MySqlDbType.VarChar).Value = value; - command.Parameters.Add("@ClientVersion", MySqlDbType.Int32).Value = action.Version; - connection.Open(); - int updateVersion = Convert.ToInt32(command.ExecuteScalar()); - if (updateVersion - clientVersion == 1) - { - action.Version = updateVersion; - UpdateCurrentActionToDB(tableName, action, connection); - } - else - { - DataTable table = GetOperationsToTransform(tableName, clientVersion + 1, updateVersion, connection); - int startVersion = int.Parse(table.Rows[0]["version"].ToString()); - int lowestVersion = GetLowestClientVersion(table); - if (startVersion > lowestVersion) - { - table = GetOperationsToTransform(tableName, lowestVersion, updateVersion, connection); - } - List actions = GetOperationsQueue(table); - foreach (ActionInfo info in actions) - { - if (!info.IsTransformed) - { - CollaborativeEditingHandler.TransformOperation(info, actions); - } - } - action = actions[actions.Count - 1]; - action.Version = updateVersion; - UpdateCurrentActionToDB(tableName, actions[actions.Count - 1], connection); - } - if (updateVersion % saveThreshold == 0) - { - UpdateOperationsToSourceDocument(tableName, HttpContext.Session.GetString("UserId"), true, updateVersion); - } - - - } - return action; - } - - private void UpdateCurrentActionToDB(string tableName, ActionInfo action, MySqlConnection connection) - { - action.IsTransformed = true; - string updateQuery = $"UPDATE `{tableName}` SET operation = @Operation WHERE version = @Version"; - using (MySqlCommand updateCommand = new MySqlCommand(updateQuery, connection)) - { - updateCommand.Parameters.Add("@Operation", MySqlDbType.VarChar).Value = Newtonsoft.Json.JsonConvert.SerializeObject(action); - updateCommand.Parameters.Add("@Version", MySqlDbType.Int32).Value = action.Version; - - updateCommand.ExecuteNonQuery(); - } - } - - private static DataTable GetOperationsToTransform(string tableName, int clientVersion, int currentVersion, MySqlConnection connection) - { - string getOperation = $"SELECT * FROM `{tableName}` WHERE version BETWEEN @ClientVersion AND @CurrentVersion"; - - using (MySqlCommand command = new MySqlCommand(getOperation, connection)) - { - command.Parameters.Add("@ClientVersion", MySqlDbType.Int32).Value = clientVersion; - command.Parameters.Add("@CurrentVersion", MySqlDbType.Int32).Value = currentVersion; - - using (MySqlDataReader reader = command.ExecuteReader()) - { - DataTable table = new DataTable(); - table.Load(reader); - return table; - } - } - } - - private static List GetOperationsQueue(DataTable table) - { - List actions = new List(); - foreach (DataRow row in table.Rows) - { - ActionInfo action = Newtonsoft.Json.JsonConvert.DeserializeObject(row["operation"].ToString()); - action.Version = int.Parse(row["version"].ToString()); - action.ClientVersion = int.Parse(row["clientVersion"].ToString()); - actions.Add(action); - } - return actions; - } - - private static int GetLowestClientVersion(DataTable table) - { - int clientVersion = int.Parse(table.Rows[0]["clientVersion"].ToString()); - foreach (DataRow row in table.Rows) - { - //TODO: Need to optimise version calculation for only untransformed operations - int version = int.Parse(row["clientVersion"].ToString()); - if (version < clientVersion) - { - clientVersion = version; - } - } - return clientVersion; - } - - internal static FormatType GetFormatType(string format) - { - if (string.IsNullOrEmpty(format)) - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - switch (format.ToLower()) - { - case ".dotx": - case ".docx": - case ".docm": - case ".dotm": - return FormatType.Docx; - case ".dot": - case ".doc": - return FormatType.Doc; - case ".rtf": - return FormatType.Rtf; - case ".txt": - return FormatType.Txt; - case ".xml": - return FormatType.WordML; - case ".html": - return FormatType.Html; - default: - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - } - } - - /// - /// Update editing operation to source document. - /// - public static void UpdateOperationsToSourceDocument(string fileName, string userId, bool partialSave, int endVersion) - { - try - { - MySqlConnection connection = new MySqlConnection(connectionString); - connection.Open(); - string tableName = fileName; - int lastSyncedVersion = GetLastedSyncedVersion(connection, fileName); - string getOperation = ""; - if (partialSave) - { - getOperation = "SELECT * FROM `" + tableName + "` WHERE version BETWEEN @StartVersion AND @EndVersion"; - } - else - { - getOperation = "SELECT * FROM `" + tableName + "` WHERE version > @LastSyncedVersion"; - } - MySqlCommand command = new MySqlCommand(getOperation, connection); - MySqlDataReader reader = command.ExecuteReader(); - DataTable table = new DataTable(); - table.Load(reader); - if (table.Rows.Count > 0) - { - List actions = GetOperationsQueue(table); - foreach (ActionInfo info in actions) - { - if (!info.IsTransformed) - { - CollaborativeEditingHandler.TransformOperation(info, actions); - } - } - //CollaborativeEditingHandler handler = new CollaborativeEditingHandler(GetDocumentFromDatabase(fileName, GetSelectedDocumentOwner(userId, fileName, connection))); - var currentDirectory = System.IO.Directory.GetCurrentDirectory(); - int index = fileName.LastIndexOf('.'); - string type = index > -1 && index < fileName.Length - 1 ? - fileName.Substring(index) : ".docx"; - Stream stream1 = System.IO.File.Open(currentDirectory + "\\" + fileName, FileMode.Open, FileAccess.ReadWrite); - Syncfusion.EJ2.DocumentEditor.WordDocument document = Syncfusion.EJ2.DocumentEditor.WordDocument.Load(stream1, GetFormatType(type)); - stream1.Close(); - CollaborativeEditingHandler handler = new CollaborativeEditingHandler(document); - for (int i = 0; i < actions.Count; i++) - { - //Console.WriteLine(i); - handler.UpdateAction(actions[i]); - } - MemoryStream stream = new MemoryStream(); - Syncfusion.DocIO.DLS.WordDocument doc = WordDocument.Save(Newtonsoft.Json.JsonConvert.SerializeObject(handler.Document)); - doc.Save(stream, Syncfusion.DocIO.FormatType.Docx); - stream.Position = 0; - byte[] data = stream.ToArray(); - System.IO.File.WriteAllBytes(currentDirectory + "\\output.docx", data); - stream.Close(); - if (!partialSave) - { - endVersion = actions[actions.Count - 1].Version; - } - doc.Close(); - } - if (!partialSave) - { - DeleteLastModifiedVersion(tableName, connection); - DropTable(fileName, connection); - - }else - { - UpdateModifiedVersion(tableName, connection, endVersion); - - } - - } - catch (Exception ex) - { - - } - - } - static void UpdateModifiedVersion(string roomName, MySqlConnection connection, int lastSavedVersion) - { - string tableName = "de_version_info"; - string query = "UPDATE `" + tableName + "` SET lastSavedVersion = @lastSavedVersion WHERE roomName = @roomName"; - - using (MySqlCommand command = new MySqlCommand(query, connection)) - { - command.Parameters.AddWithValue("@lastSavedVersion", lastSavedVersion); - command.Parameters.AddWithValue("@roomName", roomName); - - int rowsAffected = command.ExecuteNonQuery(); - Console.WriteLine($"Rows affected: {rowsAffected}"); - } - } - static void DeleteLastModifiedVersion(string roomName, MySqlConnection connection) - { - string tableName = "de_version_info"; - string query = "DELETE FROM `" + tableName + "` WHERE roomName = @roomName"; - - using (MySqlCommand command = new MySqlCommand(query, connection)) - { - command.Parameters.AddWithValue("@roomName", roomName); - command.ExecuteNonQuery(); - } - } - private static int GetLastedSyncedVersion(MySqlConnection connection, string roomName) - { - string tableName = "de_version_info"; - string query = $"SELECT lastSavedVersion FROM `{tableName}` WHERE roomName = @roomName"; - using (var command = new MySqlCommand(query, connection)) - { - command.Parameters.Add("@roomName", MySqlDbType.VarChar).Value = roomName; - - object result = command.ExecuteScalar(); - return result != null ? Convert.ToInt32(result) : -1; - } - } - private static void DropTable(string documentId, MySqlConnection connection) - { - try - { - //Delete operations record. - string sqlQuery = $"DROP TABLE `{documentId}`"; - MySqlCommand sqlCommand = new MySqlCommand(sqlQuery, connection); - sqlCommand.ExecuteNonQuery(); - } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - } - - } - - - public class FileInfo - { - public string fileName - { - get; - set; - } - public string roomName - { - get; - set; - } - - } - - public class DocumentContent - { - public int version { get; set; } - - public string sfdt { get; set; } - } -} diff --git a/Server side with database/ASP.NET Core/Using MySql Server/Controllers/DocumentEditorController.cs b/Server side with database/ASP.NET Core/Using MySql Server/Controllers/DocumentEditorController.cs deleted file mode 100644 index 810f729..0000000 --- a/Server side with database/ASP.NET Core/Using MySql Server/Controllers/DocumentEditorController.cs +++ /dev/null @@ -1,197 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Syncfusion.EJ2.DocumentEditor; -using WFormatType = Syncfusion.DocIO.FormatType; -using Syncfusion.EJ2.SpellChecker; -using Microsoft.AspNetCore.Cors; - -namespace WebApplication1.Controllers -{ - [Route("api/[controller]")] - [ApiController] - public class DocumentEditorController : ControllerBase - { - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("Import")] - public string Import(IFormCollection data) - { - if (data.Files.Count == 0) - return null; - Stream stream1 = new MemoryStream(); - IFormFile file = data.Files[0]; - int index = file.FileName.LastIndexOf('.'); - string type = index > -1 && index < file.FileName.Length - 1 ? - file.FileName.Substring(index) : ".docx"; - file.CopyTo(stream1); - stream1.Position = 0; - - WordDocument document = WordDocument.Load(stream1, GetFormatType(type.ToLower())); - string json = Newtonsoft.Json.JsonConvert.SerializeObject(document); - document.Dispose(); - return json; - } - - public class CustomParams - { - public string fileName - { - get; - set; - } - } - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("SpellCheck")] - public string SpellCheck([FromBody] SpellCheckJsonData spellChecker) - { - try - { - SpellChecker spellCheck = new SpellChecker(); - spellCheck.GetSuggestions(spellChecker.LanguageID, spellChecker.TexttoCheck, spellChecker.CheckSpelling, spellChecker.CheckSuggestion, spellChecker.AddWord); - return Newtonsoft.Json.JsonConvert.SerializeObject(spellCheck); - } - catch - { - return "{\"SpellCollection\":[],\"HasSpellingError\":false,\"Suggestions\":null}"; - } - } - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("SpellCheckByPage")] - public string SpellCheckByPage([FromBody] SpellCheckJsonData spellChecker) - { - try - { - SpellChecker spellCheck = new SpellChecker(); - spellCheck.CheckSpelling(spellChecker.LanguageID, spellChecker.TexttoCheck); - return Newtonsoft.Json.JsonConvert.SerializeObject(spellCheck); - } - catch - { - return "{\"SpellCollection\":[],\"HasSpellingError\":false,\"Suggestions\":null}"; - } - } - - public class SpellCheckJsonData - { - public int LanguageID { get; set; } - public string TexttoCheck { get; set; } - public bool CheckSpelling { get; set; } - public bool CheckSuggestion { get; set; } - public bool AddWord { get; set; } - - } - - public class CustomParameter - { - public string content { get; set; } - public string type { get; set; } - } - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("SystemClipboard")] - public string SystemClipboard([FromBody] CustomParameter param) - { - if (param.content != null && param.content != "") - { - try - { - WordDocument document = WordDocument.LoadString(param.content, GetFormatType(param.type.ToLower())); - string json = Newtonsoft.Json.JsonConvert.SerializeObject(document); - document.Dispose(); - return json; - } - catch (Exception) - { - return ""; - } - } - return ""; - } - - public class CustomRestrictParameter - { - public string passwordBase64 { get; set; } - public string saltBase64 { get; set; } - public int spinCount { get; set; } - } - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("RestrictEditing")] - public string[] RestrictEditing([FromBody] CustomRestrictParameter param) - { - if (param.passwordBase64 == "" && param.passwordBase64 == null) - return null; - return WordDocument.ComputeHash(param.passwordBase64, param.saltBase64, param.spinCount); - } - - internal static FormatType GetFormatType(string format) - { - if (string.IsNullOrEmpty(format)) - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - switch (format.ToLower()) - { - case ".dotx": - case ".docx": - case ".docm": - case ".dotm": - return FormatType.Docx; - case ".dot": - case ".doc": - return FormatType.Doc; - case ".rtf": - return FormatType.Rtf; - case ".txt": - return FormatType.Txt; - case ".xml": - return FormatType.WordML; - case ".html": - return FormatType.Html; - default: - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - } - } - internal static WFormatType GetWFormatType(string format) - { - if (string.IsNullOrEmpty(format)) - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - switch (format.ToLower()) - { - case ".dotx": - return WFormatType.Dotx; - case ".docx": - return WFormatType.Docx; - case ".docm": - return WFormatType.Docm; - case ".dotm": - return WFormatType.Dotm; - case ".dot": - return WFormatType.Dot; - case ".doc": - return WFormatType.Doc; - case ".rtf": - return WFormatType.Rtf; - case ".html": - return WFormatType.Html; - case ".txt": - return WFormatType.Txt; - case ".xml": - return WFormatType.WordML; - case ".odt": - return WFormatType.Odt; - default: - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - } - } - - } -} diff --git a/Server side with database/ASP.NET Core/Using MySql Server/Hubs/DocumentEditorHub.cs b/Server side with database/ASP.NET Core/Using MySql Server/Hubs/DocumentEditorHub.cs deleted file mode 100644 index ac53a66..0000000 --- a/Server side with database/ASP.NET Core/Using MySql Server/Hubs/DocumentEditorHub.cs +++ /dev/null @@ -1,75 +0,0 @@ -using Microsoft.AspNetCore.SignalR; -using Syncfusion.EJ2.DocumentEditor; -using WebApplication1.Controllers; - -namespace WebApplication1.Hubs -{ - public class DocumentEditorHub : Hub - { - - static Dictionary userManager = new Dictionary(); - internal static Dictionary> groupManager = new Dictionary>(); - - public async Task JoinGroup(ActionInfo info) - { - if (!userManager.ContainsKey(Context.ConnectionId)) - { - userManager.Add(Context.ConnectionId, info); - } - info.ConnectionId = Context.ConnectionId; - //Add to SignalR group - await Groups.AddToGroupAsync(Context.ConnectionId, info.RoomName); - if (groupManager.ContainsKey(info.RoomName)) - { - await Clients.Caller.SendAsync("dataReceived", "addUser", groupManager[info.RoomName]); - } - lock (groupManager) - { - if (groupManager.ContainsKey(info.RoomName)) - { - groupManager[info.RoomName].Add(info); - } - else - { - List actions = new List { info }; - groupManager.Add(info.RoomName, actions); - } - } - //Send information about new user joining to others - Clients.GroupExcept(info.RoomName, Context.ConnectionId).SendAsync("dataReceived", "addUser", info); - } - - public override Task OnConnectedAsync() - { - //Send connection id to client side - Clients.Caller.SendAsync("dataReceived", "connectionId", Context.ConnectionId); - return base.OnConnectedAsync(); - } - - public override System.Threading.Tasks.Task OnDisconnectedAsync(Exception? e) - { - string roomName = userManager[Context.ConnectionId].RoomName; - if (groupManager.ContainsKey(roomName)) - { - groupManager[roomName].Remove(userManager[Context.ConnectionId]); - - if (groupManager[roomName].Count == 0) - { - groupManager.Remove(roomName); - string userid = Context.GetHttpContext().Session.GetString("UserId"); - //Handle updating all editing operations for source document - CollaborativeEditingController.UpdateOperationsToSourceDocument(roomName, userid, false, 0); - } - } - - if (userManager.ContainsKey(Context.ConnectionId)) - { - //Send notification about user disconnection to other clients. - Clients.OthersInGroup(roomName).SendAsync("dataReceived", "removeUser", Context.ConnectionId); - Groups.RemoveFromGroupAsync(Context.ConnectionId, roomName); - userManager.Remove(Context.ConnectionId); - } - return base.OnDisconnectedAsync(e); - } - } -} diff --git a/Server side with database/ASP.NET Core/Using MySql Server/Program.cs b/Server side with database/ASP.NET Core/Using MySql Server/Program.cs deleted file mode 100644 index cb21e89..0000000 --- a/Server side with database/ASP.NET Core/Using MySql Server/Program.cs +++ /dev/null @@ -1,45 +0,0 @@ -using WebApplication1.Hubs; -using Microsoft.Azure.SignalR; - -var builder = WebApplication.CreateBuilder(args); - -builder.Services.AddControllersWithViews(); - -builder.Services.AddSignalR(); - -builder.Services.AddCors(options => -{ - options.AddPolicy("AllowAllOrigins", builder => - { - builder.AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader(); - }); -}); - -builder.Services.AddEndpointsApiExplorer(); - -var app = builder.Build(); - -// Configure the HTTP request pipeline. - -app.UseStaticFiles(); - -app.UseRouting(); - -app.UseCors(); - -app.MapHub("/documenteditorhub"); - -app.MapControllers(); - -app.UseAuthorization(); - -app.UseEndpoints(endpoints => -{ - endpoints.MapControllerRoute( - name: "default", - pattern: "{controller=Home}/{action=LogIn}/{userName?}/{id?}"); -}); - -app.Run(); diff --git a/Server side with database/ASP.NET Core/Using MySql Server/Properties/launchSettings.json b/Server side with database/ASP.NET Core/Using MySql Server/Properties/launchSettings.json deleted file mode 100644 index e4879bd..0000000 --- a/Server side with database/ASP.NET Core/Using MySql Server/Properties/launchSettings.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:38517", - "sslPort": 0 - } - }, - "profiles": { - "WebApplication1": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "applicationUrl": "http://localhost:5212", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/Server side with database/ASP.NET Core/Using MySql Server/Views/Home/Error.cshtml b/Server side with database/ASP.NET Core/Using MySql Server/Views/Home/Error.cshtml deleted file mode 100644 index f56cacb..0000000 --- a/Server side with database/ASP.NET Core/Using MySql Server/Views/Home/Error.cshtml +++ /dev/null @@ -1,7 +0,0 @@ -@* - For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 -*@ -@{ -} - -
@ViewBag.errorMessage
\ No newline at end of file diff --git a/Server side with database/ASP.NET Core/Using MySql Server/WebApplication1.csproj b/Server side with database/ASP.NET Core/Using MySql Server/WebApplication1.csproj deleted file mode 100644 index 3d20a6d..0000000 --- a/Server side with database/ASP.NET Core/Using MySql Server/WebApplication1.csproj +++ /dev/null @@ -1,29 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - diff --git a/Server side with database/ASP.NET Core/Using MySql Server/WebApplication1.sln b/Server side with database/ASP.NET Core/Using MySql Server/WebApplication1.sln deleted file mode 100644 index eff9773..0000000 --- a/Server side with database/ASP.NET Core/Using MySql Server/WebApplication1.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.4.33213.308 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApplication1", "WebApplication1.csproj", "{4356F1ED-F73A-44BC-8FA8-40B267A79C70}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - Release-Xml|Any CPU = Release-Xml|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release|Any CPU.Build.0 = Release|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release-Xml|Any CPU.ActiveCfg = Release|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release-Xml|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {56EAA24C-30CF-403F-9733-BDD27FB18338} - EndGlobalSection -EndGlobal diff --git a/Server side with database/ASP.NET Core/Using MySql Server/appsettings.Development.json b/Server side with database/ASP.NET Core/Using MySql Server/appsettings.Development.json deleted file mode 100644 index 0c208ae..0000000 --- a/Server side with database/ASP.NET Core/Using MySql Server/appsettings.Development.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/Server side with database/ASP.NET Core/Using MySql Server/appsettings.json b/Server side with database/ASP.NET Core/Using MySql Server/appsettings.json deleted file mode 100644 index 41513ad..0000000 --- a/Server side with database/ASP.NET Core/Using MySql Server/appsettings.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*", - "ConnectionStrings": { - "DocumentEditorDatabase": "<>" - - } -} \ No newline at end of file diff --git a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Character Formatting.docx b/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Character Formatting.docx deleted file mode 100644 index 5371ccc..0000000 Binary files a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Character Formatting.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Footnotes and Endnotes.docx b/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Footnotes and Endnotes.docx deleted file mode 100644 index da9c89e..0000000 Binary files a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Footnotes and Endnotes.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Getting Started.docx b/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Getting Started.docx deleted file mode 100644 index 4b7ea44..0000000 Binary files a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Getting Started.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Giant Panda.docx b/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Giant Panda.docx deleted file mode 100644 index f89bb27..0000000 Binary files a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Giant Panda.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Paragraph Formatting.docx b/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Paragraph Formatting.docx deleted file mode 100644 index 3f324d3..0000000 Binary files a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Paragraph Formatting.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Styles.docx b/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Styles.docx deleted file mode 100644 index 5668463..0000000 Binary files a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Styles.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Table Formatting.docx b/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Table Formatting.docx deleted file mode 100644 index e620881..0000000 Binary files a/Server side with database/ASP.NET Core/Using MySql Server/wwwroot/Table Formatting.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/Controllers/CollaborativeEditingController.cs b/Server side with database/ASP.NET Core/Using PostgreSQL/Controllers/CollaborativeEditingController.cs deleted file mode 100644 index 7dc1f3b..0000000 --- a/Server side with database/ASP.NET Core/Using PostgreSQL/Controllers/CollaborativeEditingController.cs +++ /dev/null @@ -1,483 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Syncfusion.EJ2.DocumentEditor; -using Microsoft.AspNetCore.Cors; -using Microsoft.AspNetCore.SignalR; -using WebApplication1.Hubs; -using System.Data; -using Microsoft.CodeAnalysis; -using Npgsql; - -namespace WebApplication1.Controllers -{ - [Route("api/[controller]")] - [ApiController] - public class CollaborativeEditingController : ControllerBase - { - private readonly IWebHostEnvironment _hostingEnvironment; - private readonly IHubContext _hubContext; - private static string connectionString; - private static string fileLocation; - private static byte saveThreshold = 200; - - public CollaborativeEditingController(IWebHostEnvironment hostingEnvironment, IHubContext hubContext, IConfiguration config) - { - _hostingEnvironment = hostingEnvironment; - _hubContext = hubContext; - //Database connection string - connectionString = config.GetConnectionString("DocumentEditorDatabase"); - fileLocation = _hostingEnvironment.WebRootPath; - } - - //Import document from wwwroot folder in web server. - [HttpPost] - [Route("ImportFile")] - [EnableCors("AllowAllOrigins")] - public string ImportFile([FromBody] FileInfo param) - { - DocumentContent content = new DocumentContent(); - WordDocument document = GetSourceDocument(param.fileName); - int lastSyncedVersion = 0; - List actions = CreatedTable(param.roomName, out lastSyncedVersion); - if (actions != null) - { - //Updated pending edit from database to source document. - document.UpdateActions(actions); - } - string json = Newtonsoft.Json.JsonConvert.SerializeObject(document); - content.version = lastSyncedVersion; - content.sfdt = json; - return Newtonsoft.Json.JsonConvert.SerializeObject(content); - } - - [HttpPost] - [Route("UpdateAction")] - [EnableCors("AllowAllOrigins")] - public async Task UpdateAction([FromBody] ActionInfo param) - { - try - { - ActionInfo modifiedAction = AddOperationsToTable(param); - await _hubContext.Clients.Group(param.RoomName).SendAsync("dataReceived", "action", modifiedAction); - return modifiedAction; - } - catch - { - return null; - } - } - - [HttpPost] - [Route("GetActionsFromServer")] - [EnableCors("AllowAllOrigins")] - public string GetActionsFromServer([FromBody] ActionInfo param) - { - string tableName = param.RoomName; - string getOperation = "SELECT * FROM \"" + tableName + "\" WHERE version > " + param.Version; - using (NpgsqlConnection connection = new NpgsqlConnection(connectionString)) - { - try - { - NpgsqlCommand command2 = new NpgsqlCommand(getOperation, connection); - NpgsqlCommand updateCommand = new NpgsqlCommand(getOperation, connection); - connection.Open(); - NpgsqlDataReader reader = updateCommand.ExecuteReader(); - DataTable table = new DataTable(); - table.Load(reader); - DataTable oldTable = table; - if (table.Rows.Count > 0) - { - int startVersion = int.Parse(table.Rows[0]["version"].ToString()); - int lowestVersion = GetLowestClientVersion(table); - if (startVersion > lowestVersion) - { - string updatedOperation = "SELECT * FROM \"" + tableName + "\" WHERE version >= " + lowestVersion; - NpgsqlCommand command = new NpgsqlCommand(updatedOperation, connection); - NpgsqlDataReader reader2 = command.ExecuteReader(); - table = new DataTable(); - table.Load(reader2); - } - List actions = GetOperationsQueue(table); - foreach (ActionInfo info in actions) - { - if (!info.IsTransformed) - { - CollaborativeEditingHandler.TransformOperation(info, actions); - } - } - actions = actions.Where(x => x.Version > param.Version).ToList(); - return Newtonsoft.Json.JsonConvert.SerializeObject(actions); - } - } - catch - { - return "{}"; - } - } - return "{}"; - } - - private static WordDocument GetSourceDocument(string fileName) - { - string path = fileLocation + "\\" + fileName; - int index = fileName.LastIndexOf('.'); - string type = index > -1 && index < fileName.Length - 1 ? - fileName.Substring(index) : ".docx"; - Stream stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); - WordDocument document = Syncfusion.EJ2.DocumentEditor.WordDocument.Load(stream, GetFormatType(type)); - stream.Dispose(); - return document; - } - - private List CreatedTable(string roomName, out int lastSyncedVersion) - { - lastSyncedVersion = 0; - string tableName = roomName; - if (!TableExists(tableName)) - { - - string queryString = "CREATE TABLE \"" + roomName - + "\" (version SERIAL PRIMARY KEY, operation TEXT, clientVersion INTEGER)"; - using (NpgsqlConnection connection = new NpgsqlConnection(connectionString)) - { - NpgsqlCommand command = new NpgsqlCommand(queryString, connection); - connection.Open(); - command.ExecuteNonQuery(); - // Create table to track the last saved version. - CreateRecordForVersionInfo(connection, roomName); - } - } - else - { - - using (NpgsqlConnection connection = new NpgsqlConnection(connectionString)) - { - - connection.Open(); - string queryString = "SELECT * FROM \"" + tableName + "\" WHERE version > " + lastSyncedVersion; - NpgsqlCommand command = new NpgsqlCommand(queryString, connection); - connection.Open(); - NpgsqlDataReader reader = command.ExecuteReader(); - DataTable table = new DataTable(); - table.Load(reader); - List actions = GetOperationsQueue(table); - return actions; - - } - } - return null; - } - private void CreateRecordForVersionInfo(NpgsqlConnection connection, String roomName) - { - string tableName = "de_version_info"; - - // Check if table exists - if (!TableExists(tableName)) - { - // If table doesn't exist, create it - string createTableQuery = $"CREATE TABLE \"" + tableName + "\" (roomName TEXT, lastSavedVersion INTEGER)"; ; - using (NpgsqlCommand createTableCommand = new NpgsqlCommand(createTableQuery, connection)) - { - createTableCommand.ExecuteNonQuery(); - } - } - - // Insert record into the table - string insertQuery = $"INSERT INTO \"" + tableName + "\" (roomName, lastSavedVersion) VALUES (?, ?)"; - using (NpgsqlCommand insertCommand = new NpgsqlCommand(insertQuery, connection)) - { - insertCommand.Parameters.AddWithValue("@roomName", roomName); - // Set initial version to 0 - insertCommand.Parameters.AddWithValue("@lastSavedVersion", 0); - insertCommand.ExecuteNonQuery(); - } - //} - - } - private bool TableExists(string roomName) - { - using (var connection = new NpgsqlConnection(connectionString)) - { - NpgsqlCommand command = new NpgsqlCommand($"SELECT CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = '" - + roomName + "') THEN 1 ELSE 0 END;", connection); - connection.Open(); - var result = (int)command.ExecuteScalar(); - return result == 1; - } - } - - private ActionInfo AddOperationsToTable(ActionInfo action) - { - int clientVersion = action.Version; - string tableName = action.RoomName; - string value = Newtonsoft.Json.JsonConvert.SerializeObject(action); - string query = $"INSERT INTO \"{tableName}\" (operation, clientVersion) VALUES (@Operation, @ClientVersion) RETURNING version AS last_id;"; - - using (NpgsqlConnection connection = new NpgsqlConnection(connectionString)) - { - - NpgsqlCommand command = new NpgsqlCommand(query, connection); - command.Parameters.AddWithValue("@Operation", value); - command.Parameters.AddWithValue("@ClientVersion", action.Version); - - connection.Open(); - int updateVersion = (int)command.ExecuteScalar(); - if (updateVersion - clientVersion == 1) - { - action.Version = updateVersion; - UpdateCurrentActionToDB(tableName, action, connection); - } - else - { - DataTable table = GetOperationsToTransform(tableName, clientVersion + 1, updateVersion, connection); - int startVersion = int.Parse(table.Rows[0]["version"].ToString()); - int lowestVersion = GetLowestClientVersion(table); - if (startVersion > lowestVersion) - { - table = GetOperationsToTransform(tableName, lowestVersion, updateVersion, connection); - } - List actions = GetOperationsQueue(table); - foreach (ActionInfo info in actions) - { - if (!info.IsTransformed) - { - CollaborativeEditingHandler.TransformOperation(info, actions); - } - } - action = actions[actions.Count - 1]; - action.Version = updateVersion; - UpdateCurrentActionToDB(tableName, actions[actions.Count - 1], connection); - } - if (updateVersion % saveThreshold == 0) - { - UpdateOperationsToSourceDocument(tableName, HttpContext.Session.GetString("UserId"), true, updateVersion); - } - - - } - return action; - } - - private void UpdateCurrentActionToDB(string tableName, ActionInfo action, NpgsqlConnection connection) - { - action.IsTransformed = true; - string updateQuery = "UPDATE \"" + tableName + "\" SET operation = ? WHERE version = " + action.Version.ToString(); - NpgsqlCommand updateCommand = new NpgsqlCommand(updateQuery, connection); - updateCommand.Parameters.AddWithValue("@Operation", Newtonsoft.Json.JsonConvert.SerializeObject(action)); - updateCommand.ExecuteNonQuery(); - } - - private static DataTable GetOperationsToTransform(string tableName, int clientVersion, int currentVersion, NpgsqlConnection connection) - { - string getOperation = "SELECT * FROM \"" + tableName + "\" WHERE version BETWEEN " + clientVersion + " AND " + currentVersion.ToString(); - NpgsqlCommand command = new NpgsqlCommand(getOperation, connection); - NpgsqlDataReader reader = command.ExecuteReader(); - DataTable table = new DataTable(); - table.Load(reader); - return table; - } - - private static List GetOperationsQueue(DataTable table) - { - List actions = new List(); - foreach (DataRow row in table.Rows) - { - ActionInfo action = Newtonsoft.Json.JsonConvert.DeserializeObject(row["operation"].ToString()); - action.Version = int.Parse(row["version"].ToString()); - action.ClientVersion = int.Parse(row["clientVersion"].ToString()); - actions.Add(action); - } - return actions; - } - - private static int GetLowestClientVersion(DataTable table) - { - int clientVersion = int.Parse(table.Rows[0]["clientVersion"].ToString()); - foreach (DataRow row in table.Rows) - { - //TODO: Need to optimise version calculation for only untransformed operations - int version = int.Parse(row["clientVersion"].ToString()); - if (version < clientVersion) - { - clientVersion = version; - } - } - return clientVersion; - } - - internal static FormatType GetFormatType(string format) - { - if (string.IsNullOrEmpty(format)) - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - switch (format.ToLower()) - { - case ".dotx": - case ".docx": - case ".docm": - case ".dotm": - return FormatType.Docx; - case ".dot": - case ".doc": - return FormatType.Doc; - case ".rtf": - return FormatType.Rtf; - case ".txt": - return FormatType.Txt; - case ".xml": - return FormatType.WordML; - case ".html": - return FormatType.Html; - default: - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - } - } - - /// - /// Update editing operation to source document. - /// - public static void UpdateOperationsToSourceDocument(string fileName, string userId, bool partialSave, int endVersion) - { - try - { - NpgsqlConnection connection = new NpgsqlConnection(connectionString); - connection.Open(); - string tableName = fileName; - int lastSyncedVersion = GetLastedSyncedVersion(connection, fileName); - string getOperation = ""; - if (partialSave) - { - getOperation = "SELECT * FROM \"" + tableName + "\" WHERE version BETWEEN " + (lastSyncedVersion + 1).ToString() + " AND " + endVersion.ToString(); - } - else - { - getOperation = "SELECT * FROM \"" + tableName + "\" WHERE version > " + lastSyncedVersion; - } - NpgsqlCommand command = new NpgsqlCommand(getOperation, connection); - NpgsqlDataReader reader = command.ExecuteReader(); - DataTable table = new DataTable(); - table.Load(reader); - if (table.Rows.Count > 0) - { - List actions = GetOperationsQueue(table); - foreach (ActionInfo info in actions) - { - if (!info.IsTransformed) - { - CollaborativeEditingHandler.TransformOperation(info, actions); - } - } - var currentDirectory = System.IO.Directory.GetCurrentDirectory(); - int index = fileName.LastIndexOf('.'); - string type = index > -1 && index < fileName.Length - 1 ? - fileName.Substring(index) : ".docx"; - Stream stream1 = System.IO.File.Open(currentDirectory + "\\" + fileName, FileMode.Open, FileAccess.ReadWrite); - Syncfusion.EJ2.DocumentEditor.WordDocument document = Syncfusion.EJ2.DocumentEditor.WordDocument.Load(stream1, GetFormatType(type)); - stream1.Close(); - CollaborativeEditingHandler handler = new CollaborativeEditingHandler(document); - for (int i = 0; i < actions.Count; i++) - { - //Console.WriteLine(i); - handler.UpdateAction(actions[i]); - } - MemoryStream stream = new MemoryStream(); - Syncfusion.DocIO.DLS.WordDocument doc = WordDocument.Save(Newtonsoft.Json.JsonConvert.SerializeObject(handler.Document)); - doc.Save(stream, Syncfusion.DocIO.FormatType.Docx); - stream.Position = 0; - byte[] data = stream.ToArray(); - System.IO.File.WriteAllBytes(currentDirectory + "\\output.docx", data); - stream.Close(); - if (!partialSave) - { - endVersion = actions[actions.Count - 1].Version; - } - doc.Close(); - } - if (!partialSave) - { - DeleteLastModifiedVersion(tableName, connection); - DropTable(fileName, connection); - - } - else - { - UpdateModifiedVersion(tableName, connection, endVersion); - - } - - } - catch (Exception ex) - { - - } - - } - static void UpdateModifiedVersion(string roomName, NpgsqlConnection connection, int lastSavedVersion) - { - string tableName = "de_version_info"; - string query = "UPDATE \"" + tableName + "\" SET lastSavedVersion = ? where roomName= '" + roomName + "'"; - - using (NpgsqlCommand command = new NpgsqlCommand(query, connection)) - { - command.Parameters.AddWithValue("@lastSavedVersion", lastSavedVersion); - command.Parameters.AddWithValue("@roomName", roomName); - command.ExecuteNonQuery(); - } - } - static void DeleteLastModifiedVersion(string roomName, NpgsqlConnection connection) - { - string tableName = "de_version_info"; - string query = "DELETE FROM \"" + tableName + "\" WHERE roomName= '" + roomName + "'"; - - using (NpgsqlCommand command = new NpgsqlCommand(query, connection)) - { - command.Parameters.AddWithValue("@roomName", roomName); - command.ExecuteNonQuery(); - } - } - private static int GetLastedSyncedVersion(NpgsqlConnection connection, string roomName) - { - string tableName = "de_version_info"; - string query = "SELECT lastSavedVersion FROM \"" + tableName + "\" WHERE roomName ='" + roomName + "'"; - var command = new NpgsqlCommand(query, connection); - command.Parameters.AddWithValue("@Operation", roomName); - return int.Parse(command.ExecuteScalar().ToString()); - } - private static void DropTable(string documentId, NpgsqlConnection connection) - { - try - { - //Delete operations record. - string sqlQuery = "drop table \"" + documentId + "\""; - var sqlCommand = new NpgsqlCommand(sqlQuery, connection); - sqlCommand.ExecuteNonQuery(); - } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - } - - } - - - public class FileInfo - { - public string fileName - { - get; - set; - } - public string roomName - { - get; - set; - } - - } - - public class DocumentContent - { - public int version { get; set; } - - public string sfdt { get; set; } - } -} diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/Controllers/DocumentEditorController.cs b/Server side with database/ASP.NET Core/Using PostgreSQL/Controllers/DocumentEditorController.cs deleted file mode 100644 index 810f729..0000000 --- a/Server side with database/ASP.NET Core/Using PostgreSQL/Controllers/DocumentEditorController.cs +++ /dev/null @@ -1,197 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Syncfusion.EJ2.DocumentEditor; -using WFormatType = Syncfusion.DocIO.FormatType; -using Syncfusion.EJ2.SpellChecker; -using Microsoft.AspNetCore.Cors; - -namespace WebApplication1.Controllers -{ - [Route("api/[controller]")] - [ApiController] - public class DocumentEditorController : ControllerBase - { - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("Import")] - public string Import(IFormCollection data) - { - if (data.Files.Count == 0) - return null; - Stream stream1 = new MemoryStream(); - IFormFile file = data.Files[0]; - int index = file.FileName.LastIndexOf('.'); - string type = index > -1 && index < file.FileName.Length - 1 ? - file.FileName.Substring(index) : ".docx"; - file.CopyTo(stream1); - stream1.Position = 0; - - WordDocument document = WordDocument.Load(stream1, GetFormatType(type.ToLower())); - string json = Newtonsoft.Json.JsonConvert.SerializeObject(document); - document.Dispose(); - return json; - } - - public class CustomParams - { - public string fileName - { - get; - set; - } - } - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("SpellCheck")] - public string SpellCheck([FromBody] SpellCheckJsonData spellChecker) - { - try - { - SpellChecker spellCheck = new SpellChecker(); - spellCheck.GetSuggestions(spellChecker.LanguageID, spellChecker.TexttoCheck, spellChecker.CheckSpelling, spellChecker.CheckSuggestion, spellChecker.AddWord); - return Newtonsoft.Json.JsonConvert.SerializeObject(spellCheck); - } - catch - { - return "{\"SpellCollection\":[],\"HasSpellingError\":false,\"Suggestions\":null}"; - } - } - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("SpellCheckByPage")] - public string SpellCheckByPage([FromBody] SpellCheckJsonData spellChecker) - { - try - { - SpellChecker spellCheck = new SpellChecker(); - spellCheck.CheckSpelling(spellChecker.LanguageID, spellChecker.TexttoCheck); - return Newtonsoft.Json.JsonConvert.SerializeObject(spellCheck); - } - catch - { - return "{\"SpellCollection\":[],\"HasSpellingError\":false,\"Suggestions\":null}"; - } - } - - public class SpellCheckJsonData - { - public int LanguageID { get; set; } - public string TexttoCheck { get; set; } - public bool CheckSpelling { get; set; } - public bool CheckSuggestion { get; set; } - public bool AddWord { get; set; } - - } - - public class CustomParameter - { - public string content { get; set; } - public string type { get; set; } - } - - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("SystemClipboard")] - public string SystemClipboard([FromBody] CustomParameter param) - { - if (param.content != null && param.content != "") - { - try - { - WordDocument document = WordDocument.LoadString(param.content, GetFormatType(param.type.ToLower())); - string json = Newtonsoft.Json.JsonConvert.SerializeObject(document); - document.Dispose(); - return json; - } - catch (Exception) - { - return ""; - } - } - return ""; - } - - public class CustomRestrictParameter - { - public string passwordBase64 { get; set; } - public string saltBase64 { get; set; } - public int spinCount { get; set; } - } - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("RestrictEditing")] - public string[] RestrictEditing([FromBody] CustomRestrictParameter param) - { - if (param.passwordBase64 == "" && param.passwordBase64 == null) - return null; - return WordDocument.ComputeHash(param.passwordBase64, param.saltBase64, param.spinCount); - } - - internal static FormatType GetFormatType(string format) - { - if (string.IsNullOrEmpty(format)) - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - switch (format.ToLower()) - { - case ".dotx": - case ".docx": - case ".docm": - case ".dotm": - return FormatType.Docx; - case ".dot": - case ".doc": - return FormatType.Doc; - case ".rtf": - return FormatType.Rtf; - case ".txt": - return FormatType.Txt; - case ".xml": - return FormatType.WordML; - case ".html": - return FormatType.Html; - default: - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - } - } - internal static WFormatType GetWFormatType(string format) - { - if (string.IsNullOrEmpty(format)) - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - switch (format.ToLower()) - { - case ".dotx": - return WFormatType.Dotx; - case ".docx": - return WFormatType.Docx; - case ".docm": - return WFormatType.Docm; - case ".dotm": - return WFormatType.Dotm; - case ".dot": - return WFormatType.Dot; - case ".doc": - return WFormatType.Doc; - case ".rtf": - return WFormatType.Rtf; - case ".html": - return WFormatType.Html; - case ".txt": - return WFormatType.Txt; - case ".xml": - return WFormatType.WordML; - case ".odt": - return WFormatType.Odt; - default: - throw new NotSupportedException("EJ2 DocumentEditor does not support this file format."); - } - } - - } -} diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/Hubs/DocumentEditorHub.cs b/Server side with database/ASP.NET Core/Using PostgreSQL/Hubs/DocumentEditorHub.cs deleted file mode 100644 index 5ea31cc..0000000 --- a/Server side with database/ASP.NET Core/Using PostgreSQL/Hubs/DocumentEditorHub.cs +++ /dev/null @@ -1,73 +0,0 @@ -using Microsoft.AspNetCore.SignalR; -using Syncfusion.EJ2.DocumentEditor; - -namespace WebApplication1.Hubs -{ - public class DocumentEditorHub : Hub - { - - static Dictionary userManager = new Dictionary(); - internal static Dictionary> groupManager = new Dictionary>(); - - public async Task JoinGroup(ActionInfo info) - { - if (!userManager.ContainsKey(Context.ConnectionId)) - { - userManager.Add(Context.ConnectionId, info); - } - info.ConnectionId = Context.ConnectionId; - //Add to SignalR group - await Groups.AddToGroupAsync(Context.ConnectionId, info.RoomName); - if (groupManager.ContainsKey(info.RoomName)) - { - await Clients.Caller.SendAsync("dataReceived", "addUser", groupManager[info.RoomName]); - } - lock (groupManager) - { - if (groupManager.ContainsKey(info.RoomName)) - { - groupManager[info.RoomName].Add(info); - } - else - { - List actions = new List { info }; - groupManager.Add(info.RoomName, actions); - } - } - //Send information about new user joining to others - Clients.GroupExcept(info.RoomName, Context.ConnectionId).SendAsync("dataReceived", "addUser", info); - } - - public override Task OnConnectedAsync() - { - //Send connection id to client side - Clients.Caller.SendAsync("dataReceived", "connectionId", Context.ConnectionId); - return base.OnConnectedAsync(); - } - - public override System.Threading.Tasks.Task OnDisconnectedAsync(Exception? e) - { - string roomName = userManager[Context.ConnectionId].RoomName; - if (groupManager.ContainsKey(roomName)) - { - groupManager[roomName].Remove(userManager[Context.ConnectionId]); - - if (groupManager[roomName].Count == 0) - { - groupManager.Remove(roomName); - //Handle updating all editing operations for source document - //CollaborativeEditingController.UpdateOperationsToSourceDocument(roomName, ""); - } - } - - if (userManager.ContainsKey(Context.ConnectionId)) - { - //Send notification about user disconnection to other clients. - Clients.OthersInGroup(roomName).SendAsync("dataReceived", "removeUser", Context.ConnectionId); - Groups.RemoveFromGroupAsync(Context.ConnectionId, roomName); - userManager.Remove(Context.ConnectionId); - } - return base.OnDisconnectedAsync(e); - } - } -} diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/Program.cs b/Server side with database/ASP.NET Core/Using PostgreSQL/Program.cs deleted file mode 100644 index cb21e89..0000000 --- a/Server side with database/ASP.NET Core/Using PostgreSQL/Program.cs +++ /dev/null @@ -1,45 +0,0 @@ -using WebApplication1.Hubs; -using Microsoft.Azure.SignalR; - -var builder = WebApplication.CreateBuilder(args); - -builder.Services.AddControllersWithViews(); - -builder.Services.AddSignalR(); - -builder.Services.AddCors(options => -{ - options.AddPolicy("AllowAllOrigins", builder => - { - builder.AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader(); - }); -}); - -builder.Services.AddEndpointsApiExplorer(); - -var app = builder.Build(); - -// Configure the HTTP request pipeline. - -app.UseStaticFiles(); - -app.UseRouting(); - -app.UseCors(); - -app.MapHub("/documenteditorhub"); - -app.MapControllers(); - -app.UseAuthorization(); - -app.UseEndpoints(endpoints => -{ - endpoints.MapControllerRoute( - name: "default", - pattern: "{controller=Home}/{action=LogIn}/{userName?}/{id?}"); -}); - -app.Run(); diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/Properties/launchSettings.json b/Server side with database/ASP.NET Core/Using PostgreSQL/Properties/launchSettings.json deleted file mode 100644 index e4879bd..0000000 --- a/Server side with database/ASP.NET Core/Using PostgreSQL/Properties/launchSettings.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:38517", - "sslPort": 0 - } - }, - "profiles": { - "WebApplication1": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "applicationUrl": "http://localhost:5212", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/Views/Home/Error.cshtml b/Server side with database/ASP.NET Core/Using PostgreSQL/Views/Home/Error.cshtml deleted file mode 100644 index f56cacb..0000000 --- a/Server side with database/ASP.NET Core/Using PostgreSQL/Views/Home/Error.cshtml +++ /dev/null @@ -1,7 +0,0 @@ -@* - For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 -*@ -@{ -} - -
@ViewBag.errorMessage
\ No newline at end of file diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/WebApplication1.csproj b/Server side with database/ASP.NET Core/Using PostgreSQL/WebApplication1.csproj deleted file mode 100644 index 196dcd7..0000000 --- a/Server side with database/ASP.NET Core/Using PostgreSQL/WebApplication1.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/WebApplication1.sln b/Server side with database/ASP.NET Core/Using PostgreSQL/WebApplication1.sln deleted file mode 100644 index eff9773..0000000 --- a/Server side with database/ASP.NET Core/Using PostgreSQL/WebApplication1.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.4.33213.308 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApplication1", "WebApplication1.csproj", "{4356F1ED-F73A-44BC-8FA8-40B267A79C70}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - Release-Xml|Any CPU = Release-Xml|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release|Any CPU.Build.0 = Release|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release-Xml|Any CPU.ActiveCfg = Release|Any CPU - {4356F1ED-F73A-44BC-8FA8-40B267A79C70}.Release-Xml|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {56EAA24C-30CF-403F-9733-BDD27FB18338} - EndGlobalSection -EndGlobal diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/appsettings.Development.json b/Server side with database/ASP.NET Core/Using PostgreSQL/appsettings.Development.json deleted file mode 100644 index 0c208ae..0000000 --- a/Server side with database/ASP.NET Core/Using PostgreSQL/appsettings.Development.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/appsettings.json b/Server side with database/ASP.NET Core/Using PostgreSQL/appsettings.json deleted file mode 100644 index 77d8f46..0000000 --- a/Server side with database/ASP.NET Core/Using PostgreSQL/appsettings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*", - "ConnectionStrings": { - "DocumentEditorDatabase": "<>" - } -} \ No newline at end of file diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Character Formatting.docx b/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Character Formatting.docx deleted file mode 100644 index 5371ccc..0000000 Binary files a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Character Formatting.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Footnotes and Endnotes.docx b/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Footnotes and Endnotes.docx deleted file mode 100644 index da9c89e..0000000 Binary files a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Footnotes and Endnotes.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Getting Started.docx b/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Getting Started.docx deleted file mode 100644 index 4b7ea44..0000000 Binary files a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Getting Started.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Giant Panda.docx b/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Giant Panda.docx deleted file mode 100644 index f89bb27..0000000 Binary files a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Giant Panda.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Paragraph Formatting.docx b/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Paragraph Formatting.docx deleted file mode 100644 index 3f324d3..0000000 Binary files a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Paragraph Formatting.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Styles.docx b/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Styles.docx deleted file mode 100644 index 5668463..0000000 Binary files a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Styles.docx and /dev/null differ diff --git a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Table Formatting.docx b/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Table Formatting.docx deleted file mode 100644 index e620881..0000000 Binary files a/Server side with database/ASP.NET Core/Using PostgreSQL/wwwroot/Table Formatting.docx and /dev/null differ diff --git a/Server side with database/Java/Java web service using PostgreSQL/.github/workflows/gitleaks.yaml b/Server side with database/Java/Java web service using PostgreSQL/.github/workflows/gitleaks.yaml deleted file mode 100644 index df4c088..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/.github/workflows/gitleaks.yaml +++ /dev/null @@ -1,38 +0,0 @@ -name: Secret Value found!! -on: - push: - public: -jobs: - scan: - name: gitleaks - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Install the gitleaks - run: wget https://github.com/zricethezav/gitleaks/releases/download/v8.15.2/gitleaks_8.15.2_linux_x64.tar.gz - shell: pwsh - - name: Extract the tar file - run: tar xzvf gitleaks_8.15.2_linux_x64.tar.gz - - name: Generate the report - id: gitleaks - run: $GITHUB_WORKSPACE/gitleaks detect -s $GITHUB_WORKSPACE -f json -r $GITHUB_WORKSPACE/leaksreport.json - shell: bash - continue-on-error: true - - name: Setup NuGet.exe - if: steps.gitleaks.outcome != 'success' - uses: nuget/setup-nuget@v1 - with: - nuget-version: latest - - name: Install the dotnet - if: steps.gitleaks.outcome != 'success' - uses: actions/setup-dotnet@v3 - with: - dotnet-version: '3.1.x' - - name: Install the report tool packages - if: steps.gitleaks.outcome != 'success' - run: | - nuget install "Syncfusion.Email" -source ${{ secrets.NexusFeedLink }} -ExcludeVersion - dir $GITHUB_WORKSPACE/Syncfusion.Email/lib/netcoreapp3.1 - dotnet $GITHUB_WORKSPACE/Syncfusion.Email/lib/netcoreapp3.1/GitleaksReportMail.dll ${{ secrets.CITEAMCREDENTIALS }} "$GITHUB_REF_NAME" ${{ secrets.NETWORKCREDENTIALS }} ${{ secrets.NETWORKKEY }} "$GITHUB_WORKSPACE" ${{ secrets.ORGANIZATIONNAME }} - exit 1 \ No newline at end of file diff --git a/Server side with database/Java/Java web service using PostgreSQL/.gitignore b/Server side with database/Java/Java web service using PostgreSQL/.gitignore deleted file mode 100644 index 549e00a..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -HELP.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ - -### VS Code ### -.vscode/ diff --git a/Server side with database/Java/Java web service using PostgreSQL/ReadMe.md b/Server side with database/Java/Java web service using PostgreSQL/ReadMe.md deleted file mode 100644 index 2ae0e98..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/ReadMe.md +++ /dev/null @@ -1,38 +0,0 @@ -# How to host the DocumentEditor service. - -Opening and saving documents from S3 bucket using PostgreSQL. - -## Maven Project - -Please find the list of commands used for running and deploying the spring boot application in Azure. - -Clean the package using - -> mvn clean package - -Run the application locally using - -> mvn spring-boot:run - -Build the package using - -> mvn package - -Above package generation command creates the "tomcat-0.0.1-SNAPSHOT.war" in the below location. - -> target\tomcat-0.0.1-SNAPSHOT.war - -Please create a Azure app service with Java & Tomcat. - -After creating the app service - ->Development Tools -> Advanced Tools -> Go -> Debug console -> CMD - -Once the file manager is opened please navigate to - ->site -> wwwroot -> webapps - -Upload the generated war file "tomcat-0.0.1-SNAPSHOT.war" the application will be hosted under - ->{site-name}/tomcat-0.0.1-SNAPSHOT - diff --git a/Server side with database/Java/Java web service using PostgreSQL/mvnw b/Server side with database/Java/Java web service using PostgreSQL/mvnw deleted file mode 100644 index a16b543..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/mvnw +++ /dev/null @@ -1,310 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/Server side with database/Java/Java web service using PostgreSQL/mvnw.cmd b/Server side with database/Java/Java web service using PostgreSQL/mvnw.cmd deleted file mode 100644 index c8d4337..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM https://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/Server side with database/Java/Java web service using PostgreSQL/pom.xml b/Server side with database/Java/Java web service using PostgreSQL/pom.xml deleted file mode 100644 index d9a6350..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/pom.xml +++ /dev/null @@ -1,195 +0,0 @@ - - - 4.0.0 - com.syncfusion - tomcat - 0.0.1-SNAPSHOT - war - tomcat - Demo project for Spring Boot - - - Syncfusion-Java - Syncfusion Java repo - https://jars.syncfusion.com/repository/maven-public/ - - - - org.springframework.boot - spring-boot-starter-parent - 2.3.4.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - com.syncfusion.tomcat.TomcatApplication - - - - com.syncfusion - syncfusion-javahelper - 25.1.37 - - - com.syncfusion - syncfusion-docio - 25.1.37 - - - com.syncfusion - syncfusion-ej2-spellchecker - 25.1.37 - - - - com.microsoft.sqlserver - mssql-jdbc - 12.4.2.jre8 - - - - software.amazon.awssdk - s3 - 2.24.9 - - - com.syncfusion - syncfusion-ej2-wordprocessor - 25.1.37 - - - redis.clients - jedis - 3.7.0 - - - org.springframework - spring-messaging - - - org.springframework - spring-websocket - - - com.google.code.gson - gson - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-security - - - org.postgresql - postgresql - runtime - - - org.springframework.boot - spring-boot-starter-jdbc - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-dependency-plugin - 2.8 - - - - copy-dependencies - compile - - copy-dependencies - - - ${project.build.directory}/${project.build.finalName}/WEB-INF/lib - system - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-dependency-plugin - - - [2.8,) - - - - copy-dependencies - - - - - - - - - - - - - - - - - diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/CollaborativeEditingController.java b/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/CollaborativeEditingController.java deleted file mode 100644 index f5688bf..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/CollaborativeEditingController.java +++ /dev/null @@ -1,475 +0,0 @@ -package com.syncfusion.tomcat; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.messaging.MessageHeaders; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.syncfusion.docio.WordDocument; -import com.syncfusion.ej2.wordprocessor.ActionInfo; -import com.syncfusion.ej2.wordprocessor.CollaborativeEditingHandler; -import com.syncfusion.ej2.wordprocessor.WordProcessorHelper; -import com.syncfusion.javahelper.system.OutSupport; -import com.syncfusion.tomcat.controller.DocumentEditorHub; - -import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; -import software.amazon.awssdk.auth.credentials.AwsCredentials; -import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; -import software.amazon.awssdk.core.ResponseInputStream; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.GetObjectRequest; -import software.amazon.awssdk.services.s3.model.GetObjectResponse; -import software.amazon.awssdk.services.s3.model.PutObjectRequest; - -@RestController -public class CollaborativeEditingController { - private static short saveThreshold = 200; - // SQL - @Value("${spring.datasource.url}") - public String datasourceUrl; - @Value("${spring.datasource.username}") - private String datasourceUsername; - @Value("${spring.datasource.password}") - private String datasourcePassword; - - // Bucket S3 - @Value("${spring.datasource.accesskey}") - private String datasourceAccessKey; - @Value("${spring.datasource.secretkey}") - private String datasourceSecretKey; - @Value("${spring.datasource.bucketname}") - private String datasourceBucketName; - @Value("${spring.datasource.regionname}") - private String datasourceRegionName; - - @Autowired - private DataSource dataSource; - - @CrossOrigin(origins = "*", allowedHeaders = "*") - @PostMapping("/api/collaborativeediting/ImportFile") - public String ImportFile(@RequestBody FilesPathInfo file) throws Exception { - try { - DocumentContent content = new DocumentContent(); - - // Load the document from S3 bucket. - WordProcessorHelper document = getDocumentFromBucketS3(file.getFileName(), datasourceAccessKey, - datasourceSecretKey, datasourceBucketName); - - int lastSyncedVersion = 0; - OutSupport lastSyncedVersion_out = new OutSupport(Integer.class); - // Create table in database to store temporary data for the collaborative - // editing session. - // Room name is a unique identifier of the document for collaborative editing. - // We need to maintain the unique ID to map it with the original document to - // save it in the S3. - - ArrayList actions = createRecordForCollaborativeEditing(file.getRoomName(), - lastSyncedVersion_out); - - if (actions != null && actions.size() > 0) { - // When new user join the collaborative editing session - // Get previous editing operation from DB and update it in document editor. - document.updateActions(actions); - ActionInfo lastAction = actions.get(actions.size() - 1); - lastSyncedVersion = lastAction.getVersion(); - } - String json = WordProcessorHelper.serialize(document); - content.setVersion(lastSyncedVersion); - content.setSfdt(json); - Gson gson = new Gson(); - String data = gson.toJson(content); - return data; - } catch (Exception e) { - e.printStackTrace(); - return "{\"sections\":[{\"blocks\":[{\"inlines\":[{\"text\":" + e.getMessage() + "}]}]}]}"; - } - } - - @CrossOrigin(origins = "*", allowedHeaders = "*") - @PostMapping("/api/collaborativeediting/UpdateAction") - public ActionInfo UpdateAction(@RequestBody ActionInfo param) throws Exception { - String roomName = param.getRoomName(); - ActionInfo transformedAction = addOperationsToTable(param); - HashMap action = new HashMap<>(); - action.put("action", "updateAction"); - DocumentEditorHub.publishToRedis(roomName, transformedAction); - //DocumentEditorHub.broadcastToRoom(roomName, transformedAction, new MessageHeaders(action)); - return transformedAction; - } - - @CrossOrigin(origins = "*", allowedHeaders = "*") - @PostMapping("/api/collaborativeediting/GetActionsFromServer") - public String GetActionsFromServer(@RequestBody ActionInfo param) throws ClassNotFoundException { - String tableName = param.getRoomName(); - String getOperation = "SELECT * FROM \"" + tableName + "\" WHERE version > " + param.getVersion(); - try (Connection connection = dataSource.getConnection()) { - try (PreparedStatement updateCommand = connection.prepareStatement(getOperation)) { - ResultSet reader = updateCommand.executeQuery(); - ArrayList actions; - ArrayList> table = getOperationsFromDatabaseResult(reader); - if (!table.isEmpty()) { - int startVersion = Integer.parseInt(table.get(0).get("version").toString()); - int lowestVersion = getLowestClientVersion(table); - if (startVersion > lowestVersion) { - String updatedOperation = "SELECT * FROM \"" + tableName + "\" WHERE version >= " - + lowestVersion; - try (PreparedStatement command = connection.prepareStatement(updatedOperation)) { - ResultSet reader2 = command.executeQuery(); - table.clear(); - table = getOperationsFromDatabaseResult(reader2); - } - } - actions = getOperationsQueue(table); - for (ActionInfo info : actions) { - if (!info.isTransformed()) { - CollaborativeEditingHandler.transformOperation(info, actions); - } - } - // Assuming getIsTransformed() and Version are properties in ActionInfo - actions.removeIf(x -> x.getVersion() <= param.getVersion()); - return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(actions); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - return "{}"; - } - - private ActionInfo addOperationsToTable(ActionInfo action) throws Exception { - int clientVersion = action.getVersion(); - String roomName = action.getRoomName(); - String value = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(action); - String query = "INSERT INTO \"" + roomName + "\" (operation, clientVersion) VALUES (?, ?) RETURNING version;"; - - try (Connection connection = dataSource.getConnection()) { - PreparedStatement preparedStatement = connection.prepareStatement(query); - preparedStatement.setString(1, value); - preparedStatement.setInt(2, action.getVersion()); - try { - ResultSet resultSet = preparedStatement.executeQuery(); - if (resultSet.next()) { - int updateVersion = resultSet.getInt("version"); - if (updateVersion - clientVersion == 1) { - action.setVersion(updateVersion); - updateCurrentActionToDB(roomName, action, connection); - } else { - ArrayList> table = getOperationsToTransform(roomName, clientVersion + 1, - updateVersion, connection); - int startVersion = (int) table.get(0).get("version"); - int lowestVersion = getLowestClientVersion(table); - if (startVersion > lowestVersion) { - table = getOperationsToTransform(roomName, lowestVersion, updateVersion, connection); - } - ArrayList actions = getOperationsQueue(table); - for (ActionInfo info : actions) { - if (!info.isTransformed()) { - CollaborativeEditingHandler.transformOperation(info, actions); - } - } - action = actions.get(actions.size() - 1); - action.setVersion(updateVersion); - updateCurrentActionToDB(roomName, actions.get(actions.size() - 1), connection); - } - if (updateVersion % saveThreshold == 0) { - // Update the operations to table once specified threshold is reached. - updateOperationsToSourceDocument(roomName, true, updateVersion, connection, datasourceAccessKey, - datasourceSecretKey, datasourceBucketName); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - return action; - } - - private int getLowestClientVersion(ArrayList> table) { - int clientVersion = (int) table.get(0).get("clientVersion"); - for (Map row : table) { - int version = Integer.parseInt(row.get("clientVersion").toString()); - if (version < clientVersion) { - clientVersion = version; - } - } - return clientVersion; - } - - private ArrayList> getOperationsToTransform(String tableName, int clientVersion, - int currentVersion, Connection connection) throws ClassNotFoundException { - String getOperation = "SELECT * FROM \"" + tableName + "\" WHERE version BETWEEN ? AND ?"; - try (PreparedStatement command = connection.prepareStatement(getOperation)) { - command.setInt(1, clientVersion); - command.setInt(2, currentVersion); - try (ResultSet resultSet = command.executeQuery()) { - ArrayList> resultList = getOperationsFromDatabaseResult(resultSet); - return resultList; - } - } catch (SQLException e) { - e.printStackTrace(); - return null; - } - } - - private void updateCurrentActionToDB(String tableName, ActionInfo action, Connection connection) { - action.setTransformed(true); - String updateQuery = "UPDATE \"" + tableName + "\" SET operation = ? WHERE version = " + action.getVersion(); - try (PreparedStatement updateStatement = connection.prepareStatement(updateQuery)) { - updateStatement.setString(1, new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(action)); - updateStatement.executeUpdate(); - } catch (SQLException | com.fasterxml.jackson.core.JsonProcessingException e) { - e.printStackTrace(); - } - } - - public static void updateOperationsToSourceDocument(String roomName, boolean partialSave, int endVersion, - Connection connection, String accessKey, String secretKey, String bucketName) throws Exception { - - int lastSyncedVersion = getLastSavedVersion(connection, roomName); - String getOperation = ""; - if (partialSave) { - getOperation = "SELECT * FROM \"" + roomName + "\" WHERE version BETWEEN " + (lastSyncedVersion + 1) - + " AND " + endVersion; - } else { - getOperation = "SELECT * FROM \"" + roomName + "\" WHERE version > " + lastSyncedVersion; - } - - try (PreparedStatement command = connection.prepareStatement(getOperation)) { - ResultSet reader = command.executeQuery(); - ArrayList> table = getOperationsFromDatabaseResult(reader); - ArrayList actions = getOperationsQueue(table); - for (ActionInfo info : actions) { - if (!info.isTransformed()) { - CollaborativeEditingHandler.transformOperation(info, actions); - } - } - reader.close(); - command.close(); - - // room name is unique identifier used for editing the document in collaborative - // editing. - // Please get the actual file name by mapping the room name. - String fileName = ""; - - CollaborativeEditingHandler handler = new CollaborativeEditingHandler( - getDocumentFromBucketS3(fileName, accessKey, secretKey, bucketName)); - for (ActionInfo info : actions) { - handler.updateAction(info); - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - WordDocument doc = WordProcessorHelper.save(WordProcessorHelper.serialize(handler.getDocument())); - doc.save(outputStream, com.syncfusion.docio.FormatType.Docx); - byte[] data = outputStream.toByteArray(); - outputStream.close(); - doc.close(); - - // Save the document to S3 bucket - AwsCredentials credentials = AwsBasicCredentials.create(accessKey, secretKey); - StaticCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(credentials); - S3Client s3Client = S3Client.builder().region(Region.US_EAST_1).credentialsProvider(credentialsProvider) - .build(); - PutObjectRequest objectRequest = PutObjectRequest.builder().bucket(bucketName).key(roomName).build(); - s3Client.putObject(objectRequest, software.amazon.awssdk.core.sync.RequestBody.fromBytes(data)); - s3Client.close(); - - if (!partialSave) { - deleteLastModifiedVersion(roomName, connection); - dropTable(roomName, connection); - } else { - updateModifiedVersion(roomName, connection, endVersion); - } - } - - // connection.commit(); - /* - * } catch (Exception e) { e.printStackTrace(); } - */ - } - - private static void updateModifiedVersion(String roomName, Connection connection, int lastSavedVersion) - throws SQLException { - String tableName = "de_version_info"; - String query = "UPDATE \"" + tableName + "\" SET lastSavedVersion = ? where roomName= '" + roomName + "'"; - PreparedStatement preparedStatement = connection.prepareStatement(query); - preparedStatement.setInt(1, lastSavedVersion); - preparedStatement.executeUpdate(); - } - - private static void deleteLastModifiedVersion(String roomName, Connection connection) throws SQLException { - String tableName = "de_version_info"; - String query = "DELETE FROM \"" + tableName + "\" WHERE roomName= '" + roomName + "'"; - PreparedStatement preparedStatement = connection.prepareStatement(query); - preparedStatement.executeUpdate(); - } - - public static void dropTable(String documentId, Connection connection) throws ClassNotFoundException { - try { - // Drop the table - String sqlQuery = "DROP TABLE \"" + documentId + "\""; - try (PreparedStatement sqlCommand = connection.prepareStatement(sqlQuery)) { - sqlCommand.executeUpdate(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private ArrayList createRecordForCollaborativeEditing(String roomName, - OutSupport lastSyncedVersion) throws SQLException, ClassNotFoundException, IOException { - try (Connection connection = dataSource.getConnection()) { - if (!tableExists(connection, roomName)) { - lastSyncedVersion.setValue(0); - // If record not present, create new table - String queryString = "CREATE TABLE \"" + roomName - + "\" (version SERIAL PRIMARY KEY, operation TEXT, clientVersion INTEGER)"; - PreparedStatement preparedStatement = connection.prepareStatement(queryString); - preparedStatement.executeUpdate(); - // Create table to track the last saved version. - createRecordForVersionInfo(connection, roomName); - } else { - lastSyncedVersion.setValue(getLastSavedVersion(connection, roomName)); - // If record present, get previous editing operation from the db record. - String queryString = "SELECT * FROM \"" + roomName + "\" WHERE version > " - + lastSyncedVersion.getValue(); - try (PreparedStatement updateCommand = connection.prepareStatement(queryString)) { - ResultSet result = updateCommand.executeQuery(); - ArrayList actions = getOperationsQueue(getOperationsFromDatabaseResult(result)); - return actions; - } - } - connection.close(); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - private static int getLastSavedVersion(Connection connection, String roomName) throws SQLException { - String tableName = "de_version_info"; - String query = "SELECT lastSavedVersion FROM \"" + tableName + "\" WHERE roomName ='" + roomName + "'"; - PreparedStatement statement = connection.prepareStatement(query); - ResultSet resultSet = statement.executeQuery(); - int lastSavedVersion = 0; - if (resultSet.next()) { - lastSavedVersion = resultSet.getInt("lastSavedVersion"); - } - resultSet.close(); - statement.close(); - return lastSavedVersion; - } - - private static void createRecordForVersionInfo(Connection connection, String roomName) throws SQLException { - String tableName = "de_version_info"; - try { - if (!tableExists(connection, tableName)) { - // If record not present, create new table - String queryString = "CREATE TABLE \"" + tableName + "\" (roomName TEXT, lastSavedVersion INTEGER)"; - PreparedStatement preparedStatement = connection.prepareStatement(queryString); - preparedStatement.executeUpdate(); - } - String query = "INSERT INTO \"" + tableName + "\" (roomName, lastSavedVersion) VALUES (?, ?)"; - PreparedStatement preparedStatement = connection.prepareStatement(query); - preparedStatement.setString(1, roomName); - // Set initial version to 0; - preparedStatement.setInt(2, 0); - preparedStatement.executeUpdate(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - - private static boolean tableExists(Connection connection, String roomName) throws ClassNotFoundException { - try { - String query = "SELECT CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = '" - + roomName + "') THEN 1 ELSE 0 END;"; - PreparedStatement statement = connection.prepareStatement(query); - // statement.setString(1, tableName); - ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - int result = resultSet.getInt(1); - return result == 1; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - private static ArrayList> getOperationsFromDatabaseResult(ResultSet reader) - throws SQLException { - ArrayList> table = new ArrayList<>(); - while (reader.next()) { - Map row = new HashMap<>(); - row.put("version", reader.getInt("version")); - row.put("clientVersion", reader.getInt("clientVersion")); - row.put("operation", reader.getString("operation")); // Add other columns as needed - table.add(row); - } - return table; - } - - private static ArrayList getOperationsQueue(ArrayList> table) - throws JsonMappingException, JsonProcessingException { - ArrayList actions = new ArrayList<>(); - for (Map row : table) { - ObjectMapper objectMapper = new ObjectMapper(); - String jsonString = (String) row.get("operation"); - // Deserialize JSON string to ActionInfo object - ActionInfo action = objectMapper.readValue(jsonString, ActionInfo.class); - action.setVersion(Integer.parseInt(row.get("version").toString())); - action.setClientVersion(Integer.parseInt(row.get("clientVersion").toString())); - actions.add(action); - } - return actions; - } - - private static WordProcessorHelper getDocumentFromBucketS3(String documentId, String accessKey, String secretKey, - String bucketName) { - try { - AwsCredentials credentials = AwsBasicCredentials.create(accessKey, secretKey); - StaticCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(credentials); - S3Client s3Client = S3Client.builder().region(Region.US_EAST_1).credentialsProvider(credentialsProvider) - .build(); - ResponseInputStream objectData = s3Client - .getObject(GetObjectRequest.builder().bucket(bucketName).key(documentId).build()); - // Read the object data into a byte array - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int bytesRead; - while ((bytesRead = objectData.read(buffer)) != -1) { - byteArrayOutputStream.write(buffer, 0, bytesRead); - } - s3Client.close(); - byte[] data = byteArrayOutputStream.toByteArray(); - // Create an input stream from the byte array - try (InputStream stream = new ByteArrayInputStream(data)) { - return WordProcessorHelper.load(stream, true); - } - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/CustomParameter.java b/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/CustomParameter.java deleted file mode 100644 index ce5a8e5..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/CustomParameter.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.syncfusion.tomcat; - -public class CustomParameter { - public String content; - public String type; - - public String getContent() { - return content; - } - - public String getType() { - return type; - } - - public void setContent(String value) { - content= value; - } - - public void setType(String value) { - type = value; - } -} diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/CustomRestrictParameter.java b/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/CustomRestrictParameter.java deleted file mode 100644 index 7d2bbf7..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/CustomRestrictParameter.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.syncfusion.tomcat; - -public class CustomRestrictParameter { - public String passwordBase64; - public String saltBase64; - public int spinCount; - - public String getPasswordBase64() { - return passwordBase64; - } - - public String getSaltBase64() { - return saltBase64; - } - - public int getSpinCount() { - return spinCount; - } - - public void setPasswordBase64(String value) { - passwordBase64= value; - } - - public void setSaltBase64(String value) { - saltBase64= value; - } - - public void setSpinCount(int value) { - spinCount= value; - } -} diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/DocumentContent.java b/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/DocumentContent.java deleted file mode 100644 index 6e95c68..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/DocumentContent.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.syncfusion.tomcat; -import java.util.List; - -import com.syncfusion.ej2.wordprocessor.ActionInfo; -public class DocumentContent { - private int version; - private String sfdt; - private List actions; - - // Default constructor - public DocumentContent() { - } - - // Parameterized constructor - - public DocumentContent(int version, String sfdt, List actions) { - this.version = version; this.sfdt = sfdt; this.actions = actions; } - - - // Getter and setter methods - public int getVersion() { - return version; - } - - public void setVersion(int version) { - this.version = version; - } - - public String getSfdt() { - return sfdt; - } - - public void setSfdt(String sfdt) { - this.sfdt = sfdt; - } - - - public List getActions() { return actions; } - - public void setActions(List actions) { this.actions = actions; } - -} diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/FileNameInfo.java b/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/FileNameInfo.java deleted file mode 100644 index b6560b7..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/FileNameInfo.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.syncfusion.tomcat; - -import java.awt.List; -import java.util.ArrayList; - -import com.syncfusion.ej2.wordprocessor.ActionInfo; -import com.syncfusion.tomcat.controller.DocumentEditorHub; - -public class FileNameInfo { - - - private int fileIndex; - private String fileName; - - public FileNameInfo(int index, String fileName) - { - this.setFileIndex(index); - this.setFileName(fileName); - if (DocumentEditorHub.roomList.containsKey(fileName)) { - ArrayList users = DocumentEditorHub.roomList.get(fileName); - for (ActionInfo user : users) { - activeUsers.add(constructInitials(user.getCurrentUser())); - } - } - } - public String constructInitials(String authorName) { - String[] splittedName = authorName.split(" "); - StringBuilder initials = new StringBuilder(); - for (String namePart : splittedName) { - if (namePart.length() > 0 && !namePart.isEmpty()) { - initials.append(namePart.charAt(0)); - } - } - return initials.toString(); - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public int getFileIndex() { - return fileIndex; - } - - public void setFileIndex(int fileIndex) { - this.fileIndex = fileIndex; - } - private String documentName; - private String createdOn; - private String sharedWith; - private String documentID; - private String sharedBy; - private String owner; - private ArrayList activeUsers = new ArrayList<>(); - - public String getDocumentName() { - return documentName; - } - - public void setDocumentName(String documentName) { - this.documentName = documentName; - } - - public String getCreatedOn() { - return createdOn; - } - - public void setCreatedOn(String createdOn) { - this.createdOn = createdOn; - } - - public String getSharedWith() { - return sharedWith; - } - - public void setSharedWith(String sharedWith) { - this.sharedWith = sharedWith; - } - - public String getDocumentID() { - return documentID; - } - - public void setDocumentID(String documentID) { - this.documentID = documentID; - } - - public String getSharedBy() { - return sharedBy; - } - - public void setSharedBy(String sharedBy) { - this.sharedBy = sharedBy; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public ArrayList getActiveUsers() { - return activeUsers; - } - - public void setActiveUsers(ArrayList activeUsers) { - this.activeUsers = activeUsers; - } - - -} \ No newline at end of file diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/FilesPathInfo.java b/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/FilesPathInfo.java deleted file mode 100644 index 0001e5d..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/FilesPathInfo.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.syncfusion.tomcat; - -public class FilesPathInfo { - private String fileName; - private String roomName; - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public String getRoomName() { - return roomName; - } - - public void setRoomName(String roomName) { - this.roomName = roomName; - } -} diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/TomcatApplication.java b/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/TomcatApplication.java deleted file mode 100644 index 15cf9f5..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/TomcatApplication.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.syncfusion.tomcat; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import com.syncfusion.ej2.wordprocessor.WordProcessorHelper; -import com.syncfusion.ej2.wordprocessor.FormatType; - -@SpringBootApplication(exclude = { SecurityAutoConfiguration.class }) -@RestController -public class TomcatApplication extends SpringBootServletInitializer { - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(TomcatApplication.class); - } - - public static void main(String[] args) { - SpringApplication.run(TomcatApplication.class, args); - } - - @CrossOrigin - @RequestMapping(value = "/") - public String hello() { - return "Hello From Syncfusion Document Editor Java Service"; - } - - @CrossOrigin - @RequestMapping(value = "/test") - public String test() { - System.out.println("==== in test ===="); - return "{\"sections\":[{\"blocks\":[{\"inlines\":[{\"texdocNamet\":\"Hello World\"}]}]}]}"; - } - - @CrossOrigin - @RequestMapping(value = "/api/wordeditor/Import") - public String uploadFile(@RequestParam("files") MultipartFile file) throws Exception { - try { - return WordProcessorHelper.load(file.getInputStream(), FormatType.Docx); - } catch (Exception e) { - e.printStackTrace(); - return "{\"sections\":[{\"blocks\":[{\"inlines\":[{\"text\":" + e.getMessage() + "}]}]}]}"; - } - } - - @CrossOrigin - @RequestMapping(value = "/api/wordeditor/RestrictEditing") - public String[] restrictEditing(@RequestBody CustomRestrictParameter param) throws Exception { - if (param.passwordBase64 == "" && param.passwordBase64 == null) - return null; - return WordProcessorHelper.computeHash(param.passwordBase64, param.saltBase64, param.spinCount); - } - - @CrossOrigin - @RequestMapping(value = "/api/wordeditor/SystemClipboard") - public String systemClipboard(@RequestBody CustomParameter param) { - if (param.content != null && param.content != "") { - try { - return WordProcessorHelper.loadString(param.content, GetFormatType(param.type.toLowerCase())); - } catch (Exception e) { - return ""; - } - } - return ""; - } - - static FormatType GetFormatType(String format) { - switch (format) { - case ".dotx": - case ".docx": - case ".docm": - case ".dotm": - return FormatType.Docx; - case ".dot": - case ".doc": - return FormatType.Doc; - case ".rtf": - return FormatType.Rtf; - case ".txt": - return FormatType.Txt; - case ".xml": - return FormatType.WordML; - case ".html": - return FormatType.Html; - default: - return FormatType.Docx; - } - } - -} diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/config/WebSocketConfig.java b/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/config/WebSocketConfig.java deleted file mode 100644 index 73c2cdf..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/config/WebSocketConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.syncfusion.tomcat.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.messaging.simp.config.MessageBrokerRegistry; -import org.springframework.web.socket.config.annotation.*; - -@Configuration -@EnableWebSocketMessageBroker -public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { - - @Override - public void registerStompEndpoints(StompEndpointRegistry registry) { - registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS(); - } - - @Override - public void configureMessageBroker(MessageBrokerRegistry registry) { - registry.setApplicationDestinationPrefixes("/app"); - registry.enableSimpleBroker("/topic"); - } - -} \ No newline at end of file diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/controller/DocumentEditorHub.java b/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/controller/DocumentEditorHub.java deleted file mode 100644 index 9115ab3..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/controller/DocumentEditorHub.java +++ /dev/null @@ -1,219 +0,0 @@ -package com.syncfusion.tomcat.controller; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.util.ArrayList; -import java.util.HashMap; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.event.EventListener; -import org.springframework.messaging.MessageHeaders; -import org.springframework.messaging.handler.annotation.DestinationVariable; -import org.springframework.messaging.handler.annotation.MessageMapping; -import org.springframework.messaging.simp.SimpMessageHeaderAccessor; -import org.springframework.messaging.simp.SimpMessagingTemplate; -import org.springframework.messaging.support.MessageBuilder; -import org.springframework.stereotype.Controller; -import org.springframework.web.socket.messaging.SessionDisconnectEvent; - -import com.syncfusion.ej2.wordprocessor.UserActionInfo; -import com.syncfusion.tomcat.CollaborativeEditingController; - -import redis.clients.jedis.Jedis; -import redis.clients.jedis.exceptions.JedisConnectionException; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.syncfusion.ej2.wordprocessor.ActionInfo; - -@Controller -public class DocumentEditorHub { - public static final HashMap> roomList = new HashMap<>(); - public static SimpMessagingTemplate messagingTemplate; - private static final int MAX_RETRIES = 5; - private static final long RETRY_INTERVAL_MS = 1000; - public DocumentEditorHub(SimpMessagingTemplate messagingTemplate) { - this.messagingTemplate = messagingTemplate; - } - - @Value("${spring.datasource.url}") - public String datasourceUrl; - @Value("${spring.datasource.username}") - private String datasourceUsername; - @Value("${spring.datasource.password}") - private String datasourcePassword; - - // Bucket S3 - @Value("${spring.datasource.accesskey}") - private String datasourceAccessKey; - @Value("${spring.datasource.secretkey}") - private String datasourceSecretKey; - @Value("${spring.datasource.bucketname}") - private String datasourceBucketName; - @Value("${spring.datasource.regionname}") - private String datasourceRegionName; - - @MessageMapping("/join/{documentName}") - public void joinGroup(ActionInfo info, SimpMessageHeaderAccessor headerAccessor, - @DestinationVariable String documentName) throws JsonProcessingException { - // To get the connection Id - String connectionId = headerAccessor.getSessionId(); - info.setConnectionId(connectionId); - String docName = info.getRoomName(); - HashMap additionalHeaders = new HashMap<>(); - additionalHeaders.put("action", "connectionId"); - MessageHeaders headers = new MessageHeaders(additionalHeaders); - // send the conection Id to the client - broadcastToRoom(docName, info, headers); - try (Jedis jedis = jedisPool.getResource()) { - // to maintain the session id with its corresponding ActionInfo details. - jedis.hset("documentMap", connectionId, documentName); - // add the user details to the Redis cache - jedis.sadd(docName, new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(info)); - // Subscribe to the room, so that all users can get the JOIN/LEAVE notification - joinLeaveUsersubscribe(docName); - // publish the user list to the redis - jedis.publish(docName, "JOIN|" + connectionId); - - } catch (JedisConnectionException e) { - System.out.println(e); - } - } - - @EventListener - public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) throws Exception { - String sessionId = event.getSessionId(); - try (Jedis jedis = jedisPool.getResource()) { - //to get the user details of the provided sessionId - String docName = jedis.hget("documentMap", sessionId); - // Publish a message indicating the user's departure from the group - jedis.publish(docName, "LEAVE|" + sessionId); - } catch (JedisConnectionException e) { - System.out.println(e); - } - } - - private void joinLeaveUsersubscribe(String docName) { - new Thread(() -> { - try (Jedis jedis = jedisPool.getResource()) { - jedis.subscribe(new JedisPubSub() { - @Override - public void onMessage(String channel, String message) { - String[] parts = message.split("\\|"); - if (parts.length == 2) { - String eventType = parts[0]; - String sessionId = parts[1]; - notifyUsers(channel, eventType, sessionId); - } - } - }, docName); - } catch (JedisConnectionException e) { - System.out.println(e); - } - }).start(); - } - - public void notifyUsers(String docName, String eventType, String sessionId) { - try (Jedis jedis = jedisPool.getResource()) { - if ("JOIN".equals(eventType)) { - HashMap addUser = new HashMap<>(); - addUser.put("action", "addUser"); - MessageHeaders addUserheaders = new MessageHeaders(addUser); - // get the list of users from Redis - Set userJsonStrings = jedis.smembers(docName); - System.out.println("userJsonStrings to join" + userJsonStrings); - ArrayList actionsList = new ArrayList<>(); - ObjectMapper mapper = new ObjectMapper(); - for (String userJson : userJsonStrings) { - try { - ActionInfo actionInfo = mapper.readValue(userJson, ActionInfo.class); - actionsList.add(actionInfo); - } catch (Exception e) { - System.err.println("Error parsing user information JSON: " + e.getMessage()); - } - } - //Boradcast the user list to all the users connected in that room - broadcastToRoom(docName, actionsList, addUserheaders); - } else if ("LEAVE".equals(eventType)) { - // get the user list from the redis - Set userJsonStrings = jedis.smembers(docName); - System.out.println("userJsonStrings to leave" + userJsonStrings); - if (!userJsonStrings.isEmpty()) { - ObjectMapper mapper = new ObjectMapper(); - for (String userJson : userJsonStrings) { - ActionInfo action = null; - try { - action = mapper.readValue(userJson, ActionInfo.class); - } catch (JsonMappingException e) { - e.printStackTrace(); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } - if (action.getConnectionId().equals(sessionId)) { - // Remove the user from the user list - jedis.srem(docName, userJson); - HashMap removeUser = new HashMap<>(); - removeUser.put("action", "removeUser"); - MessageHeaders removeUserheaders = new MessageHeaders(removeUser); - // Broadcast the removal notification to all users in the document - broadcastToRoom(docName, action, removeUserheaders); - // Remove the session ID from the session-document mapping - jedis.hdel("documentMap", sessionId); - break; - } - } - } else { - System.out.println("No users found in the document."); - } - if (userJsonStrings.isEmpty()) { - Connection connection = null; - try { - connection = DriverManager.getConnection(datasourceUrl, datasourceUsername, datasourcePassword); - } catch (SQLException e1) { - e1.printStackTrace(); - } - try { - TomcatApplication.updateOperationsToSourceDocument(docName, - "doc_18d1e2a949604a1f8430710ae19aa354", false, 0, connection); - } catch (Exception e) { - e.printStackTrace(); - } - jedis.del(docName); - } - } - - } catch (JedisConnectionException e) { - System.out.println(e); - } - - } - - public static void broadcastToRoom(String roomName, Object payload, MessageHeaders headers) { - - { - messagingTemplate.convertAndSend("/topic/public/" + roomName, - MessageBuilder.createMessage(payload, headers)); - } - } - public static void publishToRedis(String roomName, Object payload) throws JsonProcessingException { - int retries = 0; - while (retries < MAX_RETRIES) { - try (Jedis jedis = RedisSubscriber.jedisPool.getResource()) { - // try(Jedis jedis = RedisSubscriber.jedisConnection){ - - jedis.publish("collaborativedtiting", - new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(payload)); - System.out.println("Message published to Redis" - + new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(payload)); - break; - } catch (JedisConnectionException e) { - retries++; - System.out.println("Connection failed. Retrying in " + RETRY_INTERVAL_MS + " milliseconds..."); - try { - Thread.sleep(RETRY_INTERVAL_MS); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } - } - } -} \ No newline at end of file diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/controller/RedisSubscriber.java b/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/controller/RedisSubscriber.java deleted file mode 100644 index 7507463..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/controller/RedisSubscriber.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.syncfusion.tomcat.controller; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.messaging.MessageHeaders; -import org.springframework.stereotype.Component; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.syncfusion.ej2.wordprocessor.ActionInfo; - -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import redis.clients.jedis.JedisPubSub; -import redis.clients.jedis.exceptions.JedisConnectionException; - -@Component -public class RedisSubscriber { - public static JedisPool jedisPool; - // Redis Configuration - @Value("${spring.datasource.redishost}") - private String REDIS_HOST; - @Value("${spring.datasource.redisport}") - private int REDIS_PORT; - - - @PostConstruct - public void subscribeToInstanceChannel() { - String channel = "collaborativedtiting"; - new Thread(() -> { - JedisPoolConfig poolConfig = new JedisPoolConfig(); - jedisPool = new JedisPool(poolConfig, REDIS_HOST, REDIS_PORT); - try (Jedis jedis = jedisPool.getResource()) { - jedis.subscribe(new JedisPubSub() { - @Override - public void onMessage(String channel, String message) { - System.out.println("Received message from channel " + channel + ": " + message); - ObjectMapper objectMapper = new ObjectMapper(); - try { - ActionInfo action = objectMapper.readValue(message, ActionInfo.class); - HashMap updateAction = new HashMap<>(); - updateAction.put("action", "updateAction"); - MessageHeaders updateActionheaders = new MessageHeaders(updateAction); - DocumentEditorHub.broadcastToRoom(action.getRoomName(), action, updateActionheaders); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } - } - @Override - public void onSubscribe(String channel, int subscribedChannels) { - System.out.println("Subscribed to channel: " + channel); - } - }, channel); - } catch (JedisConnectionException e) { - // Handle the connection exception - System.out.println("Connection failed. Retrying ..."); - } - }).start(); - } -} diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/controller/WebSocketEventListener.java b/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/controller/WebSocketEventListener.java deleted file mode 100644 index 3bfbd8c..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/java/com/syncfusion/tomcat/controller/WebSocketEventListener.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.syncfusion.tomcat.controller; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.event.EventListener; -import org.springframework.messaging.simp.stomp.StompHeaderAccessor; -import org.springframework.stereotype.Component; -import org.springframework.web.socket.messaging.SessionConnectedEvent; - - -@Component -public class WebSocketEventListener { - - private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class); - - @EventListener - public void handleWebSocketConnectListener(SessionConnectedEvent event) { - logger.info("Received a new web socket connection"); - StompHeaderAccessor headers = StompHeaderAccessor.wrap(event.getMessage()); - String sessionId = headers.getSessionId(); - // messagingTemplate.convertAndSend("/topic/session-id", sessionId); - } - - -} diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/main/resources/application.properties b/Server side with database/Java/Java web service using PostgreSQL/src/main/resources/application.properties deleted file mode 100644 index f4236c4..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/main/resources/application.properties +++ /dev/null @@ -1,27 +0,0 @@ - -server.port=8081 - -#postgres sql configuration -spring.jpa.database=POSTGRESQL -spring.datasource.url="" -spring.datasource.username="" -spring.datasource.password="" - -#S3 configuration -spring.datasource.accesskey= "" -spring.datasource.secretkey= "" -spring.datasource.bucketname= "" -spring.datasource.regionname= "" - -#Redis configuration -spring.datasource.redishost= "" -spring.datasource.redisport= "" - - -#connection pool configuration -spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true -spring.jpa.database-platform=org.hibernate.dialect.H2Dialect -spring.datasource.type = com.zaxxer.hikari.HikariDataSource -spring.datasource.hikari.minimum-idle=10 -spring.datasource.hikari.maximum-pool-size=10 -spring.datasource.hikari.max-lifetime=1200000 \ No newline at end of file diff --git a/Server side with database/Java/Java web service using PostgreSQL/src/test/java/com/syncfusion/tomcat/TomcatApplicationTests.java b/Server side with database/Java/Java web service using PostgreSQL/src/test/java/com/syncfusion/tomcat/TomcatApplicationTests.java deleted file mode 100644 index 19b6fac..0000000 --- a/Server side with database/Java/Java web service using PostgreSQL/src/test/java/com/syncfusion/tomcat/TomcatApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.syncfusion.tomcat; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class TomcatApplicationTests { - - @Test - void contextLoads() { - } - -}