mirror of
https://github.com/ONLYOFFICE/document-server-integration.git
synced 2026-02-12 10:55:15 +08:00
Compare commits
295 Commits
v99.99.99.
...
feature/ja
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ac382d3c0 | |||
| 5933aa83ad | |||
| 2e1854f6c1 | |||
| 2d9a7ed502 | |||
| 78bd037486 | |||
| 17beef45f4 | |||
| b11a1be481 | |||
| a3e140981d | |||
| e0386f7cf9 | |||
| 0521f20413 | |||
| 61b5746ddf | |||
| 57d823acb1 | |||
| 4d99e2e406 | |||
| bec48ed834 | |||
| e856f5bcb1 | |||
| c57a710bca | |||
| 248e9213a1 | |||
| a035adcbd9 | |||
| 7fd1b65fec | |||
| 8ee0aa45b9 | |||
| dfcf244dc8 | |||
| 0563795494 | |||
| b6b6e80ffb | |||
| bd3b91d02f | |||
| 555f8d43cd | |||
| 3f48a8d492 | |||
| bb921e7eff | |||
| 13d5e6fa94 | |||
| cbfcf5de96 | |||
| 4771d96819 | |||
| d2aa6f0653 | |||
| cf2a00a374 | |||
| bdfb75dc84 | |||
| 9e21ca625c | |||
| 02def07f23 | |||
| fc4dac6c4b | |||
| 486a09f3b2 | |||
| 9a22fc854b | |||
| ac4d5561a2 | |||
| 98cdda06c4 | |||
| 744fccf913 | |||
| 349ff5d61d | |||
| dbba22df23 | |||
| 2ddd822b24 | |||
| 6b4d6baf4b | |||
| 2c8d151cc7 | |||
| 60c7c025a3 | |||
| 7aaf5243cb | |||
| 44b0f4d53d | |||
| b765d43612 | |||
| 70b63636e3 | |||
| 8d4582e379 | |||
| a1ec2cf366 | |||
| 4907e9d3c8 | |||
| 88f3d6da59 | |||
| 481b111cb2 | |||
| a1e13f3315 | |||
| d1dd289c77 | |||
| 7b4e40c4e4 | |||
| 6d4cad2215 | |||
| f43a4471ef | |||
| 0cf90e86c7 | |||
| 406de99b01 | |||
| f4bcb15d33 | |||
| d2a0164738 | |||
| a49ef4cc13 | |||
| 3ca29cd402 | |||
| c398b30e33 | |||
| 8caea9fab0 | |||
| f44c62540c | |||
| 7644db80e3 | |||
| 880497cd01 | |||
| 34f8174d9d | |||
| 99bc9d3fdf | |||
| 165c292ab8 | |||
| 8fe41cd8e6 | |||
| 705ea097e2 | |||
| f4799bebb4 | |||
| 4ffa524de0 | |||
| cd055317e0 | |||
| b1941c5980 | |||
| 83bc0fed5e | |||
| 8b71bb0433 | |||
| 5620f49f8f | |||
| d9fefef834 | |||
| 37591d847c | |||
| 77290d88f3 | |||
| 6befd87761 | |||
| f3e270c1ad | |||
| f5f1e4b391 | |||
| 8ba389d02f | |||
| 45910ff1f3 | |||
| 3bd6f51edc | |||
| fe9791f03d | |||
| 531137dca4 | |||
| e267b30b26 | |||
| 8733baa04b | |||
| 8cec9fc465 | |||
| 7ec969f4d9 | |||
| c7e13ef8a8 | |||
| 3d488f89b2 | |||
| cc00af1510 | |||
| f8aa55143c | |||
| 1b44c04893 | |||
| 1585d1821e | |||
| e996c4d265 | |||
| cc0c6189bd | |||
| ef7662c069 | |||
| 79ff84a4cc | |||
| e4bab17b08 | |||
| c734f5dd69 | |||
| d79feca18c | |||
| 1a51759154 | |||
| 77c4caa26f | |||
| 5944e41cb4 | |||
| 09ccde3f84 | |||
| b27e532a83 | |||
| 8807328180 | |||
| 827e96c506 | |||
| 68d26c9c66 | |||
| 80924be536 | |||
| 64f085d4b7 | |||
| 39c2267468 | |||
| 22af4e097f | |||
| 1a1cde0f67 | |||
| 1265ecdee1 | |||
| 19d11a97f9 | |||
| bf6f3373a6 | |||
| 1fb4d759a3 | |||
| de33efa599 | |||
| 6fa150ade6 | |||
| 88f4b6327d | |||
| 82905fca6c | |||
| ccb67ad73d | |||
| 5a233b8dc7 | |||
| 127183bb16 | |||
| 8924304bdb | |||
| 68dd1fc369 | |||
| 7251cb1681 | |||
| a82e4b6bdf | |||
| d2f2031fa7 | |||
| 4a902dff94 | |||
| f26220683c | |||
| c3e4533d1a | |||
| f6618c8c92 | |||
| efd710c6c0 | |||
| e106677efb | |||
| ecd02e07c0 | |||
| 847902fad9 | |||
| d4b5f86822 | |||
| 7c35d8127d | |||
| d023b23fc9 | |||
| 8b10c5ac2e | |||
| 54bc536329 | |||
| 07d7e5d887 | |||
| 009577b52e | |||
| c1fd896be4 | |||
| 033126583b | |||
| 3140d31e9c | |||
| 92ea5151ad | |||
| ae4e4c14ad | |||
| 9a9d3c0b35 | |||
| 13d3fe97d9 | |||
| 5bfe32f796 | |||
| 5a1ad9139f | |||
| 91fbc384f3 | |||
| 9d275ebe6c | |||
| 09a5d802ec | |||
| b548ffb97e | |||
| 50b0c3d29e | |||
| 93b4560c31 | |||
| 2e9807814a | |||
| d0cfd03bf8 | |||
| 72c14a4e7b | |||
| 44a3f29a79 | |||
| 98dceacc4c | |||
| 05f4063ba6 | |||
| d5797f7c02 | |||
| 5f40faac2a | |||
| c062e554db | |||
| 41e44985d6 | |||
| 95e1135e86 | |||
| cafb79c8d5 | |||
| 1dbc275a57 | |||
| 6dd44d2094 | |||
| b74a3c5565 | |||
| 27e5fa8482 | |||
| 46dab40432 | |||
| ebd4ead751 | |||
| 9014f96da3 | |||
| 273e4d5b77 | |||
| d8b6cdcf78 | |||
| 6e0899daaf | |||
| a5d459a744 | |||
| dcb48f3849 | |||
| c8b3ed761e | |||
| 01c8b23d1d | |||
| bf9373842b | |||
| 7eaf4f5ae7 | |||
| e09f258f25 | |||
| 054e144d93 | |||
| 3b698eb974 | |||
| c356d952be | |||
| b1f3704624 | |||
| 1dd545dc9c | |||
| 1f6dfb0677 | |||
| b59874f54b | |||
| 4d9f02c606 | |||
| c344a1d6a6 | |||
| a53f36eca3 | |||
| ca49e5bdda | |||
| 4882459f51 | |||
| 0a0f5b556c | |||
| fdefc25479 | |||
| 2502c2a979 | |||
| df83585352 | |||
| 6979ec815e | |||
| d007b0a969 | |||
| 96a9dd7990 | |||
| 91d8fc2487 | |||
| ae64081f97 | |||
| 820cafe202 | |||
| 3ec226109e | |||
| b1f0fa6ecc | |||
| b02ffff33e | |||
| f74f0ba376 | |||
| d61fdaaa53 | |||
| 270cbee160 | |||
| a31a24a871 | |||
| df0e197cb5 | |||
| 09802afc6f | |||
| 1c43679d87 | |||
| 573eeb6e18 | |||
| 78cf6c35f8 | |||
| c7f5003d69 | |||
| 19baff4340 | |||
| cc5c912658 | |||
| 64f2d605c2 | |||
| c9fca685bf | |||
| 820883a584 | |||
| 05a00a33a3 | |||
| 613cb713cc | |||
| 9216ff3a97 | |||
| dbaa7c5113 | |||
| d6ad145111 | |||
| 456df162e6 | |||
| 50fd47cf7c | |||
| f9c0da1696 | |||
| a7807513c6 | |||
| 128430d698 | |||
| 8077a66f16 | |||
| b3d8695a26 | |||
| 00872758ee | |||
| 3301c24de5 | |||
| dd0c049a70 | |||
| 44fb3a089c | |||
| 513bf99adb | |||
| 6f92633ef8 | |||
| b67e768dce | |||
| 751a886bfa | |||
| 66ea4b144b | |||
| 7a73422231 | |||
| 93accdac7c | |||
| def268f5f2 | |||
| a7c917db3f | |||
| 82efd0f18a | |||
| 8ce90d89ed | |||
| 9277d3de58 | |||
| baf7a1e5dd | |||
| e2a14a74db | |||
| 848cfb20bc | |||
| ddd3ec82a8 | |||
| 0ed08fd7b2 | |||
| e1c5907003 | |||
| 9dd2d7c0db | |||
| 8f0cbb78af | |||
| 72e48914aa | |||
| 82a282029a | |||
| 9b7c12b5c0 | |||
| 6ea5546099 | |||
| 92fbd1e293 | |||
| 855c1ed9f9 | |||
| 7e60ec15fd | |||
| 3697a4a888 | |||
| 0b8107d167 | |||
| 885850ee33 | |||
| 98c61250a6 | |||
| 457487844c | |||
| ff72956b68 | |||
| cda8a86c2a | |||
| e96200df85 | |||
| de75b11e18 | |||
| f27afe1535 | |||
| 1bdb3c03bc | |||
| 111dc14f2b |
2
.github/workflows/lint-java.yml
vendored
2
.github/workflows/lint-java.yml
vendored
@ -6,7 +6,7 @@ on:
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/java/**']
|
||||
pull_request:
|
||||
branches: [master, main, develop]
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/java/**']
|
||||
|
||||
jobs:
|
||||
|
||||
2
.github/workflows/lint-nodejs.yml
vendored
2
.github/workflows/lint-nodejs.yml
vendored
@ -6,7 +6,7 @@ on:
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/nodejs/**']
|
||||
pull_request:
|
||||
branches: [master, main, develop]
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/nodejs/**']
|
||||
|
||||
env:
|
||||
|
||||
8
.github/workflows/lint-php.yml
vendored
8
.github/workflows/lint-php.yml
vendored
@ -6,7 +6,7 @@ on:
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/php/**']
|
||||
pull_request:
|
||||
branches: [master, main, develop]
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/php/**']
|
||||
|
||||
jobs:
|
||||
@ -22,8 +22,10 @@ jobs:
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.1'
|
||||
php-version: '8.2'
|
||||
tools: cs2pr, phpcs
|
||||
|
||||
- name: Run phpcs
|
||||
run: phpcs -q --extensions=php,module,inc,install,test,profile,theme,css,info,txt,md,yml --ignore=node_modules,bower_components,vendor ./
|
||||
run: |
|
||||
phpcs --version
|
||||
phpcs -q --extensions=php,module,inc,install,test,profile,theme,info --ignore=node_modules,bower_components,vendor,css,js,lib --standard=./ruleset.xml ./
|
||||
2
.github/workflows/lint-python.yml
vendored
2
.github/workflows/lint-python.yml
vendored
@ -6,7 +6,7 @@ on:
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/python/**']
|
||||
pull_request:
|
||||
branches: [master, main, develop]
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/python/**']
|
||||
|
||||
jobs:
|
||||
|
||||
2
.github/workflows/lint-ruby.yml
vendored
2
.github/workflows/lint-ruby.yml
vendored
@ -6,7 +6,7 @@ on:
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/ruby/**']
|
||||
pull_request:
|
||||
branches: [master, main, develop]
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/ruby/**']
|
||||
|
||||
jobs:
|
||||
|
||||
2
.github/workflows/lint-spring.yml
vendored
2
.github/workflows/lint-spring.yml
vendored
@ -6,7 +6,7 @@ on:
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/java-spring/**']
|
||||
pull_request:
|
||||
branches: [master, main, develop]
|
||||
branches: [master, main]
|
||||
paths: ['web/documentserver-example/java-spring/**']
|
||||
|
||||
jobs:
|
||||
|
||||
@ -250,6 +250,14 @@ jQuery.UI - jQuery UI is an open source library of interface components —
|
||||
License: MIT
|
||||
License File: jQuery.UI.license
|
||||
|
||||
JWT - JSON Web Token implementation (https://github.com/firebase/php-jwt/blob/master/LICENSE)
|
||||
License: BSD-3-Clause
|
||||
License File: jwt.license
|
||||
|
||||
PHP_CodeSniffer - PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent. (https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt)
|
||||
License: BSD-3-Clause
|
||||
License File: PHP_CodeSniffer.license
|
||||
|
||||
|
||||
web/documentserver-example/ruby
|
||||
|
||||
|
||||
@ -1,9 +1,14 @@
|
||||
# Change Log
|
||||
|
||||
- php: linter refactoring
|
||||
|
||||
## 1.5.0
|
||||
- nodejs: added wopi putRelativeFile action
|
||||
- nodejs: wopi editnew action for exisiting file
|
||||
- nodejs: fix wopi actions after restart
|
||||
- setting an unavailable language
|
||||
- description in the tooltip on the main page
|
||||
- nodejs: referenceData
|
||||
- option to send directUrl
|
||||
|
||||
## 1.4.0
|
||||
|
||||
@ -26,13 +26,13 @@
|
||||
<RemoveDir Directories="$(To)" ContinueOnError="true" />
|
||||
|
||||
<ItemGroup>
|
||||
<ZipFilesCSharp Include="$(DirCSharp)**" Exclude="$(DirCSharp)obj\**;$(DirCSharp)**\.git" />
|
||||
<ZipFilesCSharp Include="$(DirCSharp)**" Exclude="$(DirCSharp).vs\**;$(DirCSharp)bin\*.pdb;$(DirCSharp)bin\*.xml;$(DirCSharp)obj\**;$(DirCSharp)packages\**;$(DirCSharp)**\.git" />
|
||||
</ItemGroup>
|
||||
<Copy SourceFiles="@(ZipFilesCSharp)" DestinationFiles="@(ZipFilesCSharp->'$(NameCSharp)\%(RecursiveDir)%(Filename)%(Extension)')" />
|
||||
<Zip Files="$(NameCSharp)" WorkingDirectory="$(To)" ZipFileName="$(NameCSharp).zip" />
|
||||
|
||||
<ItemGroup>
|
||||
<ZipFilesMVC Include="$(DirMvc)**" Exclude="$(DirMvc)obj\**;$(DirMvc)**\.git" />
|
||||
<ZipFilesMVC Include="$(DirMvc)**" Exclude="$(DirMvc).vs\**;$(DirMvc)bin\*.pdb;$(DirMvc)bin\*.xml;$(DirMvc)obj\**;$(DirMvc)packages\**;$(DirMvc)**\.git" />
|
||||
</ItemGroup>
|
||||
<Copy SourceFiles="@(ZipFilesMVC)" DestinationFiles="@(ZipFilesMVC->'$(NameMvc)\%(RecursiveDir)%(Filename)%(Extension)')" />
|
||||
<Zip Files="$(NameMvc)" WorkingDirectory="$(To)" ZipFileName="$(NameMvc).zip" />
|
||||
|
||||
@ -98,9 +98,7 @@ namespace OnlineEditorsExampleMVC.Helpers
|
||||
var downloadUri = (string)fileData["url"];
|
||||
string curExt = Path.GetExtension(fileName).ToLower(); // get current file extension
|
||||
|
||||
var downloadExt = fileData.ContainsKey("filetype")
|
||||
? "." + (string)fileData["filetype"]
|
||||
: Path.GetExtension(downloadUri).ToLower() ?? ""; // TODO: Delete in version 7.0 or higher. Support for versions below 7.0
|
||||
var downloadExt = "." + (string)fileData["filetype"]; // get the extension of the downloaded file
|
||||
|
||||
var newFileName = fileName;
|
||||
|
||||
@ -130,37 +128,48 @@ namespace OnlineEditorsExampleMVC.Helpers
|
||||
|
||||
DocManagerHelper.VerifySSL();
|
||||
|
||||
var storagePath = DocManagerHelper.StoragePath(newFileName, userAddress); // get the file path
|
||||
var histDir = DocManagerHelper.HistoryDir(storagePath); // get the path to the history directory
|
||||
if (!Directory.Exists(histDir)) Directory.CreateDirectory(histDir);
|
||||
|
||||
var versionDir = DocManagerHelper.VersionDir(histDir, DocManagerHelper.GetFileVersion(histDir)); // get the path to the file version
|
||||
if (!Directory.Exists(versionDir)) Directory.CreateDirectory(versionDir); // if the path doesn't exist, create it
|
||||
|
||||
// get the path to the previous file version and move it to the storage directory
|
||||
File.Move(DocManagerHelper.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));
|
||||
|
||||
DownloadToFile(downloadUri, storagePath); // save file to the storage directory
|
||||
DownloadToFile((string)fileData["changesurl"], Path.Combine(versionDir, "diff.zip")); // save file changes to the diff.zip archive
|
||||
|
||||
var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;
|
||||
if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
|
||||
try
|
||||
{
|
||||
var jss = new JavaScriptSerializer();
|
||||
hist = jss.Serialize(fileData["history"]);
|
||||
}
|
||||
var bytesFile = DownloadFile(downloadUri); // download document file
|
||||
var storagePath = DocManagerHelper.StoragePath(newFileName, userAddress); // get the file path
|
||||
|
||||
if (!string.IsNullOrEmpty(hist))
|
||||
var histDir = DocManagerHelper.HistoryDir(storagePath); // get the path to the history directory
|
||||
if (!Directory.Exists(histDir)) Directory.CreateDirectory(histDir);
|
||||
|
||||
var versionDir = DocManagerHelper.VersionDir(histDir, DocManagerHelper.GetFileVersion(histDir)); // get the path to the file version
|
||||
if (!Directory.Exists(versionDir)) Directory.CreateDirectory(versionDir); // if the path doesn't exist, create it
|
||||
|
||||
// get the path to the previous file version and move it to the storage directory
|
||||
File.Move(DocManagerHelper.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));
|
||||
|
||||
SaveFile(bytesFile, storagePath);// save document file
|
||||
|
||||
byte[] bytesChanges = DownloadFile((string)fileData["changesurl"]); // download changes file
|
||||
SaveFile(bytesChanges, Path.Combine(versionDir, "diff.zip")); // save file changes to the diff.zip archive
|
||||
|
||||
var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;
|
||||
if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
|
||||
{
|
||||
var jss = new JavaScriptSerializer();
|
||||
hist = jss.Serialize(fileData["history"]);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(hist))
|
||||
{
|
||||
File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist); // write the history changes to the changes.json file
|
||||
}
|
||||
|
||||
File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]); // write the key value to the key.txt file
|
||||
|
||||
string forcesavePath = DocManagerHelper.ForcesavePath(newFileName, userAddress, false); // get the path to the forcesaved file version
|
||||
if (!forcesavePath.Equals("")) // if the forcesaved file version exists
|
||||
{
|
||||
File.Delete(forcesavePath); // remove it
|
||||
}
|
||||
|
||||
} catch (Exception)
|
||||
{
|
||||
File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist); // write the history changes to the changes.json file
|
||||
}
|
||||
|
||||
File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]); // write the key value to the key.txt file
|
||||
|
||||
string forcesavePath = DocManagerHelper.ForcesavePath(newFileName, userAddress, false); // get the path to the forcesaved file version
|
||||
if (!forcesavePath.Equals("")) // if the forcesaved file version exists
|
||||
{
|
||||
File.Delete(forcesavePath); // remove it
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
@ -176,9 +185,7 @@ namespace OnlineEditorsExampleMVC.Helpers
|
||||
|
||||
string curExt = Path.GetExtension(fileName).ToLower(); // get current file extension
|
||||
|
||||
var downloadExt = fileData.ContainsKey("filetype")
|
||||
? "." + (string)fileData["filetype"]
|
||||
: Path.GetExtension(downloadUri).ToLower(); // TODO: Delete in version 7.0 or higher. Support for versions below 7.0
|
||||
var downloadExt = "." + (string)fileData["filetype"]; // get the extension of the downloaded file
|
||||
|
||||
Boolean newFileName = false;
|
||||
|
||||
@ -206,43 +213,51 @@ namespace OnlineEditorsExampleMVC.Helpers
|
||||
}
|
||||
|
||||
DocManagerHelper.VerifySSL();
|
||||
|
||||
string forcesavePath = "";
|
||||
Boolean isSubmitForm = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm
|
||||
|
||||
if (isSubmitForm) // if the form is submitted
|
||||
try
|
||||
{
|
||||
if (newFileName)
|
||||
var bytesFile = DownloadFile(downloadUri); // download document file
|
||||
|
||||
string forcesavePath = "";
|
||||
Boolean isSubmitForm = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm
|
||||
|
||||
if (isSubmitForm) // if the form is submitted
|
||||
{
|
||||
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress); // get the correct file name if it already exists
|
||||
if (newFileName)
|
||||
{
|
||||
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress); // get the correct file name if it already exists
|
||||
} else
|
||||
{
|
||||
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + curExt, userAddress);
|
||||
{
|
||||
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + curExt, userAddress);
|
||||
}
|
||||
forcesavePath = DocManagerHelper.StoragePath(fileName, userAddress);
|
||||
}
|
||||
forcesavePath = DocManagerHelper.StoragePath(fileName, userAddress);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (newFileName)
|
||||
else
|
||||
{
|
||||
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
|
||||
}
|
||||
forcesavePath = DocManagerHelper.ForcesavePath(fileName, userAddress, false);
|
||||
if (newFileName)
|
||||
{
|
||||
fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
|
||||
}
|
||||
forcesavePath = DocManagerHelper.ForcesavePath(fileName, userAddress, false);
|
||||
if (string.IsNullOrEmpty(forcesavePath)) // create forcesave path if it doesn't exist
|
||||
{
|
||||
forcesavePath = DocManagerHelper.ForcesavePath(fileName, userAddress, true);
|
||||
{
|
||||
forcesavePath = DocManagerHelper.ForcesavePath(fileName, userAddress, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DownloadToFile(downloadUri, forcesavePath);
|
||||
SaveFile(bytesFile, forcesavePath);// save document file
|
||||
|
||||
if (isSubmitForm)
|
||||
if (isSubmitForm)
|
||||
{
|
||||
var jss = new JavaScriptSerializer();
|
||||
var actions = jss.Deserialize<List<object>>(jss.Serialize(fileData["actions"]));
|
||||
var action = jss.Deserialize<Dictionary<string, object>>(jss.Serialize(actions[0]));
|
||||
var user = action["userid"].ToString(); // get the user id
|
||||
DocManagerHelper.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for the forcesaved file
|
||||
}
|
||||
} catch (Exception)
|
||||
{
|
||||
var jss = new JavaScriptSerializer();
|
||||
var actions = jss.Deserialize<List<object>>(jss.Serialize(fileData["actions"]));
|
||||
var action = jss.Deserialize<Dictionary<string, object>>(jss.Serialize(actions[0]));
|
||||
var user = action["userid"].ToString(); // get the user id
|
||||
DocManagerHelper.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for the forcesaved file
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
@ -314,27 +329,30 @@ namespace OnlineEditorsExampleMVC.Helpers
|
||||
}
|
||||
}
|
||||
|
||||
// save file
|
||||
private static void SaveFile(byte[] data, string path)
|
||||
{
|
||||
using (var fs = File.Open(path, FileMode.Create))
|
||||
{
|
||||
fs.Write(data, 0, data.Length);
|
||||
}
|
||||
}
|
||||
|
||||
// save file information from the url to the file specified
|
||||
private static void DownloadToFile(string url, string path)
|
||||
private static byte[] DownloadFile(string url)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url)) throw new ArgumentException("url"); // url isn't specified
|
||||
if (string.IsNullOrEmpty(path)) throw new ArgumentException("path"); // file isn't specified
|
||||
|
||||
var req = (HttpWebRequest)WebRequest.Create(url);
|
||||
req.Timeout = 5000;
|
||||
using (var stream = req.GetResponse().GetResponseStream()) // get input stream of the file information from the url
|
||||
{
|
||||
if (stream == null) throw new Exception("stream is null");
|
||||
const int bufferSize = 4096;
|
||||
|
||||
using (var fs = File.Open(path, FileMode.Create))
|
||||
using (MemoryStream memoryStream = new MemoryStream())
|
||||
{
|
||||
var buffer = new byte[bufferSize];
|
||||
int readed;
|
||||
while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
|
||||
{
|
||||
fs.Write(buffer, 0, readed); // write bytes to the output stream
|
||||
}
|
||||
stream.CopyTo(memoryStream);
|
||||
return memoryStream.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -461,20 +461,21 @@ namespace OnlineEditorsExampleMVC
|
||||
var userAddress = context.Request["userAddress"];
|
||||
var isEmbedded = context.Request["dmode"];
|
||||
|
||||
if (JwtManager.Enabled && isEmbedded == null)
|
||||
if (JwtManager.Enabled && isEmbedded == null && userAddress != null)
|
||||
{
|
||||
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
|
||||
|
||||
string token = "";
|
||||
if (context.Request.Headers.AllKeys.Contains(JWTheader, StringComparer.InvariantCultureIgnoreCase))
|
||||
{
|
||||
var headerToken = context.Request.Headers.Get(JWTheader).Substring("Bearer ".Length);
|
||||
string token = JwtManager.Decode(headerToken);
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
|
||||
context.Response.Write("JWT validation failed");
|
||||
return;
|
||||
}
|
||||
token = JwtManager.Decode(headerToken);
|
||||
}
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
|
||||
context.Response.Write("JWT validation failed");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
<?xml version="1.0"?>
|
||||
<appSettings>
|
||||
<clear />
|
||||
<add key="version" value="1.4.0"/>
|
||||
<add key="version" value="1.5.0"/>
|
||||
|
||||
<add key="filesize-max" value="52428800"/>
|
||||
<add key="storage-path" value=""/>
|
||||
|
||||
@ -100,9 +100,7 @@ namespace OnlineEditorsExample
|
||||
var downloadUri = (string)fileData["url"];
|
||||
var curExt = Path.GetExtension(fileName).ToLower(); // get current file extension
|
||||
|
||||
var downloadExt = fileData.ContainsKey("filetype")
|
||||
? "." + (string)fileData["filetype"]
|
||||
: Path.GetExtension(downloadUri).ToLower() ?? ""; // TODO: Delete in version 7.0 or higher. Support for versions below 7.0
|
||||
var downloadExt = "." + (string)fileData["filetype"]; // get the extension of the downloaded file
|
||||
|
||||
var newFileName = fileName;
|
||||
|
||||
@ -132,37 +130,48 @@ namespace OnlineEditorsExample
|
||||
|
||||
_Default.VerifySSL();
|
||||
|
||||
var storagePath = _Default.StoragePath(newFileName, userAddress); // get the file path
|
||||
var histDir = _Default.HistoryDir(storagePath); // get the path to the history directory
|
||||
if (!Directory.Exists(histDir)) Directory.CreateDirectory(histDir);
|
||||
|
||||
var versionDir = _Default.VersionDir(histDir, _Default.GetFileVersion(histDir)); // get the path to the file version
|
||||
if (!Directory.Exists(versionDir)) Directory.CreateDirectory(versionDir); // if the path doesn't exist, create it
|
||||
|
||||
// get the path to the previous file version and rename the storage path with it
|
||||
File.Copy(_Default.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));
|
||||
|
||||
DownloadToFile(downloadUri, storagePath); // save file to the storage directory
|
||||
DownloadToFile((string)fileData["changesurl"], Path.Combine(versionDir, "diff.zip")); // save file changes to the diff.zip archive
|
||||
|
||||
var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;
|
||||
if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
|
||||
try
|
||||
{
|
||||
var jss = new JavaScriptSerializer();
|
||||
hist = jss.Serialize(fileData["history"]);
|
||||
}
|
||||
var bytesFile = DownloadFile(downloadUri); // download document file
|
||||
var storagePath = _Default.StoragePath(newFileName, userAddress); // get the file path
|
||||
|
||||
if (!string.IsNullOrEmpty(hist))
|
||||
{
|
||||
File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist); // write the history changes to the changes.json file
|
||||
}
|
||||
var histDir = _Default.HistoryDir(storagePath); // get the path to the history directory
|
||||
if (!Directory.Exists(histDir)) Directory.CreateDirectory(histDir);
|
||||
|
||||
File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]); // write the key value to the key.txt file
|
||||
var versionDir = _Default.VersionDir(histDir, _Default.GetFileVersion(histDir)); // get the path to the file version
|
||||
if (!Directory.Exists(versionDir)) Directory.CreateDirectory(versionDir); // if the path doesn't exist, create it
|
||||
|
||||
string forcesavePath = _Default.ForcesavePath(newFileName, userAddress, false); // get the path to the forcesaved file version
|
||||
// get the path to the previous file version and rename the storage path with it
|
||||
File.Copy(_Default.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));
|
||||
|
||||
SaveFile(bytesFile, storagePath);// save document file
|
||||
|
||||
var bytesChanges = DownloadFile((string)fileData["changesurl"]); // download changes file
|
||||
SaveFile(bytesChanges, Path.Combine(versionDir, "diff.zip")); // save file changes to the diff.zip archive
|
||||
|
||||
var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;
|
||||
if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
|
||||
{
|
||||
var jss = new JavaScriptSerializer();
|
||||
hist = jss.Serialize(fileData["history"]);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(hist))
|
||||
{
|
||||
File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist); // write the history changes to the changes.json file
|
||||
}
|
||||
|
||||
File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]); // write the key value to the key.txt file
|
||||
|
||||
string forcesavePath = _Default.ForcesavePath(newFileName, userAddress, false); // get the path to the forcesaved file version
|
||||
if (!string.IsNullOrEmpty(forcesavePath)) // if the forcesaved file version exists
|
||||
{
|
||||
File.Delete(forcesavePath); // remove it
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
File.Delete(forcesavePath); // remove it
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
@ -178,9 +187,7 @@ namespace OnlineEditorsExample
|
||||
|
||||
string curExt = Path.GetExtension(fileName).ToLower(); // get current file extension
|
||||
|
||||
var downloadExt = fileData.ContainsKey("filetype")
|
||||
? "." + (string)fileData["filetype"]
|
||||
: Path.GetExtension(downloadUri).ToLower(); // TODO: Delete in version 7.0 or higher. Support for versions below 7.0
|
||||
var downloadExt = "." + (string)fileData["filetype"]; // get the extension of the downloaded file
|
||||
|
||||
Boolean newFileName = false;
|
||||
|
||||
@ -209,43 +216,51 @@ namespace OnlineEditorsExample
|
||||
|
||||
_Default.VerifySSL();
|
||||
|
||||
string forcesavePath = "";
|
||||
Boolean isSubmitForm = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm
|
||||
|
||||
if (isSubmitForm) // if the form is submitted
|
||||
try
|
||||
{
|
||||
if (newFileName)
|
||||
var bytesFile = DownloadFile(downloadUri); // download document file
|
||||
string forcesavePath = "";
|
||||
Boolean isSubmitForm = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm
|
||||
|
||||
if (isSubmitForm) // if the form is submitted
|
||||
{
|
||||
fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress); // get the correct file name if it already exists
|
||||
if (newFileName)
|
||||
{
|
||||
fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress); // get the correct file name if it already exists
|
||||
} else
|
||||
{
|
||||
fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + curExt, userAddress);
|
||||
{
|
||||
fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + curExt, userAddress);
|
||||
}
|
||||
forcesavePath = _Default.StoragePath(fileName, userAddress);
|
||||
}
|
||||
forcesavePath = _Default.StoragePath(fileName, userAddress);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (newFileName)
|
||||
else
|
||||
{
|
||||
fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
|
||||
}
|
||||
if (newFileName)
|
||||
{
|
||||
fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
|
||||
}
|
||||
|
||||
forcesavePath = _Default.ForcesavePath(fileName, userAddress, false);
|
||||
forcesavePath = _Default.ForcesavePath(fileName, userAddress, false);
|
||||
if (string.IsNullOrEmpty(forcesavePath)) // create forcesave path if it doesn't exist
|
||||
{
|
||||
forcesavePath = _Default.ForcesavePath(fileName, userAddress, true);
|
||||
}
|
||||
}
|
||||
|
||||
SaveFile(bytesFile, forcesavePath);// save document file
|
||||
|
||||
if (isSubmitForm)
|
||||
{
|
||||
forcesavePath = _Default.ForcesavePath(fileName, userAddress, true);
|
||||
var jss = new JavaScriptSerializer();
|
||||
var actions = jss.Deserialize<List<object>>(jss.Serialize(fileData["actions"]));
|
||||
var action = jss.Deserialize<Dictionary<string, object>>(jss.Serialize(actions[0]));
|
||||
var user = action["userid"].ToString(); // get the user id
|
||||
DocEditor.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for the forcesaved file
|
||||
}
|
||||
}
|
||||
|
||||
DownloadToFile(downloadUri, forcesavePath);
|
||||
|
||||
if (isSubmitForm)
|
||||
catch (Exception)
|
||||
{
|
||||
var jss = new JavaScriptSerializer();
|
||||
var actions = jss.Deserialize<List<object>>(jss.Serialize(fileData["actions"]));
|
||||
var action = jss.Deserialize<Dictionary<string, object>>(jss.Serialize(actions[0]));
|
||||
var user = action["userid"].ToString(); // get the user id
|
||||
DocEditor.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for the forcesaved file
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
@ -317,27 +332,29 @@ namespace OnlineEditorsExample
|
||||
}
|
||||
}
|
||||
|
||||
private static void SaveFile(byte[] data, string path)
|
||||
{
|
||||
using (var fs = File.Open(path, FileMode.Create))
|
||||
{
|
||||
fs.Write(data, 0, data.Length);
|
||||
}
|
||||
}
|
||||
|
||||
// save file information from the url to the file specified
|
||||
private static void DownloadToFile(string url, string path)
|
||||
private static byte[] DownloadFile(string url)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url)) throw new ArgumentException("url"); // url isn't specified
|
||||
if (string.IsNullOrEmpty(path)) throw new ArgumentException("path"); // file isn't specified
|
||||
|
||||
var req = (HttpWebRequest)WebRequest.Create(url);
|
||||
req.Timeout = 5000;
|
||||
using (var stream = req.GetResponse().GetResponseStream()) // get input stream of the file information from the url
|
||||
{
|
||||
if (stream == null) throw new Exception("stream is null");
|
||||
const int bufferSize = 4096;
|
||||
|
||||
using (var fs = File.Open(path, FileMode.Create))
|
||||
using (MemoryStream memoryStream = new MemoryStream())
|
||||
{
|
||||
var buffer = new byte[bufferSize];
|
||||
int readed;
|
||||
while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
|
||||
{
|
||||
fs.Write(buffer, 0, readed); // write bytes to the output stream
|
||||
}
|
||||
stream.CopyTo(memoryStream);
|
||||
return memoryStream.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -281,21 +281,21 @@ namespace OnlineEditorsExample
|
||||
var userAddress = Path.GetFileName(context.Request["userAddress"]);
|
||||
var isEmbedded = context.Request["dmode"];
|
||||
|
||||
if (JwtManager.Enabled && isEmbedded == null)
|
||||
if (JwtManager.Enabled && isEmbedded == null && userAddress != null)
|
||||
{
|
||||
string JWTheader = string.IsNullOrEmpty(WebConfigurationManager.AppSettings["files.docservice.header"]) ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
|
||||
|
||||
string token = "";
|
||||
if (context.Request.Headers.AllKeys.Contains(JWTheader, StringComparer.InvariantCultureIgnoreCase))
|
||||
{
|
||||
var headerToken = context.Request.Headers.Get(JWTheader).Substring("Bearer ".Length);
|
||||
string token = JwtManager.Decode(headerToken);
|
||||
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
|
||||
context.Response.Write("JWT validation failed");
|
||||
return;
|
||||
}
|
||||
token = JwtManager.Decode(headerToken);
|
||||
}
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
|
||||
context.Response.Write("JWT validation failed");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<appSettings>
|
||||
<clear />
|
||||
<add key="version" value="1.4.0"/>
|
||||
<add key="version" value="1.5.0"/>
|
||||
|
||||
<add key="filesize-max" value="52428800"/>
|
||||
<add key="storage-path" value=""/>
|
||||
|
||||
@ -139,11 +139,11 @@ See the detailed guide to learn how to install Document Server [for Linux](https
|
||||
a) archive with Java-Spring:
|
||||
|
||||
```
|
||||
wget https://api.onlyoffice.com/app_data/editor/Java-Spring%20Example.zip
|
||||
wget https://api.onlyoffice.com/app_data/editor/Java%20Spring%20Example.zip
|
||||
```
|
||||
|
||||
```
|
||||
unzip Java-Spring\ Example.zip
|
||||
unzip Java\ Spring\ Example.zip
|
||||
```
|
||||
b) git repository:
|
||||
```
|
||||
@ -156,7 +156,7 @@ See the detailed guide to learn how to install Document Server [for Linux](https
|
||||
a) from archive
|
||||
|
||||
```
|
||||
cd Java-Spring\ Example/
|
||||
cd Java\ Spring\ Example/
|
||||
```
|
||||
b) from git repository
|
||||
```
|
||||
|
||||
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0"?>
|
||||
<!DOCTYPE suppressions PUBLIC
|
||||
"-//Checkstyle//DTD SuppressionFilter Configuration 1.0//EN"
|
||||
"https://checkstyle.org/dtds/suppressions_1_0.dtd">
|
||||
|
||||
<suppressions>
|
||||
<suppress checks="HideUtilityClassConstructor" files="IntegrationApplication.java"/>
|
||||
<suppress checks="DesignForExtension" files="."/>
|
||||
<suppress checks="ParameterNumber" files="."/>
|
||||
<suppress checks="JavadocPackage" files="."/>
|
||||
<suppress checks="JavadocVariable" files="."/>
|
||||
<suppress checks="MissingJavadocMethod" files="."/>
|
||||
</suppressions>
|
||||
199
web/documentserver-example/java-spring/checkstyle.xml
Normal file
199
web/documentserver-example/java-spring/checkstyle.xml
Normal file
@ -0,0 +1,199 @@
|
||||
<?xml version="1.0"?>
|
||||
<!DOCTYPE module PUBLIC
|
||||
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
|
||||
"https://checkstyle.org/dtds/configuration_1_3.dtd">
|
||||
|
||||
<!--
|
||||
|
||||
Checkstyle configuration that checks the sun coding conventions from:
|
||||
|
||||
- the Java Language Specification at
|
||||
https://docs.oracle.com/javase/specs/jls/se11/html/index.html
|
||||
|
||||
- the Sun Code Conventions at https://www.oracle.com/java/technologies/javase/codeconventions-contents.html
|
||||
|
||||
- the Javadoc guidelines at
|
||||
https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html
|
||||
|
||||
- the JDK Api documentation https://docs.oracle.com/en/java/javase/11/
|
||||
|
||||
- some best practices
|
||||
|
||||
Checkstyle is very configurable. Be sure to read the documentation at
|
||||
https://checkstyle.org (or in your downloaded distribution).
|
||||
|
||||
Most Checks are configurable, be sure to consult the documentation.
|
||||
|
||||
To completely disable a check, just comment it out or delete it from the file.
|
||||
To suppress certain violations please review suppression filters.
|
||||
|
||||
Finally, it is worth reading the documentation.
|
||||
|
||||
-->
|
||||
|
||||
<module name="Checker">
|
||||
<!--
|
||||
If you set the basedir property below, then all reported file
|
||||
names will be relative to the specified directory. See
|
||||
https://checkstyle.org/config.html#Checker
|
||||
|
||||
<property name="basedir" value="${basedir}"/>
|
||||
-->
|
||||
<property name="severity" value="error"/>
|
||||
|
||||
<property name="fileExtensions" value="java, properties, xml"/>
|
||||
|
||||
<!-- Excludes all 'module-info.java' files -->
|
||||
<!-- See https://checkstyle.org/config_filefilters.html -->
|
||||
<module name="BeforeExecutionExclusionFileFilter">
|
||||
<property name="fileNamePattern" value="module\-info\.java$"/>
|
||||
</module>
|
||||
|
||||
<!-- https://checkstyle.org/config_filters.html#SuppressionFilter -->
|
||||
<module name="SuppressionFilter">
|
||||
<property name="file" value="${org.checkstyle.sun.suppressionfilter.config}"
|
||||
default="checkstyle-suppressions.xml" />
|
||||
<property name="optional" value="true"/>
|
||||
</module>
|
||||
|
||||
<!-- Checks that a package-info.java file exists for each package. -->
|
||||
<!-- See https://checkstyle.org/config_javadoc.html#JavadocPackage -->
|
||||
<module name="JavadocPackage"/>
|
||||
|
||||
<!-- Checks whether files end with a new line. -->
|
||||
<!-- See https://checkstyle.org/config_misc.html#NewlineAtEndOfFile -->
|
||||
<module name="NewlineAtEndOfFile"/>
|
||||
|
||||
<!-- Checks that property files contain the same keys. -->
|
||||
<!-- See https://checkstyle.org/config_misc.html#Translation -->
|
||||
<module name="Translation"/>
|
||||
|
||||
<!-- Checks for Size Violations. -->
|
||||
<!-- See https://checkstyle.org/config_sizes.html -->
|
||||
<module name="FileLength"/>
|
||||
<module name="LineLength">
|
||||
<property name="fileExtensions" value="java"/>
|
||||
<property name="max" value="120"/>
|
||||
</module>
|
||||
|
||||
<!-- Checks for whitespace -->
|
||||
<!-- See https://checkstyle.org/config_whitespace.html -->
|
||||
<module name="FileTabCharacter"/>
|
||||
|
||||
<!-- Miscellaneous other checks. -->
|
||||
<!-- See https://checkstyle.org/config_misc.html -->
|
||||
<module name="RegexpSingleline">
|
||||
<property name="format" value="\s+$"/>
|
||||
<property name="minimum" value="0"/>
|
||||
<property name="maximum" value="0"/>
|
||||
<property name="message" value="Line has trailing spaces."/>
|
||||
</module>
|
||||
|
||||
<!-- Checks for Headers -->
|
||||
<!-- See https://checkstyle.org/config_header.html -->
|
||||
<module name="Header">
|
||||
<property name="headerFile" value="onlyoffice.header"/>
|
||||
<property name="fileExtensions" value="java"/>
|
||||
</module>
|
||||
|
||||
<module name="TreeWalker">
|
||||
|
||||
<!-- Checks for Javadoc comments. -->
|
||||
<!-- See https://checkstyle.org/config_javadoc.html -->
|
||||
<module name="InvalidJavadocPosition"/>
|
||||
<module name="JavadocMethod"/>
|
||||
<module name="JavadocType"/>
|
||||
<module name="JavadocVariable"/>
|
||||
<module name="JavadocStyle"/>
|
||||
<module name="MissingJavadocMethod"/>
|
||||
|
||||
<!-- Checks for Naming Conventions. -->
|
||||
<!-- See https://checkstyle.org/config_naming.html -->
|
||||
<module name="ConstantName"/>
|
||||
<module name="LocalFinalVariableName"/>
|
||||
<module name="LocalVariableName"/>
|
||||
<module name="MemberName"/>
|
||||
<module name="MethodName"/>
|
||||
<module name="PackageName"/>
|
||||
<module name="ParameterName"/>
|
||||
<module name="StaticVariableName"/>
|
||||
<module name="TypeName"/>
|
||||
|
||||
<!-- Checks for imports -->
|
||||
<!-- See https://checkstyle.org/config_imports.html -->
|
||||
<module name="AvoidStarImport"/>
|
||||
<module name="IllegalImport"/> <!-- defaults to sun.* packages -->
|
||||
<module name="RedundantImport"/>
|
||||
<module name="UnusedImports">
|
||||
<property name="processJavadoc" value="false"/>
|
||||
</module>
|
||||
|
||||
<!-- Checks for Size Violations. -->
|
||||
<!-- See https://checkstyle.org/config_sizes.html -->
|
||||
<module name="MethodLength"/>
|
||||
<module name="ParameterNumber"/>
|
||||
|
||||
<!-- Checks for whitespace -->
|
||||
<!-- See https://checkstyle.org/config_whitespace.html -->
|
||||
<module name="EmptyForIteratorPad"/>
|
||||
<module name="GenericWhitespace"/>
|
||||
<module name="MethodParamPad"/>
|
||||
<module name="NoWhitespaceAfter"/>
|
||||
<module name="NoWhitespaceBefore"/>
|
||||
<module name="OperatorWrap"/>
|
||||
<module name="ParenPad"/>
|
||||
<module name="TypecastParenPad"/>
|
||||
<module name="WhitespaceAfter"/>
|
||||
<module name="WhitespaceAround"/>
|
||||
|
||||
<!-- Modifier Checks -->
|
||||
<!-- See https://checkstyle.org/config_modifier.html -->
|
||||
<module name="ModifierOrder"/>
|
||||
<module name="RedundantModifier"/>
|
||||
|
||||
<!-- Checks for blocks. You know, those {}'s -->
|
||||
<!-- See https://checkstyle.org/config_blocks.html -->
|
||||
<module name="AvoidNestedBlocks"/>
|
||||
<module name="EmptyBlock"/>
|
||||
<module name="LeftCurly"/>
|
||||
<module name="NeedBraces"/>
|
||||
<module name="RightCurly"/>
|
||||
|
||||
<!-- Checks for common coding problems -->
|
||||
<!-- See https://checkstyle.org/config_coding.html -->
|
||||
<module name="EmptyStatement"/>
|
||||
<module name="EqualsHashCode"/>
|
||||
<module name="HiddenField"/>
|
||||
<module name="IllegalInstantiation"/>
|
||||
<module name="InnerAssignment"/>
|
||||
<module name="MagicNumber"/>
|
||||
<module name="MissingSwitchDefault"/>
|
||||
<module name="MultipleVariableDeclarations"/>
|
||||
<module name="SimplifyBooleanExpression"/>
|
||||
<module name="SimplifyBooleanReturn"/>
|
||||
|
||||
<!-- Checks for class design -->
|
||||
<!-- See https://checkstyle.org/config_design.html -->
|
||||
<module name="DesignForExtension"/>
|
||||
<module name="FinalClass"/>
|
||||
<module name="HideUtilityClassConstructor"/>
|
||||
<module name="InterfaceIsType"/>
|
||||
<module name="VisibilityModifier"/>
|
||||
|
||||
<!-- Miscellaneous other checks. -->
|
||||
<!-- See https://checkstyle.org/config_misc.html -->
|
||||
<module name="ArrayTypeStyle"/>
|
||||
<module name="FinalParameters"/>
|
||||
<module name="TodoComment"/>
|
||||
<module name="UpperEll"/>
|
||||
|
||||
<!-- https://checkstyle.org/config_filters.html#SuppressionXpathFilter -->
|
||||
<module name="SuppressionXpathFilter">
|
||||
<property name="file" value="${org.checkstyle.sun.suppressionxpathfilter.config}"
|
||||
default="checkstyle-xpath-suppressions.xml" />
|
||||
<property name="optional" value="true"/>
|
||||
</module>
|
||||
|
||||
</module>
|
||||
|
||||
</module>
|
||||
17
web/documentserver-example/java-spring/onlyoffice.header
Normal file
17
web/documentserver-example/java-spring/onlyoffice.header
Normal file
@ -0,0 +1,17 @@
|
||||
/**
|
||||
*
|
||||
* (c) Copyright Ascensio System SIA 2023
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
@ -35,6 +35,14 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
@ -86,14 +94,13 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-checkstyle-plugin</artifactId>
|
||||
<version>2.17</version>
|
||||
<version>3.2.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>validate</id>
|
||||
<phase>validate</phase>
|
||||
<configuration>
|
||||
<configLocation>google_checks.xml</configLocation>
|
||||
<encoding>UTF-8</encoding>
|
||||
<configLocation>checkstyle.xml</configLocation>
|
||||
<failsOnError>true</failsOnError>
|
||||
<failOnViolation>true</failOnViolation>
|
||||
<logViolationsToConsole>true</logViolationsToConsole>
|
||||
|
||||
@ -32,8 +32,9 @@ public class ExampleData {
|
||||
@Autowired
|
||||
private UserServices userService;
|
||||
@PostConstruct
|
||||
public void init(){
|
||||
List<String> description_user_0=List.of( // the description for user 0
|
||||
public void init() {
|
||||
// the description for user 0
|
||||
List<String> descriptionUserZero = List.of(
|
||||
"The name is requested when the editor is opened",
|
||||
"Doesn’t belong to any group",
|
||||
"Can review all the changes",
|
||||
@ -46,7 +47,9 @@ public class ExampleData {
|
||||
"Can't view chat",
|
||||
"View file without collaboration"
|
||||
);
|
||||
List<String> description_user_1 = List.of( // the description for user 1
|
||||
|
||||
// the description for user 1
|
||||
List<String> descriptionUserFirst = List.of(
|
||||
"File author by default",
|
||||
"He doesn’t belong to any of the groups",
|
||||
"He can review all the changes",
|
||||
@ -56,19 +59,26 @@ public class ExampleData {
|
||||
"Can see the information about all users",
|
||||
"Can view chat"
|
||||
);
|
||||
List<String> description_user_2 = List.of( // the description for user 2
|
||||
|
||||
// the description for user 2
|
||||
List<String> descriptionUserSecond = List.of(
|
||||
"He belongs to Group2",
|
||||
"He can review only his own changes or the changes made by the users who don’t belong to any of the groups",
|
||||
"He can view every comment, edit his comments and the comments left by the users who don't belong to any of the groups and remove only his comments",
|
||||
"He can review only his own changes or the changes made by the users who don’t belong"
|
||||
+ " to any of the groups",
|
||||
"He can view every comment, edit his comments and the comments left by the users "
|
||||
+ "who don't belong to any of the groups and remove only his comments",
|
||||
"This file is favorite",
|
||||
"Can create a file from an editor",
|
||||
"Can see the information about users from Group2 and users who don’t belong to any group",
|
||||
"Can view chat"
|
||||
);
|
||||
List<String> description_user_3 = List.of( // the description for user 3
|
||||
|
||||
// the description for user 3
|
||||
List<String> descriptionUserThird = List.of(
|
||||
"He belongs to Group3",
|
||||
"He can review only the changes made by the users from Group2",
|
||||
"He can view the comments left by the users from Group2 and Group3 and edit the comments left by the users from Group2",
|
||||
"He can view the comments left by the users from Group2 and Group3 and edit the comments left by "
|
||||
+ "the users from Group2",
|
||||
"This file isn’t favorite",
|
||||
"He can’t copy data from the file into the clipboard",
|
||||
"He can’t download the file",
|
||||
@ -77,24 +87,27 @@ public class ExampleData {
|
||||
"Can see the information about Group2 users",
|
||||
"Can view chat"
|
||||
);
|
||||
userService.createUser("John Smith", "smith@example.com", // create user 1 with the specified parameters
|
||||
description_user_1, "", List.of(FilterState.NULL.toString()),
|
||||
List.of(FilterState.NULL.toString()),
|
||||
List.of(FilterState.NULL.toString()),
|
||||
List.of(FilterState.NULL.toString()),
|
||||
List.of(FilterState.NULL.toString()),
|
||||
null, true);
|
||||
userService.createUser("Mark Pottato", "pottato@example.com", // create user 2 with the specified parameters
|
||||
description_user_2, "group-2", List.of("","group-2"), List.of(FilterState.NULL.toString()),
|
||||
List.of("group-2", ""), List.of("group-2"), List.of("group-2", ""), true,
|
||||
true);
|
||||
userService.createUser("Hamish Mitchell", "mitchell@example.com", // create user 3 with the specified parameters
|
||||
description_user_3, "group-3", List.of("group-2"), List.of("group-2", "group-3"),
|
||||
List.of("group-2"), new ArrayList<>(), List.of("group-2"), false,
|
||||
true);
|
||||
userService.createUser("Anonymous",null, // create user 0 with the specified parameters
|
||||
description_user_0,"", List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
|
||||
List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()), new ArrayList<>(),null,
|
||||
false);
|
||||
|
||||
// create user 1 with the specified parameters
|
||||
userService.createUser("John Smith", "smith@example.com", descriptionUserFirst,
|
||||
"", List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
|
||||
List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
|
||||
List.of(FilterState.NULL.toString()), null, true);
|
||||
|
||||
// create user 2 with the specified parameters
|
||||
userService.createUser("Mark Pottato", "pottato@example.com", descriptionUserSecond,
|
||||
"group-2", List.of("", "group-2"), List.of(FilterState.NULL.toString()),
|
||||
List.of("group-2", ""), List.of("group-2"), List.of("group-2", ""), true, true);
|
||||
|
||||
// create user 3 with the specified parameters
|
||||
userService.createUser("Hamish Mitchell", "mitchell@example.com", descriptionUserThird,
|
||||
"group-3", List.of("group-2"), List.of("group-2", "group-3"), List.of("group-2"),
|
||||
new ArrayList<>(), List.of("group-2"), false, true);
|
||||
|
||||
// create user 0 with the specified parameters
|
||||
userService.createUser("Anonymous", null, descriptionUserZero, "",
|
||||
List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
|
||||
List.of(FilterState.NULL.toString()), List.of(FilterState.NULL.toString()),
|
||||
new ArrayList<>(), null, false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -24,9 +24,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@SpringBootApplication
|
||||
public class IntegrationApplication {
|
||||
|
||||
// run the SpringApplication from the IntagrationApplication with the specified parameters
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(IntegrationApplication.class, args);
|
||||
}
|
||||
// run the SpringApplication from the IntagrationApplication with the specified parameters
|
||||
public static void main(final String[] args) {
|
||||
SpringApplication.run(IntegrationApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -48,39 +48,40 @@ public class IntegrationConfiguration {
|
||||
private SSLUtils ssl;
|
||||
|
||||
@Bean
|
||||
public ModelMapper mapper(){ // create the model mapper
|
||||
public ModelMapper mapper() { // create the model mapper
|
||||
ModelMapper mapper = new ModelMapper();
|
||||
mapper.getConfiguration() // get the mapper configuration and set new parameters to it
|
||||
.setMatchingStrategy(MatchingStrategies.STRICT) // specify the STRICT matching strategy
|
||||
.setFieldMatchingEnabled(true) // define if the field matching is enabled or not
|
||||
.setSkipNullEnabled(true) // define if null value will be skipped or not
|
||||
.setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); // specify the PRIVATE field access level
|
||||
.setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE); /* specify
|
||||
the PRIVATE field access level */
|
||||
return mapper;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JSONParser jsonParser(){ // create JSON parser
|
||||
public JSONParser jsonParser() { // create JSON parser
|
||||
return new JSONParser();
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void init(){ // initialize the storage path builder
|
||||
public void init() { // initialize the storage path builder
|
||||
storagePathBuilder.configure(storageAddress.isBlank() ? null : storageAddress);
|
||||
if(!verifyPerrOff.isEmpty()) {
|
||||
try{
|
||||
if(verifyPerrOff.equals("true")) {
|
||||
if (!verifyPerrOff.isEmpty()) {
|
||||
try {
|
||||
if (verifyPerrOff.equals("true")) {
|
||||
ssl.turnOffSslChecking(); //the certificate will be ignored
|
||||
} else {
|
||||
ssl.turnOnSslChecking(); //the certificate will be verified
|
||||
}
|
||||
} catch(Exception e) {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ObjectMapper objectMapper(){ // create the object mapper
|
||||
public ObjectMapper objectMapper() { // create the object mapper
|
||||
return new ObjectMapper();
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,37 @@
|
||||
/**
|
||||
*
|
||||
* (c) Copyright Ascensio System SIA 2023
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.onlyoffice.integration.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(final HttpSecurity http) throws Exception {
|
||||
return http
|
||||
.requiresChannel(channel -> channel.anyRequest().requiresSecure())
|
||||
.authorizeRequests(authorize -> authorize.anyRequest().permitAll())
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
@ -40,7 +40,16 @@ import org.springframework.web.bind.annotation.CookieValue;
|
||||
import org.springframework.web.bind.annotation.CrossOrigin;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import java.util.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.onlyoffice.integration.documentserver.util.Constants.ANONYMOUS_USER_ID;
|
||||
|
||||
@CrossOrigin("*")
|
||||
@Controller
|
||||
@ -75,20 +84,25 @@ public class EditorController {
|
||||
|
||||
@GetMapping(path = "${url.editor}")
|
||||
// process request to open the editor page
|
||||
public String index(@RequestParam("fileName") String fileName,
|
||||
@RequestParam(value = "action", required = false) String actionParam,
|
||||
@RequestParam(value = "type", required = false) String typeParam,
|
||||
@RequestParam(value = "actionLink", required = false) String actionLink,
|
||||
@RequestParam(value = "directUrl", required = false, defaultValue = "false") Boolean directUrl,
|
||||
@CookieValue(value = "uid") String uid,
|
||||
@CookieValue(value = "ulang") String lang,
|
||||
Model model) throws JsonProcessingException {
|
||||
public String index(@RequestParam("fileName") final String fileName,
|
||||
@RequestParam(value = "action", required = false) final String actionParam,
|
||||
@RequestParam(value = "type", required = false) final String typeParam,
|
||||
@RequestParam(value = "actionLink", required = false) final String actionLink,
|
||||
@RequestParam(value = "directUrl", required = false,
|
||||
defaultValue = "false") final Boolean directUrl,
|
||||
@CookieValue(value = "uid") final String uid,
|
||||
@CookieValue(value = "ulang") final String lang,
|
||||
final Model model) throws JsonProcessingException {
|
||||
Action action = Action.edit;
|
||||
Type type = Type.desktop;
|
||||
Locale locale = new Locale("en");
|
||||
|
||||
if(actionParam != null) action = Action.valueOf(actionParam);
|
||||
if(typeParam != null) type = Type.valueOf(typeParam);
|
||||
if (actionParam != null) {
|
||||
action = Action.valueOf(actionParam);
|
||||
}
|
||||
if (typeParam != null) {
|
||||
type = Type.valueOf(typeParam);
|
||||
}
|
||||
|
||||
List<String> langsAndKeys = Arrays.asList(langs.split("\\|"));
|
||||
for (String langAndKey : langsAndKeys) {
|
||||
@ -102,7 +116,9 @@ public class EditorController {
|
||||
Optional<User> optionalUser = userService.findUserById(Integer.parseInt(uid));
|
||||
|
||||
// if the user is not present, return the ONLYOFFICE start page
|
||||
if(!optionalUser.isPresent()) return "index.html";
|
||||
if (!optionalUser.isPresent()) {
|
||||
return "index.html";
|
||||
}
|
||||
|
||||
User user = optionalUser.get();
|
||||
|
||||
@ -121,23 +137,38 @@ public class EditorController {
|
||||
);
|
||||
|
||||
// add attributes to the specified model
|
||||
model.addAttribute("model", fileModel); // add file model with the default parameters to the original model
|
||||
model.addAttribute("fileHistory", historyManager.getHistory(fileModel.getDocument())); // get file history and add it to the model
|
||||
model.addAttribute("docserviceApiUrl",docserviceSite + docserviceApiUrl); // create the document service api URL and add it to the model
|
||||
model.addAttribute("dataInsertImage", getInsertImage(directUrl)); // get an image and add it to the model
|
||||
model.addAttribute("dataCompareFile", getCompareFile(directUrl)); // get a document for comparison and add it to the model
|
||||
model.addAttribute("dataMailMergeRecipients", getMailMerge(directUrl)); // get recipients data for mail merging and add it to the model
|
||||
model.addAttribute("usersForMentions", getUserMentions(uid)); // get user data for mentions and add it to the model
|
||||
// add file model with the default parameters to the original model
|
||||
model.addAttribute("model", fileModel);
|
||||
|
||||
// get file history and add it to the model
|
||||
model.addAttribute("fileHistory", historyManager.getHistory(fileModel.getDocument()));
|
||||
|
||||
// create the document service api URL and add it to the model
|
||||
model.addAttribute("docserviceApiUrl", docserviceSite + docserviceApiUrl);
|
||||
|
||||
// get an image and add it to the model
|
||||
model.addAttribute("dataInsertImage", getInsertImage(directUrl));
|
||||
|
||||
// get a document for comparison and add it to the model
|
||||
model.addAttribute("dataCompareFile", getCompareFile(directUrl));
|
||||
|
||||
// get recipients data for mail merging and add it to the model
|
||||
model.addAttribute("dataMailMergeRecipients", getMailMerge(directUrl));
|
||||
|
||||
// get user data for mentions and add it to the model
|
||||
model.addAttribute("usersForMentions", getUserMentions(uid));
|
||||
return "editor.html";
|
||||
}
|
||||
|
||||
private List<Mentions> getUserMentions(String uid){ // get user data for mentions
|
||||
List<Mentions> usersForMentions=new ArrayList<>();
|
||||
if(uid!=null && !uid.equals("4")) {
|
||||
private List<Mentions> getUserMentions(final String uid) { // get user data for mentions
|
||||
List<Mentions> usersForMentions = new ArrayList<>();
|
||||
if (uid != null && !uid.equals("4")) {
|
||||
List<User> list = userService.findAll();
|
||||
for (User u : list) {
|
||||
if (u.getId()!=Integer.parseInt(uid) && u.getId()!=4) {
|
||||
usersForMentions.add(new Mentions(u.getName(),u.getEmail())); // user data includes user names and emails
|
||||
if (u.getId() != Integer.parseInt(uid) && u.getId() != ANONYMOUS_USER_ID) {
|
||||
|
||||
// user data includes user names and emails
|
||||
usersForMentions.add(new Mentions(u.getName(), u.getEmail()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -146,41 +177,49 @@ public class EditorController {
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private String getInsertImage(Boolean directUrl) { // get an image that will be inserted into the document
|
||||
private String getInsertImage(final Boolean directUrl) { // get an image that will be inserted into the document
|
||||
Map<String, Object> dataInsertImage = new HashMap<>();
|
||||
dataInsertImage.put("fileType", "png");
|
||||
dataInsertImage.put("url", storagePathBuilder.getServerUrl(true) + "/css/img/logo.png");
|
||||
if (directUrl) {
|
||||
dataInsertImage.put("directUrl", storagePathBuilder.getServerUrl(false) + "/css/img/logo.png");
|
||||
dataInsertImage.put("directUrl", storagePathBuilder
|
||||
.getServerUrl(false) + "/css/img/logo.png");
|
||||
}
|
||||
|
||||
// check if the document token is enabled
|
||||
if(jwtManager.tokenEnabled()){
|
||||
dataInsertImage.put("token", jwtManager.createToken(dataInsertImage)); // create token from the dataInsertImage object
|
||||
if (jwtManager.tokenEnabled()) {
|
||||
|
||||
// create token from the dataInsertImage object
|
||||
dataInsertImage.put("token", jwtManager.createToken(dataInsertImage));
|
||||
}
|
||||
|
||||
return objectMapper.writeValueAsString(dataInsertImage).substring(1, objectMapper.writeValueAsString(dataInsertImage).length()-1);
|
||||
return objectMapper.writeValueAsString(dataInsertImage)
|
||||
.substring(1, objectMapper.writeValueAsString(dataInsertImage).length() - 1);
|
||||
}
|
||||
|
||||
// get a document that will be compared with the current document
|
||||
@SneakyThrows
|
||||
private String getCompareFile(Boolean directUrl) { // get a document that will be compared with the current document
|
||||
private String getCompareFile(final Boolean directUrl) {
|
||||
Map<String, Object> dataCompareFile = new HashMap<>();
|
||||
dataCompareFile.put("fileType", "docx");
|
||||
dataCompareFile.put("url", storagePathBuilder.getServerUrl(true) + "/assets?name=sample.docx");
|
||||
if (directUrl) {
|
||||
dataCompareFile.put("directUrl", storagePathBuilder.getServerUrl(false) + "/assets?name=sample.docx");
|
||||
dataCompareFile.put("directUrl", storagePathBuilder
|
||||
.getServerUrl(false) + "/assets?name=sample.docx");
|
||||
}
|
||||
|
||||
// check if the document token is enabled
|
||||
if(jwtManager.tokenEnabled()){
|
||||
dataCompareFile.put("token", jwtManager.createToken(dataCompareFile)); // create token from the dataCompareFile object
|
||||
if (jwtManager.tokenEnabled()) {
|
||||
|
||||
// create token from the dataCompareFile object
|
||||
dataCompareFile.put("token", jwtManager.createToken(dataCompareFile));
|
||||
}
|
||||
|
||||
return objectMapper.writeValueAsString(dataCompareFile);
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private String getMailMerge(Boolean directUrl) {
|
||||
private String getMailMerge(final Boolean directUrl) {
|
||||
Map<String, Object> dataMailMergeRecipients = new HashMap<>(); // get recipients data for mail merging
|
||||
dataMailMergeRecipients.put("fileType", "csv");
|
||||
dataMailMergeRecipients.put("url", storagePathBuilder.getServerUrl(true) + "/csv");
|
||||
@ -189,8 +228,10 @@ public class EditorController {
|
||||
}
|
||||
|
||||
// check if the document token is enabled
|
||||
if(jwtManager.tokenEnabled()){
|
||||
dataMailMergeRecipients.put("token", jwtManager.createToken(dataMailMergeRecipients)); // create token from the dataMailMergeRecipients object
|
||||
if (jwtManager.tokenEnabled()) {
|
||||
|
||||
// create token from the dataMailMergeRecipients object
|
||||
dataMailMergeRecipients.put("token", jwtManager.createToken(dataMailMergeRecipients));
|
||||
}
|
||||
|
||||
return objectMapper.writeValueAsString(dataMailMergeRecipients);
|
||||
|
||||
@ -41,16 +41,26 @@ import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.bind.annotation.CookieValue;
|
||||
import org.springframework.web.bind.annotation.CrossOrigin;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.*;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@CrossOrigin("*")
|
||||
@Controller
|
||||
@ -90,10 +100,10 @@ public class FileController {
|
||||
private CallbackManager callbackManager;
|
||||
|
||||
// create user metadata
|
||||
private String createUserMetadata(String uid, String fullFileName) {
|
||||
private String createUserMetadata(final String uid, final String fullFileName) {
|
||||
Optional<User> optionalUser = userService.findUserById(Integer.parseInt(uid)); // find a user by their ID
|
||||
String documentType = fileUtility.getDocumentType(fullFileName).toString().toLowerCase(); // get document type
|
||||
if(optionalUser.isPresent()){
|
||||
if (optionalUser.isPresent()) {
|
||||
User user = optionalUser.get();
|
||||
storageMutator.createMeta(fullFileName, // create meta information with the user ID and name specified
|
||||
String.valueOf(user.getId()), user.getName());
|
||||
@ -102,33 +112,39 @@ public class FileController {
|
||||
}
|
||||
|
||||
// download data from the specified file
|
||||
private ResponseEntity<Resource> downloadFile(String fileName){
|
||||
private ResponseEntity<Resource> downloadFile(final String fileName) {
|
||||
Resource resource = storageMutator.loadFileAsResource(fileName); // load the specified file as a resource
|
||||
String contentType = "application/octet-stream";
|
||||
|
||||
// create a response with the content type, header and body with the file data
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(contentType))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"" + resource.getFilename() + "\"")
|
||||
.body(resource);
|
||||
}
|
||||
|
||||
// download data from the specified history file
|
||||
private ResponseEntity<Resource> downloadFileHistory(String fileName, String version, String file){
|
||||
Resource resource = storageMutator.loadFileAsResourceHistory(fileName,version,file); // load the specified file as a resource
|
||||
private ResponseEntity<Resource> downloadFileHistory(final String fileName,
|
||||
final String version,
|
||||
final String file) {
|
||||
|
||||
// load the specified file as a resource
|
||||
Resource resource = storageMutator.loadFileAsResourceHistory(fileName, version, file);
|
||||
String contentType = "application/octet-stream";
|
||||
|
||||
// create a response with the content type, header and body with the file data
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(contentType))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"" + resource.getFilename() + "\"")
|
||||
.body(resource);
|
||||
}
|
||||
|
||||
@PostMapping("/upload")
|
||||
@ResponseBody
|
||||
public String upload(@RequestParam("file") MultipartFile file, // upload a file
|
||||
@CookieValue("uid") String uid){
|
||||
public String upload(@RequestParam("file") final MultipartFile file, // upload a file
|
||||
@CookieValue("uid") final String uid) {
|
||||
try {
|
||||
String fullFileName = file.getOriginalFilename(); // get file name
|
||||
String fileExtension = fileUtility.getFileExtension(fullFileName); // get file extension
|
||||
@ -136,17 +152,19 @@ public class FileController {
|
||||
byte[] bytes = file.getBytes(); // get file in bytes
|
||||
|
||||
// check if the file size exceeds the maximum file size or is less than 0
|
||||
if(fileUtility.getMaxFileSize() < fileSize || fileSize <= 0){
|
||||
if (fileUtility.getMaxFileSize() < fileSize || fileSize <= 0) {
|
||||
return "{ \"error\": \"File size is incorrect\"}"; // if so, write an error message to the response
|
||||
}
|
||||
|
||||
// check if file extension is supported by the editor
|
||||
if(!fileUtility.getFileExts().contains(fileExtension)){
|
||||
return "{ \"error\": \"File type is not supported\"}"; // if not, write an error message to the response
|
||||
if (!fileUtility.getFileExts().contains(fileExtension)) {
|
||||
|
||||
// if not, write an error message to the response
|
||||
return "{ \"error\": \"File type is not supported\"}";
|
||||
}
|
||||
|
||||
String fileNamePath = storageMutator.updateFile(fullFileName, bytes); // update a file
|
||||
if (fileNamePath.isBlank()){
|
||||
if (fileNamePath.isBlank()) {
|
||||
throw new IOException("Could not update a file"); // if the file cannot be updated, an error occurs
|
||||
}
|
||||
|
||||
@ -156,31 +174,46 @@ public class FileController {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "{ \"error\": \"Something went wrong when uploading the file.\"}"; // if the operation of file uploading is unsuccessful, an error occurs
|
||||
|
||||
// if the operation of file uploading is unsuccessful, an error occurs
|
||||
return "{ \"error\": \"Something went wrong when uploading the file.\"}";
|
||||
}
|
||||
|
||||
@PostMapping(path = "${url.converter}")
|
||||
@ResponseBody
|
||||
public String convert(@RequestBody Converter body, // convert a file
|
||||
@CookieValue("uid") String uid, @CookieValue("ulang") String lang){
|
||||
String fileName = body.getFileName(); // get file name
|
||||
String fileUri = documentManager.getDownloadUrl(fileName, true); // get URL for downloading a file with the specified name
|
||||
String filePass = body.getFilePass() != null ? body.getFilePass() : null; // get file password if it exists
|
||||
String fileExt = fileUtility.getFileExtension(fileName); // get file extension
|
||||
DocumentType type = fileUtility.getDocumentType(fileName); // get document type (word, cell or slide)
|
||||
String internalFileExt = fileUtility.getInternalExtension(type); // get an editor internal extension (".docx", ".xlsx" or ".pptx")
|
||||
public String convert(@RequestBody final Converter body, // convert a file
|
||||
@CookieValue("uid") final String uid, @CookieValue("ulang") final String lang) {
|
||||
// get file name
|
||||
String fileName = body.getFileName();
|
||||
|
||||
try{
|
||||
if(fileUtility.getConvertExts().contains(fileExt)){ // check if the file with such an extension can be converted
|
||||
// get URL for downloading a file with the specified name
|
||||
String fileUri = documentManager.getDownloadUrl(fileName, true);
|
||||
|
||||
// get file password if it exists
|
||||
String filePass = body.getFilePass() != null ? body.getFilePass() : null;
|
||||
|
||||
// get file extension
|
||||
String fileExt = fileUtility.getFileExtension(fileName);
|
||||
|
||||
// get document type (word, cell or slide)
|
||||
DocumentType type = fileUtility.getDocumentType(fileName);
|
||||
|
||||
// get an editor internal extension (".docx", ".xlsx" or ".pptx")
|
||||
String internalFileExt = fileUtility.getInternalExtension(type);
|
||||
|
||||
try {
|
||||
// check if the file with such an extension can be converted
|
||||
if (fileUtility.getConvertExts().contains(fileExt)) {
|
||||
String key = serviceConverter.generateRevisionId(fileUri); // generate document key
|
||||
String newFileUri = serviceConverter // get the URL to the converted file
|
||||
.getConvertedUri(fileUri, fileExt, internalFileExt, key, filePass, true, lang);
|
||||
|
||||
if(newFileUri.isEmpty()){
|
||||
if (newFileUri.isEmpty()) {
|
||||
return "{ \"step\" : \"0\", \"filename\" : \"" + fileName + "\"}";
|
||||
}
|
||||
|
||||
// get a file name of an internal file extension with an index if the file with such a name already exists
|
||||
/* get a file name of an internal file extension with an index if the file
|
||||
with such a name already exists */
|
||||
String nameWithInternalExt = fileUtility.getFileNameWithoutExtension(fileName) + internalFileExt;
|
||||
String correctedName = documentManager.getCorrectName(nameWithInternalExt);
|
||||
|
||||
@ -188,7 +221,7 @@ public class FileController {
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
|
||||
InputStream stream = connection.getInputStream(); // get input stream of the converted file
|
||||
|
||||
if (stream == null){
|
||||
if (stream == null) {
|
||||
connection.disconnect();
|
||||
throw new RuntimeException("Input stream is null");
|
||||
}
|
||||
@ -200,87 +233,104 @@ public class FileController {
|
||||
|
||||
// create meta information about the converted file with the user ID and name specified
|
||||
return createUserMetadata(uid, fileName);
|
||||
}catch (Exception e) {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "{ \"error\": \"" + "The file can't be converted.\"}"; // if the operation of file converting is unsuccessful, an error occurs
|
||||
// if the operation of file converting is unsuccessful, an error occurs
|
||||
return "{ \"error\": \"" + "The file can't be converted.\"}";
|
||||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
@ResponseBody
|
||||
public String delete(@RequestBody Converter body){ // delete a file
|
||||
try
|
||||
{
|
||||
public String delete(@RequestBody final Converter body) { // delete a file
|
||||
try {
|
||||
String fullFileName = fileUtility.getFileName(body.getFileName()); // get full file name
|
||||
boolean fileSuccess = storageMutator.deleteFile(fullFileName); // delete a file from the storage and return the status of this operation (true or false)
|
||||
boolean historySuccess = storageMutator.deleteFileHistory(fullFileName); // delete file history and return the status of this operation (true or false)
|
||||
|
||||
return "{ \"success\": \""+ (fileSuccess && historySuccess) +"\"}";
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return "{ \"error\": \"" + e.getMessage() + "\"}"; // if the operation of file deleting is unsuccessful, an error occurs
|
||||
// delete a file from the storage and return the status of this operation (true or false)
|
||||
boolean fileSuccess = storageMutator.deleteFile(fullFileName);
|
||||
|
||||
// delete file history and return the status of this operation (true or false)
|
||||
boolean historySuccess = storageMutator.deleteFileHistory(fullFileName);
|
||||
|
||||
return "{ \"success\": \"" + (fileSuccess && historySuccess) + "\"}";
|
||||
} catch (Exception e) {
|
||||
// if the operation of file deleting is unsuccessful, an error occurs
|
||||
return "{ \"error\": \"" + e.getMessage() + "\"}";
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/downloadhistory")
|
||||
public ResponseEntity<Resource> downloadHistory(HttpServletRequest request,// download a file
|
||||
@RequestParam("fileName") String fileName,
|
||||
@RequestParam("ver") String version,
|
||||
@RequestParam("file") String file){ // history file
|
||||
try{
|
||||
public ResponseEntity<Resource> downloadHistory(final HttpServletRequest request, // download a file
|
||||
@RequestParam("fileName") final String fileName,
|
||||
@RequestParam("ver") final String version,
|
||||
@RequestParam("file") final String file) { // history file
|
||||
try {
|
||||
// check if a token is enabled or not
|
||||
if(jwtManager.tokenEnabled()){
|
||||
if (jwtManager.tokenEnabled()) {
|
||||
String header = request.getHeader(documentJwtHeader == null // get the document JWT header
|
||||
|| documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader);
|
||||
if(header != null && !header.isEmpty()){
|
||||
String token = header.replace("Bearer ", ""); // token is the header without the Bearer prefix
|
||||
if (header != null && !header.isEmpty()) {
|
||||
String token = header
|
||||
.replace("Bearer ", ""); // token is the header without the Bearer prefix
|
||||
jwtManager.readToken(token); // read the token
|
||||
}else {
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return downloadFileHistory(fileName,version,file); // download data from the specified file
|
||||
} catch(Exception e){
|
||||
return downloadFileHistory(fileName, version, file); // download data from the specified file
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping(path = "${url.download}")
|
||||
public ResponseEntity<Resource> download(HttpServletRequest request, // download a file
|
||||
@RequestParam("fileName") String fileName){
|
||||
try{
|
||||
public ResponseEntity<Resource> download(final HttpServletRequest request, // download a file
|
||||
@RequestParam("fileName") final String fileName,
|
||||
@RequestParam(value = "userAddress", required = false) final String userAddress){
|
||||
try {
|
||||
// check if a token is enabled or not
|
||||
if(jwtManager.tokenEnabled()){
|
||||
String header = request.getHeader(documentJwtHeader == null // get the document JWT header
|
||||
if (jwtManager.tokenEnabled() && userAddress != null) {
|
||||
String header = request.getHeader(documentJwtHeader == null // get the document JWT header
|
||||
|| documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader);
|
||||
if(header != null && !header.isEmpty()){
|
||||
String token = header.replace("Bearer ", ""); // token is the header without the Bearer prefix
|
||||
if (header != null && !header.isEmpty()) {
|
||||
String token = header
|
||||
.replace("Bearer ", ""); // token is the header without the Bearer prefix
|
||||
jwtManager.readToken(token); // read the token
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return downloadFile(fileName); // download data from the specified file
|
||||
} catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/create")
|
||||
public String create(@RequestParam("fileExt") String fileExt, // create a sample file of the specified extension
|
||||
@RequestParam(value = "sample", required = false) Optional<Boolean> isSample,
|
||||
@CookieValue(value = "uid", required = false) String uid,
|
||||
Model model){
|
||||
Boolean sampleData = (isSample.isPresent() && !isSample.isEmpty()) && isSample.get(); // specify if the sample data exists or not
|
||||
if(fileExt != null){
|
||||
try{
|
||||
public String create(@RequestParam("fileExt")
|
||||
final String fileExt, // create a sample file of the specified extension
|
||||
@RequestParam(value = "sample", required = false) final Optional<Boolean> isSample,
|
||||
@CookieValue(value = "uid", required = false) final String uid,
|
||||
final Model model) {
|
||||
// specify if the sample data exists or not
|
||||
Boolean sampleData = (isSample.isPresent() && !isSample.isEmpty()) && isSample.get();
|
||||
if (fileExt != null) {
|
||||
try {
|
||||
Optional<User> user = userService.findUserById(Integer.parseInt(uid)); // find a user by their ID
|
||||
if (!user.isPresent()) throw new RuntimeException("Could not fine any user with id = "+uid); // if the user with the specified ID doesn't exist, an error occurs
|
||||
String fileName = documentManager.createDemo(fileExt, sampleData, uid, user.get().getName()); // create a demo document with the sample data
|
||||
if (!user.isPresent()) {
|
||||
// if the user with the specified ID doesn't exist, an error occurs
|
||||
throw new RuntimeException("Could not fine any user with id = " + uid);
|
||||
}
|
||||
String fileName = documentManager.createDemo(fileExt,
|
||||
sampleData,
|
||||
uid,
|
||||
user.get().getName()); // create a demo document with the sample data
|
||||
if (fileName.isBlank() || fileName == null) {
|
||||
throw new RuntimeException("You must have forgotten to add asset files");
|
||||
}
|
||||
return "redirect:editor?fileName=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8); // redirect the request
|
||||
}catch (Exception ex){
|
||||
return "redirect:editor?fileName=" + URLEncoder
|
||||
.encode(fileName, StandardCharsets.UTF_8); // redirect the request
|
||||
} catch (Exception ex) {
|
||||
model.addAttribute("error", ex.getMessage());
|
||||
return "error.html";
|
||||
}
|
||||
@ -289,33 +339,35 @@ public class FileController {
|
||||
}
|
||||
|
||||
@GetMapping("/assets")
|
||||
public ResponseEntity<Resource> assets(@RequestParam("name") String name) // get sample files from the assests
|
||||
{
|
||||
public ResponseEntity<Resource> assets(@RequestParam("name")
|
||||
final String name) { // get sample files from the assests
|
||||
String fileName = Path.of("assets", "sample", fileUtility.getFileName(name)).toString();
|
||||
return downloadFile(fileName);
|
||||
}
|
||||
|
||||
@GetMapping("/csv")
|
||||
public ResponseEntity<Resource> csv() // download a csv file
|
||||
{
|
||||
public ResponseEntity<Resource> csv() { // download a csv file
|
||||
String fileName = Path.of("assets", "sample", "csv.csv").toString();
|
||||
return downloadFile(fileName);
|
||||
}
|
||||
|
||||
@GetMapping("/files")
|
||||
@ResponseBody
|
||||
public ArrayList<Map<String, Object>> files(@RequestParam(value = "fileId", required = false) String fileId){ // get files information
|
||||
public ArrayList<Map<String, Object>> files(@RequestParam(value = "fileId", required = false)
|
||||
final String fileId) { // get files information
|
||||
return fileId == null ? documentManager.getFilesInfo() : documentManager.getFilesInfo(fileId);
|
||||
}
|
||||
|
||||
@PostMapping(path = "${url.track}")
|
||||
@ResponseBody
|
||||
public String track(HttpServletRequest request, // track file changes
|
||||
@RequestParam("fileName") String fileName,
|
||||
@RequestParam("userAddress") String userAddress,
|
||||
@RequestBody Track body){
|
||||
public String track(final HttpServletRequest request, // track file changes
|
||||
@RequestParam("fileName") final String fileName,
|
||||
@RequestParam("userAddress") final String userAddress,
|
||||
@RequestBody final Track body) {
|
||||
Track track;
|
||||
try {
|
||||
String bodyString = objectMapper.writeValueAsString(body); // write the request body to the object mapper as a string
|
||||
String bodyString = objectMapper
|
||||
.writeValueAsString(body); // write the request body to the object mapper as a string
|
||||
String header = request.getHeader(documentJwtHeader == null // get the request header
|
||||
|| documentJwtHeader.isEmpty() ? "Authorization" : documentJwtHeader);
|
||||
|
||||
@ -324,20 +376,20 @@ public class FileController {
|
||||
}
|
||||
|
||||
JSONObject bodyCheck = jwtManager.parseBody(bodyString, header); // parse the request body
|
||||
body = objectMapper.readValue(bodyCheck.toJSONString(), Track.class); // read the request body
|
||||
track = objectMapper.readValue(bodyCheck.toJSONString(), Track.class); // read the request body
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return e.getMessage();
|
||||
}
|
||||
|
||||
int error = callbackHandler.handle(body, fileName);
|
||||
int error = callbackHandler.handle(track, fileName);
|
||||
|
||||
return"{\"error\":" + error + "}";
|
||||
return "{\"error\":" + error + "}";
|
||||
}
|
||||
|
||||
@PostMapping("/saveas")
|
||||
@ResponseBody
|
||||
public String saveAs(@RequestBody JSONObject body, @CookieValue("uid") String uid) {
|
||||
public String saveAs(@RequestBody final JSONObject body, @CookieValue("uid") final String uid) {
|
||||
String title = (String) body.get("title");
|
||||
String saveAsFileUrl = (String) body.get("url");
|
||||
|
||||
@ -368,17 +420,17 @@ public class FileController {
|
||||
|
||||
@PostMapping("/rename")
|
||||
@ResponseBody
|
||||
public String rename(@RequestBody JSONObject body) {
|
||||
public String rename(@RequestBody final JSONObject body) {
|
||||
String newfilename = (String) body.get("newfilename");
|
||||
String dockey = (String) body.get("dockey");
|
||||
String origExt = "." + (String) body.get("ext");
|
||||
String curExt = newfilename;
|
||||
|
||||
if(newfilename.indexOf(".") != -1) {
|
||||
if (newfilename.indexOf(".") != -1) {
|
||||
curExt = (String) fileUtility.getFileExtension(newfilename);
|
||||
}
|
||||
|
||||
if(origExt.compareTo(curExt) != 0) {
|
||||
if (origExt.compareTo(curExt) != 0) {
|
||||
newfilename += origExt;
|
||||
}
|
||||
|
||||
|
||||
@ -21,16 +21,25 @@ package com.onlyoffice.integration.controllers;
|
||||
import com.onlyoffice.integration.documentserver.storage.FileStorageMutator;
|
||||
import com.onlyoffice.integration.documentserver.storage.FileStoragePathBuilder;
|
||||
import com.onlyoffice.integration.documentserver.util.Misc;
|
||||
import com.onlyoffice.integration.entities.*;
|
||||
import com.onlyoffice.integration.services.UserServices;
|
||||
import com.onlyoffice.integration.documentserver.util.file.FileUtility;
|
||||
import com.onlyoffice.integration.entities.User;
|
||||
import com.onlyoffice.integration.services.UserServices;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.bind.annotation.CrossOrigin;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@CrossOrigin("*")
|
||||
@ -68,8 +77,8 @@ public class IndexController {
|
||||
private String langs;
|
||||
|
||||
@GetMapping("${url.index}")
|
||||
public String index(@RequestParam(value = "directUrl", required = false) Boolean directUrl,
|
||||
Model model){
|
||||
public String index(@RequestParam(value = "directUrl", required = false) final Boolean directUrl,
|
||||
final Model model) {
|
||||
java.io.File[] files = storageMutator.getStoredFiles(); // get all the stored files from the storage
|
||||
List<String> docTypes = new ArrayList<>();
|
||||
List<Boolean> filesEditable = new ArrayList<>();
|
||||
@ -87,24 +96,30 @@ public class IndexController {
|
||||
List<User> users = userService.findAll(); // get a list of all the users
|
||||
|
||||
String tooltip = users.stream() // get the tooltip with the user descriptions
|
||||
.map(user -> mistUtility.convertUserDescriptions(user.getName(), user.getDescriptions())) // convert user descriptions to the specified format
|
||||
.map(user -> mistUtility.convertUserDescriptions(user.getName(),
|
||||
user.getDescriptions())) // convert user descriptions to the specified format
|
||||
.collect(Collectors.joining());
|
||||
|
||||
for(java.io.File file:files){ // run through all the files
|
||||
for (java.io.File file:files) { // run through all the files
|
||||
String fileName = file.getName(); // get file name
|
||||
docTypes.add(fileUtility.getDocumentType(fileName).toString().toLowerCase()); // add a document type of each file to the list
|
||||
filesEditable.add(fileUtility.getEditedExts().contains(fileUtility.getFileExtension(fileName))); // specify if a file is editable or not
|
||||
versions.add(" ["+storagePathBuilder.getFileVersion(fileName, true)+"]"); // add a file version to the list
|
||||
docTypes.add(fileUtility
|
||||
.getDocumentType(fileName)
|
||||
.toString()
|
||||
.toLowerCase()); // add a document type of each file to the list
|
||||
filesEditable.add(fileUtility.getEditedExts()
|
||||
.contains(fileUtility.getFileExtension(fileName))); // specify if a file is editable or not
|
||||
versions.add(" [" + storagePathBuilder.
|
||||
getFileVersion(fileName, true) + "]"); // add a file version to the list
|
||||
isFillFormDoc.add(fileUtility.getFillExts().contains(fileUtility.getFileExtension(fileName)));
|
||||
}
|
||||
|
||||
// add all the parameters to the model
|
||||
model.addAttribute("isFillFormDoc", isFillFormDoc);
|
||||
model.addAttribute("versions",versions);
|
||||
model.addAttribute("versions", versions);
|
||||
model.addAttribute("files", files);
|
||||
model.addAttribute("docTypes", docTypes);
|
||||
model.addAttribute("filesEditable", filesEditable);
|
||||
model.addAttribute("datadocs", docserviceSite+docservicePreloader);
|
||||
model.addAttribute("datadocs", docserviceSite + docservicePreloader);
|
||||
model.addAttribute("tooltip", tooltip);
|
||||
model.addAttribute("users", users);
|
||||
model.addAttribute("languages", languages);
|
||||
@ -115,12 +130,15 @@ public class IndexController {
|
||||
|
||||
@PostMapping("/config")
|
||||
@ResponseBody
|
||||
public HashMap<String, String> configParameters(){ // get configuration parameters
|
||||
public HashMap<String, String> configParameters() { // get configuration parameters
|
||||
HashMap<String, String> configuration = new HashMap<>();
|
||||
|
||||
configuration.put("FillExtList", String.join(",", fileUtility.getFillExts())); // put a list of the extensions that can be filled to config
|
||||
configuration.put("ConverExtList", String.join(",", fileUtility.getConvertExts())); // put a list of the extensions that can be converted to config
|
||||
configuration.put("EditedExtList", String.join(",", fileUtility.getEditedExts())); // put a list of the extensions that can be edited to config
|
||||
configuration.put("FillExtList", String.join(",", fileUtility
|
||||
.getFillExts())); // put a list of the extensions that can be filled to config
|
||||
configuration.put("ConverExtList", String.join(",", fileUtility
|
||||
.getConvertExts())); // put a list of the extensions that can be converted to config
|
||||
configuration.put("EditedExtList", String.join(",", fileUtility
|
||||
.getEditedExts())); // put a list of the extensions that can be edited to config
|
||||
configuration.put("UrlConverter", urlConverter);
|
||||
configuration.put("UrlEditor", urlEditor);
|
||||
|
||||
|
||||
@ -26,7 +26,7 @@ public interface Callback {
|
||||
int handle(Track body, String fileName); // handle the callback
|
||||
int getStatus(); // get document status
|
||||
@Autowired
|
||||
default void selfRegistration(CallbackHandler callbackHandler){ // register a callback handler
|
||||
default void selfRegistration(CallbackHandler callbackHandler) { // register a callback handler
|
||||
callbackHandler.register(getStatus(), this);
|
||||
}
|
||||
}
|
||||
|
||||
@ -33,14 +33,14 @@ public class CallbackHandler {
|
||||
|
||||
private Map<Integer, Callback> callbackHandlers = new HashMap<>();
|
||||
|
||||
public void register(int code, Callback callback){ // register a callback handler
|
||||
public void register(final int code, final Callback callback) { // register a callback handler
|
||||
callbackHandlers.put(code, callback);
|
||||
}
|
||||
|
||||
public int handle(Track body, String fileName){ // handle a callback
|
||||
public int handle(final Track body, final String fileName) { // handle a callback
|
||||
Callback callback = callbackHandlers.get(body.getStatus());
|
||||
if (callback == null){
|
||||
logger.warn("Callback status "+body.getStatus()+" is not supported yet");
|
||||
if (callback == null) {
|
||||
logger.warn("Callback status " + body.getStatus() + " is not supported yet");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@ -26,10 +26,10 @@ public enum Status {
|
||||
MUST_FORCE_SAVE(6), // 6 - document is being edited, but the current document state is saved
|
||||
CORRUPTED_FORCE_SAVE(7); // 7 - error has occurred while force saving the document
|
||||
private int code;
|
||||
Status(int code){
|
||||
this.code = code;
|
||||
Status(final int codeParam) {
|
||||
this.code = codeParam;
|
||||
}
|
||||
public int getCode(){ // get document status
|
||||
public int getCode() { // get document status
|
||||
return this.code;
|
||||
}
|
||||
}
|
||||
|
||||
@ -31,15 +31,18 @@ public class EditCallback implements Callback {
|
||||
@Autowired
|
||||
private CallbackManager callbackManager;
|
||||
@Override
|
||||
public int handle(Track body, String fileName) { // handle the callback when the document is being edited
|
||||
public int handle(final Track body,
|
||||
final String fileName) { // handle the callback when the document is being edited
|
||||
int result = 0;
|
||||
Action action = body.getActions().get(0); // get the user ID who is editing the document
|
||||
if (action.getType().equals(com.onlyoffice.integration.documentserver.models.enums.Action.edit)) { // if this value is not equal to the user ID
|
||||
if (action.getType().equals(com.onlyoffice.integration.documentserver.models.enums
|
||||
.Action.edit)) { // if this value is not equal to the user ID
|
||||
String user = action.getUserid(); // get user ID
|
||||
if (!body.getUsers().contains(user)) { // if this user is not specified in the body
|
||||
String key = body.getKey(); // get document key
|
||||
try {
|
||||
callbackManager.commandRequest("forcesave", key, null); // create a command request to forcibly save the document being edited without closing it
|
||||
// create a command request to forcibly save the document being edited without closing it
|
||||
callbackManager.commandRequest("forcesave", key, null);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
result = 1;
|
||||
|
||||
@ -30,7 +30,8 @@ public class ForcesaveCallback implements Callback {
|
||||
@Autowired
|
||||
private CallbackManager callbackManager;
|
||||
@Override
|
||||
public int handle(Track body, String fileName) { // handle the callback when the force saving request is performed
|
||||
public int handle(final Track body,
|
||||
final String fileName) { // handle the callback when the force saving request is performed
|
||||
int result = 0;
|
||||
try {
|
||||
callbackManager.processForceSave(body, fileName); // file force saving process
|
||||
@ -43,6 +44,7 @@ public class ForcesaveCallback implements Callback {
|
||||
|
||||
@Override
|
||||
public int getStatus() { // get document status
|
||||
return Status.MUST_FORCE_SAVE.getCode(); // return status 6 - document is being edited, but the current document state is saved
|
||||
// return status 6 - document is being edited, but the current document state is saved
|
||||
return Status.MUST_FORCE_SAVE.getCode();
|
||||
}
|
||||
}
|
||||
|
||||
@ -30,7 +30,8 @@ public class SaveCallback implements Callback {
|
||||
@Autowired
|
||||
private CallbackManager callbackManager;
|
||||
@Override
|
||||
public int handle(Track body, String fileName) { // handle the callback when the saving request is performed
|
||||
public int handle(final Track body,
|
||||
final String fileName) { // handle the callback when the saving request is performed
|
||||
int result = 0;
|
||||
try {
|
||||
callbackManager.processSave(body, fileName); // file saving process
|
||||
|
||||
@ -32,17 +32,24 @@ import org.json.simple.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.*;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
//TODO: Refactoring
|
||||
import static com.onlyoffice.integration.documentserver.util.Constants.FILE_SAVE_TIMEOUT;
|
||||
|
||||
// todo: Refactoring
|
||||
@Component
|
||||
@Primary
|
||||
public class DefaultCallbackManager implements CallbackManager {
|
||||
@ -69,18 +76,20 @@ public class DefaultCallbackManager implements CallbackManager {
|
||||
@Autowired
|
||||
private ServiceConverter serviceConverter;
|
||||
|
||||
// save file information from the URL to the file specified
|
||||
private void downloadToFile(String url, Path path) throws Exception {
|
||||
if (url == null || url.isEmpty()) throw new RuntimeException("Url argument is not specified"); // URL isn't specified
|
||||
if (path == null) throw new RuntimeException("Path argument is not specified"); // file isn't specified
|
||||
// download file from url
|
||||
@SneakyThrows
|
||||
private byte[] getDownloadFile(final String url) {
|
||||
if (url == null || url.isEmpty()) {
|
||||
throw new RuntimeException("Url argument is not specified"); // URL isn't specified
|
||||
}
|
||||
|
||||
URL uri = new URL(url);
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) uri.openConnection();
|
||||
connection.setConnectTimeout(5000);
|
||||
connection.setConnectTimeout(FILE_SAVE_TIMEOUT);
|
||||
InputStream stream = connection.getInputStream(); // get input stream of the file information from the URL
|
||||
|
||||
int statusCode = connection.getResponseCode();
|
||||
if (statusCode != 200) { // checking status code
|
||||
if (statusCode != HttpStatus.OK.value()) { // checking status code
|
||||
connection.disconnect();
|
||||
throw new RuntimeException("Document editing service returned status: " + statusCode);
|
||||
}
|
||||
@ -90,11 +99,21 @@ public class DefaultCallbackManager implements CallbackManager {
|
||||
throw new RuntimeException("Input stream is null");
|
||||
}
|
||||
|
||||
storageMutator.createOrUpdateFile(path, stream); // update a file or create a new one
|
||||
return stream.readAllBytes();
|
||||
}
|
||||
|
||||
// file saving
|
||||
@SneakyThrows
|
||||
private void saveFile(final byte[] byteArray, final Path path) {
|
||||
if (path == null) {
|
||||
throw new RuntimeException("Path argument is not specified"); // file isn't specified
|
||||
}
|
||||
// update a file or create a new one
|
||||
storageMutator.createOrUpdateFile(path, new ByteArrayInputStream(byteArray));
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public void processSave(Track body, String fileName) { // file saving process
|
||||
public void processSave(final Track body, final String fileName) { // file saving process
|
||||
String downloadUri = body.getUrl();
|
||||
String changesUri = body.getChangesurl();
|
||||
String key = body.getKey();
|
||||
@ -103,46 +122,57 @@ public class DefaultCallbackManager implements CallbackManager {
|
||||
String curExt = fileUtility.getFileExtension(fileName); // get current file extension
|
||||
String downloadExt = "." + body.getFiletype(); // get an extension of the downloaded file
|
||||
|
||||
// Todo [Delete in version 7.0 or higher]
|
||||
if (downloadExt != "." + null) downloadExt = fileUtility.getFileExtension(downloadUri); // Support for versions below 7.0
|
||||
|
||||
//TODO: Refactoring
|
||||
if (!curExt.equals(downloadExt)) { // convert downloaded file to the file with the current extension if these extensions aren't equal
|
||||
// todo: Refactoring
|
||||
// convert downloaded file to the file with the current extension if these extensions aren't equal
|
||||
if (!curExt.equals(downloadExt)) {
|
||||
try {
|
||||
String newFileUri = serviceConverter.getConvertedUri(downloadUri, downloadExt, curExt, serviceConverter.generateRevisionId(downloadUri), null, false, null); // convert a file and get URL to a new file
|
||||
String newFileUri = serviceConverter
|
||||
.getConvertedUri(downloadUri, downloadExt, curExt,
|
||||
serviceConverter.generateRevisionId(downloadUri), null, false,
|
||||
null); // convert a file and get URL to a new file
|
||||
if (newFileUri.isEmpty()) {
|
||||
newFileName = documentManager
|
||||
.getCorrectName(fileUtility.getFileNameWithoutExtension(fileName) + downloadExt); // get the correct file name if it already exists
|
||||
.getCorrectName(fileUtility.getFileNameWithoutExtension(fileName)
|
||||
+ downloadExt); // get the correct file name if it already exists
|
||||
} else {
|
||||
downloadUri = newFileUri;
|
||||
}
|
||||
} catch (Exception e){
|
||||
newFileName = documentManager.getCorrectName(fileUtility.getFileNameWithoutExtension(fileName) + downloadExt);
|
||||
} catch (Exception e) {
|
||||
newFileName = documentManager
|
||||
.getCorrectName(fileUtility.getFileNameWithoutExtension(fileName) + downloadExt);
|
||||
}
|
||||
}
|
||||
|
||||
byte[] byteArrayFile = getDownloadFile(downloadUri); // download document file
|
||||
|
||||
String storagePath = storagePathBuilder.getFileLocation(newFileName); // get the path to a new file
|
||||
Path lastVersion = Paths.get(storagePathBuilder.getFileLocation(fileName)); // get the path to the last file version
|
||||
Path lastVersion = Paths.get(storagePathBuilder
|
||||
.getFileLocation(fileName)); // get the path to the last file version
|
||||
|
||||
if (lastVersion.toFile().exists()) { // if the last file version exists
|
||||
Path histDir = Paths.get(storagePathBuilder.getHistoryDir(storagePath)); // get the history directory
|
||||
storageMutator.createDirectory(histDir); // and create it
|
||||
|
||||
String versionDir = documentManager.versionDir(histDir.toAbsolutePath().toString(), // get the file version directory
|
||||
storagePathBuilder.getFileVersion(histDir.toAbsolutePath().toString(), false), true);
|
||||
String versionDir = documentManager
|
||||
.versionDir(histDir.toAbsolutePath().toString(), // get the file version directory
|
||||
storagePathBuilder
|
||||
.getFileVersion(histDir.toAbsolutePath().toString(), false), true);
|
||||
|
||||
Path ver = Paths.get(versionDir);
|
||||
Path toSave = Paths.get(storagePath);
|
||||
|
||||
storageMutator.createDirectory(ver); // create the file version directory
|
||||
storageMutator.moveFile(lastVersion, Paths.get(versionDir + File.separator + "prev" + curExt)); // move the last file version to the file version directory with the "prev" postfix
|
||||
|
||||
downloadToFile(downloadUri, toSave); // save file to the storage path
|
||||
downloadToFile(changesUri, Path.of(versionDir + File.separator + "diff.zip")); // save file changes to the diff.zip archive
|
||||
saveFile(byteArrayFile, toSave); // save document file
|
||||
|
||||
byte[] byteArrayChanges = getDownloadFile(changesUri); // download file changes
|
||||
saveFile(byteArrayChanges, Path
|
||||
.of(versionDir + File.separator + "diff.zip")); // save file changes to the diff.zip archive
|
||||
|
||||
JSONObject jsonChanges = new JSONObject(); // create a json object for document changes
|
||||
jsonChanges.put("changes", body.getHistory().getChanges()); // put the changes to the json object
|
||||
jsonChanges.put("serverVersion", body.getHistory().getServerVersion()); // put the server version to the json object
|
||||
jsonChanges.put("serverVersion", body.getHistory()
|
||||
.getServerVersion()); // put the server version to the json object
|
||||
String history = objectMapper.writeValueAsString(jsonChanges);
|
||||
|
||||
if (history == null && body.getHistory() != null) {
|
||||
@ -150,20 +180,26 @@ public class DefaultCallbackManager implements CallbackManager {
|
||||
}
|
||||
|
||||
if (history != null && !history.isEmpty()) {
|
||||
storageMutator.writeToFile(versionDir + File.separator + "changes.json", history); // write the history changes to the changes.json file
|
||||
// write the history changes to the changes.json file
|
||||
storageMutator.writeToFile(versionDir + File.separator + "changes.json", history);
|
||||
}
|
||||
|
||||
storageMutator.writeToFile(versionDir + File.separator + "key.txt", key); // write the key value to the key.txt file
|
||||
storageMutator.deleteFile(storagePathBuilder.getForcesavePath(newFileName, false)); // get the path to the forcesaved file version and remove it
|
||||
// write the key value to the key.txt file
|
||||
storageMutator.writeToFile(versionDir + File.separator + "key.txt", key);
|
||||
|
||||
// get the path to the forcesaved file version and remove it
|
||||
storageMutator.deleteFile(storagePathBuilder.getForcesavePath(newFileName, false));
|
||||
}
|
||||
}
|
||||
|
||||
//TODO: Replace (String method) with (Enum method)
|
||||
// todo: Replace (String method) with (Enum method)
|
||||
@SneakyThrows
|
||||
public void commandRequest(String method, String key, HashMap meta) { // create a command request
|
||||
String DocumentCommandUrl = docserviceUrlSite + docserviceUrlCommand;
|
||||
public void commandRequest(final String method,
|
||||
final String key,
|
||||
final HashMap meta) { // create a command request
|
||||
String documentCommandUrl = docserviceUrlSite + docserviceUrlCommand;
|
||||
|
||||
URL url = new URL(DocumentCommandUrl);
|
||||
URL url = new URL(documentCommandUrl);
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
|
||||
|
||||
HashMap<String, Object> params = new HashMap<String, Object>();
|
||||
@ -175,12 +211,14 @@ public class DefaultCallbackManager implements CallbackManager {
|
||||
}
|
||||
|
||||
String headerToken;
|
||||
if (jwtManager.tokenEnabled()) // check if a secret key to generate token exists or not
|
||||
{
|
||||
if (jwtManager.tokenEnabled()) { // check if a secret key to generate token exists or not
|
||||
Map<String, Object> payloadMap = new HashMap<>();
|
||||
payloadMap.put("payload", params);
|
||||
headerToken = jwtManager.createToken(payloadMap); // encode a payload object into a header token
|
||||
connection.setRequestProperty(documentJwtHeader.equals("") ? "Authorization" : documentJwtHeader, "Bearer " + headerToken); // add a header Authorization with a header token and Authorization prefix in it
|
||||
|
||||
// add a header Authorization with a header token and Authorization prefix in it
|
||||
connection.setRequestProperty(documentJwtHeader.equals("")
|
||||
? "Authorization" : documentJwtHeader, "Bearer " + headerToken);
|
||||
|
||||
String token = jwtManager.createToken(params); // encode a payload object into a body token
|
||||
params.put("token", token);
|
||||
@ -191,7 +229,8 @@ public class DefaultCallbackManager implements CallbackManager {
|
||||
byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
connection.setRequestMethod("POST"); // set the request method
|
||||
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); // set the Content-Type header
|
||||
connection
|
||||
.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); // set the Content-Type header
|
||||
connection.setDoOutput(true); // set the doOutput field to true
|
||||
connection.connect();
|
||||
|
||||
@ -201,76 +240,82 @@ public class DefaultCallbackManager implements CallbackManager {
|
||||
|
||||
InputStream stream = connection.getInputStream(); // get input stream
|
||||
|
||||
if (stream == null) throw new RuntimeException("Could not get an answer");
|
||||
if (stream == null) {
|
||||
throw new RuntimeException("Could not get an answer");
|
||||
}
|
||||
|
||||
String jsonString = serviceConverter.convertStreamToString(stream); // convert stream to json string
|
||||
connection.disconnect();
|
||||
|
||||
JSONObject response = serviceConverter.convertStringToJSON(jsonString); // convert json string to json object
|
||||
//TODO: Add errors ENUM
|
||||
// todo: Add errors ENUM
|
||||
String responseCode = response.get("error").toString();
|
||||
switch(responseCode) {
|
||||
switch (responseCode) {
|
||||
case "0":
|
||||
case "4": {
|
||||
case "4":
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
default:
|
||||
throw new RuntimeException(response.toJSONString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public void processForceSave(Track body, String fileName) { // file force saving process
|
||||
public void processForceSave(final Track body, final String fileNameParam) { // file force saving process
|
||||
|
||||
String downloadUri = body.getUrl();
|
||||
String fileName = fileNameParam;
|
||||
|
||||
String curExt = fileUtility.getFileExtension(fileName); // get current file extension
|
||||
String downloadExt = "."+body.getFiletype(); // get an extension of the downloaded file
|
||||
String downloadExt = "." + body.getFiletype(); // get an extension of the downloaded file
|
||||
|
||||
// Todo [Delete in version 7.0 or higher]
|
||||
if (downloadExt != "."+null) downloadExt = fileUtility.getFileExtension(downloadUri); // Support for versions below 7.0
|
||||
|
||||
Boolean newFileName = false;
|
||||
|
||||
// convert downloaded file to the file with the current extension if these extensions aren't equal
|
||||
//TODO: Extract function
|
||||
// todo: Extract function
|
||||
if (!curExt.equals(downloadExt)) {
|
||||
try {
|
||||
String newFileUri = serviceConverter.getConvertedUri(downloadUri, downloadExt,
|
||||
curExt, serviceConverter.generateRevisionId(downloadUri), null, false, null); // convert file and get URL to a new file
|
||||
// convert file and get URL to a new file
|
||||
String newFileUri = serviceConverter
|
||||
.getConvertedUri(downloadUri, downloadExt, curExt, serviceConverter
|
||||
.generateRevisionId(downloadUri), null, false, null);
|
||||
if (newFileUri.isEmpty()) {
|
||||
newFileName = true;
|
||||
} else {
|
||||
downloadUri = newFileUri;
|
||||
}
|
||||
} catch (Exception e){
|
||||
} catch (Exception e) {
|
||||
newFileName = true;
|
||||
}
|
||||
}
|
||||
|
||||
byte[] byteArrayFile = getDownloadFile(downloadUri); // download document file
|
||||
String forcesavePath = "";
|
||||
|
||||
//TODO: Use ENUMS
|
||||
//TODO: Pointless toString conversion
|
||||
// todo: Use ENUMS
|
||||
// todo: Pointless toString conversion
|
||||
boolean isSubmitForm = body.getForcesavetype().toString().equals("3");
|
||||
|
||||
//TODO: Extract function
|
||||
// todo: Extract function
|
||||
if (isSubmitForm) { // if the form is submitted
|
||||
if (newFileName){
|
||||
if (newFileName) {
|
||||
// get the correct file name if it already exists
|
||||
fileName = documentManager
|
||||
.getCorrectName(fileUtility.getFileNameWithoutExtension(fileName) + "-form" + downloadExt); // get the correct file name if it already exists
|
||||
.getCorrectName(fileUtility
|
||||
.getFileNameWithoutExtension(fileName) + "-form" + downloadExt);
|
||||
} else {
|
||||
fileName = documentManager.getCorrectName(fileUtility.getFileNameWithoutExtension(fileName) + "-form" + curExt);
|
||||
fileName = documentManager
|
||||
.getCorrectName(fileUtility.getFileNameWithoutExtension(fileName) + "-form" + curExt);
|
||||
}
|
||||
forcesavePath = storagePathBuilder.getFileLocation(fileName); // create forcesave path if it doesn't exist
|
||||
List<Action> actions = body.getActions();
|
||||
Action action = actions.get(0);
|
||||
String user = action.getUserid(); // get the user ID
|
||||
storageMutator.createMeta(fileName, user, "Filling Form"); // create meta data for the forcesaved file
|
||||
// create meta data for the forcesaved file
|
||||
storageMutator.createMeta(fileName, user, "Filling Form");
|
||||
} else {
|
||||
if (newFileName){
|
||||
fileName = documentManager.getCorrectName(fileUtility.getFileNameWithoutExtension(fileName) + downloadExt);
|
||||
if (newFileName) {
|
||||
fileName = documentManager
|
||||
.getCorrectName(fileUtility.getFileNameWithoutExtension(fileName) + downloadExt);
|
||||
}
|
||||
|
||||
forcesavePath = storagePathBuilder.getForcesavePath(fileName, false);
|
||||
@ -279,6 +324,6 @@ public class DefaultCallbackManager implements CallbackManager {
|
||||
}
|
||||
}
|
||||
|
||||
downloadToFile(downloadUri, Path.of(forcesavePath));
|
||||
saveFile(byteArrayFile, Path.of(forcesavePath));
|
||||
}
|
||||
}
|
||||
|
||||
@ -27,8 +27,9 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.*;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.net.InetAddress;
|
||||
@ -37,7 +38,12 @@ import java.net.UnknownHostException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.onlyoffice.integration.documentserver.util.Constants.KILOBYTE_SIZE;
|
||||
|
||||
@Component
|
||||
@Primary
|
||||
@ -62,23 +68,23 @@ public class DefaultDocumentManager implements DocumentManager {
|
||||
private ServiceConverter serviceConverter;
|
||||
|
||||
// get URL to the created file
|
||||
public String getCreateUrl(String fileName, Boolean sample){
|
||||
String fileExt = fileName.substring(fileName.length() - 4);
|
||||
String url = storagePathBuilder.getServerUrl(true) + "/create?fileExt=" + fileExt + "&sample=" + sample;
|
||||
public String getCreateUrl(final String fileName, final Boolean sample) {
|
||||
String fileExt = fileUtility.getFileExtension(fileName).replace(".", "");
|
||||
String url = storagePathBuilder.getServerUrl(true)
|
||||
+ "/create?fileExt=" + fileExt + "&sample=" + sample;
|
||||
return url;
|
||||
}
|
||||
|
||||
// get a file name with an index if the file with such a name already exists
|
||||
public String getCorrectName(String fileName)
|
||||
{
|
||||
public String getCorrectName(final String fileName) {
|
||||
String baseName = fileUtility.getFileNameWithoutExtension(fileName); // get file name without extension
|
||||
String ext = fileUtility.getFileExtension(fileName); // get file extension
|
||||
String name = baseName + ext; // create a full file name
|
||||
|
||||
Path path = Paths.get(storagePathBuilder.getFileLocation(name));
|
||||
|
||||
for (int i = 1; Files.exists(path); i++) // run through all the files with such a name in the storage directory
|
||||
{
|
||||
// run through all the files with such a name in the storage directory
|
||||
for (int i = 1; Files.exists(path); i++) {
|
||||
name = baseName + " (" + i + ")" + ext; // and add an index to the base name
|
||||
path = Paths.get(storagePathBuilder.getFileLocation(name));
|
||||
}
|
||||
@ -87,101 +93,94 @@ public class DefaultDocumentManager implements DocumentManager {
|
||||
}
|
||||
|
||||
// get file URL
|
||||
public String getFileUri(String fileName, Boolean forDocumentServer)
|
||||
{
|
||||
try
|
||||
{
|
||||
public String getFileUri(final String fileName, final Boolean forDocumentServer) {
|
||||
try {
|
||||
String serverPath = storagePathBuilder.getServerUrl(forDocumentServer); // get server URL
|
||||
String hostAddress = storagePathBuilder.getStorageLocation(); // get the storage directory
|
||||
String filePathDownload = !fileName.contains(InetAddress.getLocalHost().getHostAddress()) ? fileName
|
||||
: fileName.substring(fileName.indexOf(InetAddress.getLocalHost().getHostAddress()) + InetAddress.getLocalHost().getHostAddress().length() + 1);
|
||||
: fileName.substring(fileName.indexOf(InetAddress.getLocalHost()
|
||||
.getHostAddress()) + InetAddress.getLocalHost().getHostAddress().length() + 1);
|
||||
if (!filesStorage.isEmpty() && filePathDownload.contains(filesStorage)) {
|
||||
filePathDownload = filePathDownload.substring(filesStorage.length() + 1);
|
||||
}
|
||||
|
||||
String filePath = serverPath + "/download?fileName=" + URLEncoder.encode(filePathDownload, java.nio.charset.StandardCharsets.UTF_8.toString())
|
||||
+ "&userAddress" + URLEncoder.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString());
|
||||
String filePath = serverPath + "/download?fileName=" + URLEncoder
|
||||
.encode(filePathDownload, java.nio.charset.StandardCharsets.UTF_8.toString()) + "&userAddress"
|
||||
+ URLEncoder.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString());
|
||||
return filePath;
|
||||
}
|
||||
catch (UnsupportedEncodingException | UnknownHostException e)
|
||||
{
|
||||
} catch (UnsupportedEncodingException | UnknownHostException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// get file URL
|
||||
public String getHistoryFileUrl(String fileName, Integer version, String file, Boolean forDocumentServer)
|
||||
{
|
||||
try
|
||||
{
|
||||
public String getHistoryFileUrl(final String fileName, final Integer version, final String file,
|
||||
final Boolean forDocumentServer) {
|
||||
try {
|
||||
String serverPath = storagePathBuilder.getServerUrl(forDocumentServer); // get server URL
|
||||
String hostAddress = storagePathBuilder.getStorageLocation(); // get the storage directory
|
||||
String filePathDownload = !fileName.contains(InetAddress.getLocalHost().getHostAddress()) ? fileName
|
||||
: fileName.substring(fileName.indexOf(InetAddress.getLocalHost().getHostAddress()) + InetAddress.getLocalHost().getHostAddress().length() + 1);
|
||||
String userAddress = forDocumentServer ? "&userAddress" + URLEncoder.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString()) : "";
|
||||
String filePath = serverPath + "/downloadhistory?fileName=" + URLEncoder.encode(filePathDownload, java.nio.charset.StandardCharsets.UTF_8.toString())
|
||||
+ "&ver=" + version + "&file="+file
|
||||
: fileName.substring(fileName.indexOf(InetAddress.getLocalHost().getHostAddress())
|
||||
+ InetAddress.getLocalHost().getHostAddress().length() + 1);
|
||||
String userAddress = forDocumentServer ? "&userAddress" + URLEncoder
|
||||
.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString()) : "";
|
||||
String filePath = serverPath + "/downloadhistory?fileName=" + URLEncoder
|
||||
.encode(filePathDownload, java.nio.charset.StandardCharsets.UTF_8.toString())
|
||||
+ "&ver=" + version + "&file=" + file
|
||||
+ userAddress;
|
||||
return filePath;
|
||||
}
|
||||
catch (UnsupportedEncodingException | UnknownHostException e)
|
||||
{
|
||||
} catch (UnsupportedEncodingException | UnknownHostException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// get the callback URL
|
||||
public String getCallback(String fileName)
|
||||
{
|
||||
public String getCallback(final String fileName) {
|
||||
String serverPath = storagePathBuilder.getServerUrl(true);
|
||||
String storageAddress = storagePathBuilder.getStorageLocation();
|
||||
try
|
||||
{
|
||||
String query = trackUrl+"?fileName="+
|
||||
URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString())
|
||||
+ "&userAddress=" + URLEncoder.encode(storageAddress, java.nio.charset.StandardCharsets.UTF_8.toString());
|
||||
try {
|
||||
String query = trackUrl + "?fileName="
|
||||
+ URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString())
|
||||
+ "&userAddress=" + URLEncoder
|
||||
.encode(storageAddress, java.nio.charset.StandardCharsets.UTF_8.toString());
|
||||
return serverPath + query;
|
||||
}
|
||||
catch (UnsupportedEncodingException e)
|
||||
{
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// get URL to download a file
|
||||
public String getDownloadUrl(String fileName, Boolean isServer) {
|
||||
public String getDownloadUrl(final String fileName, final Boolean isServer) {
|
||||
String serverPath = storagePathBuilder.getServerUrl(isServer);
|
||||
String storageAddress = storagePathBuilder.getStorageLocation();
|
||||
try
|
||||
{
|
||||
String userAddress = isServer ? "&userAddress=" + URLEncoder.encode(storageAddress, java.nio.charset.StandardCharsets.UTF_8.toString()) : "";
|
||||
String query = downloadUrl+"?fileName="
|
||||
try {
|
||||
String userAddress = isServer ? "&userAddress=" + URLEncoder
|
||||
.encode(storageAddress, java.nio.charset.StandardCharsets.UTF_8.toString()) : "";
|
||||
String query = downloadUrl + "?fileName="
|
||||
+ URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString())
|
||||
+ userAddress;
|
||||
|
||||
return serverPath + query;
|
||||
}
|
||||
catch (UnsupportedEncodingException e)
|
||||
{
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// get file information
|
||||
public ArrayList<Map<String, Object>> getFilesInfo(){
|
||||
public ArrayList<Map<String, Object>> getFilesInfo() {
|
||||
ArrayList<Map<String, Object>> files = new ArrayList<>();
|
||||
|
||||
// run through all the stored files
|
||||
for(File file : storageMutator.getStoredFiles()){
|
||||
for (File file : storageMutator.getStoredFiles()) {
|
||||
Map<String, Object> map = new LinkedHashMap<>(); // write all the parameters to the map
|
||||
map.put("version", storagePathBuilder.getFileVersion(file.getName(), false));
|
||||
map.put("id", serviceConverter
|
||||
.generateRevisionId(storagePathBuilder.getStorageLocation() +
|
||||
"/" + file.getName() + "/"
|
||||
.generateRevisionId(storagePathBuilder.getStorageLocation()
|
||||
+ "/" + file.getName() + "/"
|
||||
+ Paths.get(storagePathBuilder.getFileLocation(file.getName()))
|
||||
.toFile()
|
||||
.lastModified()));
|
||||
map.put("contentLength", new BigDecimal(String.valueOf((file.length()/1024.0)))
|
||||
map.put("contentLength", new BigDecimal(String.valueOf((file.length() / Double.valueOf(KILOBYTE_SIZE))))
|
||||
.setScale(2, RoundingMode.HALF_UP) + " KB");
|
||||
map.put("pureContentLength", file.length());
|
||||
map.put("title", file.getName());
|
||||
@ -193,11 +192,11 @@ public class DefaultDocumentManager implements DocumentManager {
|
||||
}
|
||||
|
||||
// get file information by its ID
|
||||
public ArrayList<Map<String, Object>> getFilesInfo(String fileId){
|
||||
public ArrayList<Map<String, Object>> getFilesInfo(final String fileId) {
|
||||
ArrayList<Map<String, Object>> file = new ArrayList<>();
|
||||
|
||||
for (Map<String, Object> map : getFilesInfo()){
|
||||
if (map.get("id").equals(fileId)){
|
||||
for (Map<String, Object> map : getFilesInfo()) {
|
||||
if (map.get("id").equals(fileId)) {
|
||||
file.add(map);
|
||||
break;
|
||||
}
|
||||
@ -207,26 +206,33 @@ public class DefaultDocumentManager implements DocumentManager {
|
||||
}
|
||||
|
||||
// get the path to the file version by the history path and file version
|
||||
public String versionDir(String path, Integer version, boolean historyPath) {
|
||||
if (!historyPath){
|
||||
public String versionDir(final String path, final Integer version, final boolean historyPath) {
|
||||
if (!historyPath) {
|
||||
return storagePathBuilder.getHistoryDir(storagePathBuilder.getFileLocation(path)) + version;
|
||||
}
|
||||
return path + File.separator + version;
|
||||
}
|
||||
|
||||
// create demo document
|
||||
public String createDemo(String fileExt,Boolean sample,String uid,String uname) {
|
||||
String demoName = (sample ? "sample." : "new.") + fileExt; // create sample or new template file with the necessary extension
|
||||
String demoPath = "assets" + File.separator + (sample ? "sample" : "new") + File.separator + demoName; // get the path to the sample document
|
||||
String fileName = getCorrectName(demoName); // get a file name with an index if the file with such a name already exists
|
||||
public String createDemo(final String fileExt, final Boolean sample, final String uid, final String uname) {
|
||||
String demoName = (sample ? "sample." : "new.")
|
||||
+ fileExt; // create sample or new template file with the necessary extension
|
||||
String demoPath = "assets" + File.separator + (sample ? "sample" : "new")
|
||||
+ File.separator + demoName; // get the path to the sample document
|
||||
|
||||
// get a file name with an index if the file with such a name already exists
|
||||
String fileName = getCorrectName(demoName);
|
||||
|
||||
InputStream stream = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResourceAsStream(demoPath); // get the input file stream
|
||||
|
||||
if (stream == null) return null;
|
||||
if (stream == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
storageMutator.createFile(Path.of(storagePathBuilder.getFileLocation(fileName)), stream); // create a file in the specified directory
|
||||
storageMutator.createFile(Path.of(storagePathBuilder
|
||||
.getFileLocation(fileName)), stream); // create a file in the specified directory
|
||||
storageMutator.createMeta(fileName, uid, uname); // create meta information of the demo file
|
||||
|
||||
return fileName;
|
||||
|
||||
@ -23,14 +23,20 @@ import java.util.Map;
|
||||
|
||||
// specify the document manager functions
|
||||
public interface DocumentManager {
|
||||
String getCorrectName(String fileName); // get a file name with an index if the file with such a name already exists
|
||||
|
||||
// get a file name with an index if the file with such a name already exists
|
||||
String getCorrectName(String fileName);
|
||||
String getFileUri(String fileName, Boolean forDocumentServer); // get file URL
|
||||
String getHistoryFileUrl(String fileName, Integer version, String file, Boolean forDocumentServer); // get file URL
|
||||
String getCallback(String fileName); // get the callback URL
|
||||
String getDownloadUrl(String fileName, Boolean forDocumentServer); // get URL to download a file
|
||||
ArrayList<Map<String, Object>> getFilesInfo(); // get file information
|
||||
ArrayList<Map<String, Object>> getFilesInfo(String fileId); // get file information by its ID
|
||||
String versionDir(String path, Integer version, boolean historyPath); // get the path to the file version by the history path and file version
|
||||
String createDemo(String fileExt,Boolean sample,String uid,String uname) throws Exception; // create demo document
|
||||
|
||||
// get the path to the file version by the history path and file version
|
||||
String versionDir(String path, Integer version, boolean historyPath);
|
||||
|
||||
// create demo document
|
||||
String createDemo(String fileExt, Boolean sample, String uid, String uname) throws Exception;
|
||||
String getCreateUrl(String fileName, Boolean sample); // get URL to the created file
|
||||
}
|
||||
|
||||
@ -34,9 +34,13 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Scanner;
|
||||
|
||||
//TODO: Rebuild completely
|
||||
// todo: Rebuild completely
|
||||
@Component
|
||||
public class DefaultHistoryManager implements HistoryManager {
|
||||
|
||||
@ -58,10 +62,12 @@ public class DefaultHistoryManager implements HistoryManager {
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
//TODO: Refactoring
|
||||
// todo: Refactoring
|
||||
@SneakyThrows
|
||||
public String[] getHistory(Document document) { // get document history
|
||||
String histDir = storagePathBuilder.getHistoryDir(storagePathBuilder.getFileLocation(document.getTitle())); // get history directory
|
||||
public String[] getHistory(final Document document) { // get document history
|
||||
|
||||
// get history directory
|
||||
String histDir = storagePathBuilder.getHistoryDir(storagePathBuilder.getFileLocation(document.getTitle()));
|
||||
Integer curVer = storagePathBuilder.getFileVersion(histDir, false); // get current file version
|
||||
|
||||
if (curVer > 0) { // check if the current file version is greater than 0
|
||||
@ -71,14 +77,17 @@ public class DefaultHistoryManager implements HistoryManager {
|
||||
for (Integer i = 1; i <= curVer; i++) { // run through all the file versions
|
||||
Map<String, Object> obj = new HashMap<String, Object>();
|
||||
Map<String, Object> dataObj = new HashMap<String, Object>();
|
||||
String verDir = documentManager.versionDir(histDir, i, true); // get the path to the given file version
|
||||
String verDir = documentManager
|
||||
.versionDir(histDir, i, true); // get the path to the given file version
|
||||
|
||||
String key = i == curVer ? document.getKey() : readFileToEnd(new File(verDir + File.separator + "key.txt")); // get document key
|
||||
String key = i == curVer ? document.getKey() : readFileToEnd(new File(verDir
|
||||
+ File.separator + "key.txt")); // get document key
|
||||
obj.put("key", key);
|
||||
obj.put("version", i);
|
||||
|
||||
if (i == 1) { // check if the version number is equal to 1
|
||||
String createdInfo = readFileToEnd(new File(histDir + File.separator + "createdInfo.json")); // get file with meta data
|
||||
String createdInfo = readFileToEnd(new File(histDir
|
||||
+ File.separator + "createdInfo.json")); // get file with meta data
|
||||
JSONObject json = (JSONObject) parser.parse(createdInfo); // and turn it into json object
|
||||
|
||||
// write meta information to the object (user information and creation date)
|
||||
@ -89,19 +98,23 @@ public class DefaultHistoryManager implements HistoryManager {
|
||||
obj.put("user", user);
|
||||
}
|
||||
|
||||
dataObj.put("fileType", fileUtility.getFileExtension(document.getTitle()).replace(".", ""));
|
||||
dataObj.put("fileType", fileUtility
|
||||
.getFileExtension(document.getTitle()).replace(".", ""));
|
||||
dataObj.put("key", key);
|
||||
dataObj.put("url", i == curVer ? document.getUrl() :
|
||||
documentManager.getHistoryFileUrl(document.getTitle(), i, "prev" + fileUtility.getFileExtension(document.getTitle()), true));
|
||||
dataObj.put("url", i == curVer ? document.getUrl()
|
||||
: documentManager.getHistoryFileUrl(document.getTitle(), i, "prev" + fileUtility
|
||||
.getFileExtension(document.getTitle()), true));
|
||||
if (!document.getDirectUrl().equals("")) {
|
||||
dataObj.put("directUrl", i == curVer ? document.getDirectUrl() :
|
||||
documentManager.getHistoryFileUrl(document.getTitle(), i, "prev" + fileUtility.getFileExtension(document.getTitle()), false));
|
||||
dataObj.put("directUrl", i == curVer ? document.getDirectUrl()
|
||||
: documentManager.getHistoryFileUrl(document.getTitle(), i, "prev" + fileUtility
|
||||
.getFileExtension(document.getTitle()), false));
|
||||
}
|
||||
dataObj.put("version", i);
|
||||
|
||||
if (i > 1) { //check if the version number is greater than 1
|
||||
// if so, get the path to the changes.json file
|
||||
JSONObject changes = (JSONObject) parser.parse(readFileToEnd(new File(documentManager.versionDir(histDir, i - 1, true) + File.separator + "changes.json")));
|
||||
JSONObject changes = (JSONObject) parser.parse(readFileToEnd(new File(documentManager
|
||||
.versionDir(histDir, i - 1, true) + File.separator + "changes.json")));
|
||||
JSONObject change = (JSONObject) ((JSONArray) changes.get("changes")).get(0);
|
||||
|
||||
// write information about changes to the object
|
||||
@ -110,7 +123,8 @@ public class DefaultHistoryManager implements HistoryManager {
|
||||
obj.put("created", change.get("created"));
|
||||
obj.put("user", change.get("user"));
|
||||
|
||||
Map<String, Object> prev = (Map<String, Object>) histData.get(Integer.toString(i - 2)); // get the history data from the previous file version
|
||||
// get the history data from the previous file version
|
||||
Map<String, Object> prev = (Map<String, Object>) histData.get(Integer.toString(i - 2));
|
||||
Map<String, Object> prevInfo = new HashMap<String, Object>();
|
||||
prevInfo.put("fileType", prev.get("fileType"));
|
||||
prevInfo.put("key", prev.get("key")); // write key and URL information about previous file version
|
||||
@ -118,13 +132,18 @@ public class DefaultHistoryManager implements HistoryManager {
|
||||
if (!document.getDirectUrl().equals("")) {
|
||||
prevInfo.put("directUrl", prev.get("directUrl"));
|
||||
}
|
||||
dataObj.put("previous", prevInfo); // write information about previous file version to the data object
|
||||
|
||||
// write information about previous file version to the data object
|
||||
dataObj.put("previous", prevInfo);
|
||||
// write the path to the diff.zip archive with differences in this file version
|
||||
Integer verdiff = i - 1;
|
||||
dataObj.put("changesUrl", documentManager.getHistoryFileUrl(document.getTitle(), verdiff, "diff.zip", true));
|
||||
dataObj.put("changesUrl", documentManager
|
||||
.getHistoryFileUrl(document.getTitle(), verdiff, "diff.zip", true));
|
||||
}
|
||||
|
||||
if (jwtManager.tokenEnabled()) dataObj.put("token", jwtManager.createToken(dataObj));
|
||||
if (jwtManager.tokenEnabled()) {
|
||||
dataObj.put("token", jwtManager.createToken(dataObj));
|
||||
}
|
||||
|
||||
hist.add(obj);
|
||||
histData.put(Integer.toString(i - 1), dataObj);
|
||||
@ -136,7 +155,8 @@ public class DefaultHistoryManager implements HistoryManager {
|
||||
histObj.put("history", hist);
|
||||
|
||||
try {
|
||||
return new String[]{objectMapper.writeValueAsString(histObj), objectMapper.writeValueAsString(histData)};
|
||||
return new String[]{objectMapper.writeValueAsString(histObj),
|
||||
objectMapper.writeValueAsString(histData)};
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@ -145,7 +165,7 @@ public class DefaultHistoryManager implements HistoryManager {
|
||||
}
|
||||
|
||||
// read a file
|
||||
private String readFileToEnd(File file) {
|
||||
private String readFileToEnd(final File file) {
|
||||
String output = "";
|
||||
try {
|
||||
try (FileInputStream is = new FileInputStream(file)) {
|
||||
|
||||
@ -43,7 +43,7 @@ public class DefaultJwtManager implements JwtManager {
|
||||
private JSONParser parser;
|
||||
|
||||
// create document token
|
||||
public String createToken(Map<String, Object> payloadClaims) {
|
||||
public String createToken(final Map<String, Object> payloadClaims) {
|
||||
try {
|
||||
// build a HMAC signer using a SHA-256 hash
|
||||
Signer signer = HMACSigner.newSHA256Signer(tokenSecret);
|
||||
@ -63,18 +63,20 @@ public class DefaultJwtManager implements JwtManager {
|
||||
}
|
||||
|
||||
// read document token
|
||||
public JWT readToken(String token) {
|
||||
public JWT readToken(final String token) {
|
||||
try {
|
||||
// build a HMAC verifier using the token secret
|
||||
Verifier verifier = HMACVerifier.newVerifier(tokenSecret);
|
||||
return JWT.getDecoder().decode(token, verifier); // verify and decode the encoded string JWT to a rich object
|
||||
|
||||
// verify and decode the encoded string JWT to a rich object
|
||||
return JWT.getDecoder().decode(token, verifier);
|
||||
} catch (Exception exception) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// parse the body
|
||||
public JSONObject parseBody(String payload, String header) {
|
||||
public JSONObject parseBody(final String payload, final String header) {
|
||||
JSONObject body;
|
||||
try {
|
||||
Object obj = parser.parse(payload); // get body parameters by parsing the payload
|
||||
@ -86,7 +88,9 @@ public class DefaultJwtManager implements JwtManager {
|
||||
String token = (String) body.get("token"); // get token from the body
|
||||
if (token == null) { // if token is empty
|
||||
if (header != null && !header.isBlank()) { // and the header is defined
|
||||
token = header.startsWith("Bearer ") ? header.substring(7) : header; // get token from the header (it is placed after the Bearer prefix if it exists)
|
||||
|
||||
// get token from the header (it is placed after the Bearer prefix if it exists)
|
||||
token = header.startsWith("Bearer ") ? header.substring("Bearer ".length()) : header;
|
||||
}
|
||||
}
|
||||
if (token == null || token.isBlank()) {
|
||||
@ -100,7 +104,7 @@ public class DefaultJwtManager implements JwtManager {
|
||||
if (jwt.getObject("payload") != null) { // get payload from the token and check if it is not empty
|
||||
try {
|
||||
@SuppressWarnings("unchecked") LinkedHashMap<String, Object> jwtPayload =
|
||||
(LinkedHashMap<String, Object>)jwt.getObject("payload");
|
||||
(LinkedHashMap<String, Object>) jwt.getObject("payload");
|
||||
|
||||
jwt.claims = jwtPayload;
|
||||
} catch (Exception ex) {
|
||||
|
||||
@ -42,24 +42,27 @@ public class SampleTemplateManager implements TemplateManager {
|
||||
private FileUtility fileUtility;
|
||||
|
||||
// create a template document with the specified name
|
||||
public List<Template> createTemplates(String fileName){
|
||||
public List<Template> createTemplates(final String fileName) {
|
||||
List<Template> templates = List.of(
|
||||
new Template("", "Blank", documentManager.getCreateUrl(fileName, false)), // create a blank template
|
||||
new Template(getTemplateImageUrl(fileName), "With sample content", documentManager.getCreateUrl(fileName, true)) // create a template with sample content using the template image
|
||||
new Template("", "Blank", documentManager
|
||||
.getCreateUrl(fileName, false)), // create a blank template
|
||||
new Template(getTemplateImageUrl(fileName), "With sample content", documentManager
|
||||
.getCreateUrl(fileName,
|
||||
true)) // create a template with sample content using the template image
|
||||
);
|
||||
|
||||
return templates;
|
||||
}
|
||||
|
||||
// get the template image URL for the specified file
|
||||
public String getTemplateImageUrl(String fileName){
|
||||
public String getTemplateImageUrl(final String fileName) {
|
||||
DocumentType fileType = fileUtility.getDocumentType(fileName); // get the file type
|
||||
String path = storagePathBuilder.getServerUrl(true); // get server URL
|
||||
if(fileType.equals(DocumentType.word)){ // get URL to the template image for the word document type
|
||||
if (fileType.equals(DocumentType.word)) { // get URL to the template image for the word document type
|
||||
return path + "/css/img/file_docx.svg";
|
||||
} else if(fileType.equals(DocumentType.slide)){ // get URL to the template image for the slide document type
|
||||
} else if (fileType.equals(DocumentType.slide)) { // get URL to the template image for the slide document type
|
||||
return path + "/css/img/file_pptx.svg";
|
||||
} else if(fileType.equals(DocumentType.cell)){ // get URL to the template image for the cell document type
|
||||
} else if (fileType.equals(DocumentType.cell)) { // get URL to the template image for the cell document type
|
||||
return path + "/css/img/file_xlsx.svg";
|
||||
}
|
||||
return path + "/css/img/file_docx.svg"; // get URL to the template image for the default document type (word)
|
||||
|
||||
@ -28,21 +28,26 @@ import org.springframework.stereotype.Component;
|
||||
@Scope("prototype")
|
||||
@Getter
|
||||
@Setter
|
||||
public class Customization { // the parameters which allow to customize the editor interface so that it looked like your other products (if there are any) and change the presence or absence of the additional buttons, links, change logos and editor owner details
|
||||
/* The parameters which allow to customize the editor interface so that it looked like your
|
||||
other products (if there are any) and change the presence or absence of the additional buttons,
|
||||
links, change logos and editor owner details. */
|
||||
public class Customization {
|
||||
@Autowired
|
||||
private Logo logo; // the image file at the top left corner of the Editor header
|
||||
@Autowired
|
||||
private Goback goback; // the settings for the Open file location menu button and upper right corner button
|
||||
private Boolean autosave = true; // if the Autosave menu option is enabled or disabled
|
||||
private Boolean comments = true; // if the Comments menu button is displayed or hidden
|
||||
private Boolean compactHeader = false; // if the additional action buttons are displayed in the upper part of the editor window header next to the logo (false) or in the toolbar (true)
|
||||
private Boolean compactHeader = false; /* if the additional action buttons are displayed
|
||||
in the upper part of the editor window header next to the logo (false) or in the toolbar (true) */
|
||||
private Boolean compactToolbar = false; // if the top toolbar type displayed is full (false) or compact (true)
|
||||
private Boolean compatibleFeatures = false; // the use of functionality only compatible with the OOXML format
|
||||
private Boolean forcesave = false; // add the request for the forced file saving to the callback handler when saving the document within the document editing service
|
||||
private Boolean forcesave = false; /* add the request for the forced file saving to the callback handler
|
||||
when saving the document within the document editing service */
|
||||
private Boolean help = true; // if the Help menu button is displayed or hidden
|
||||
private Boolean hideRightMenu = false; // if the right menu is displayed or hidden on first loading
|
||||
private Boolean hideRulers = false; // if the editor rulers are displayed or hidden
|
||||
private Boolean submitForm = false; // if the Submit form button is displayed or hidden
|
||||
private Boolean about = true;
|
||||
private Boolean feedback =true;
|
||||
private Boolean feedback = true;
|
||||
}
|
||||
|
||||
@ -28,9 +28,13 @@ import org.springframework.stereotype.Component;
|
||||
@Scope("prototype")
|
||||
@Getter
|
||||
@Setter
|
||||
public class Embedded { // the parameters which allow to change the settings which define the behavior of the buttons in the embedded mode
|
||||
private String embedUrl; // the absolute URL to the document serving as a source file for the document embedded into the web page
|
||||
private String saveUrl; // the absolute URL that will allow the document to be saved onto the user personal computer
|
||||
/* The parameters which allow to change the settings
|
||||
which define the behavior of the buttons in the embedded mode */
|
||||
public class Embedded {
|
||||
private String embedUrl; /* the absolute URL to the document serving as a source file for the document embedded
|
||||
into the web page */
|
||||
private String saveUrl; /* the absolute URL that will allow the document to be saved
|
||||
onto the user personal computer */
|
||||
private String shareUrl; // the absolute URL that will allow other users to share this document
|
||||
private ToolbarDocked toolbarDocked; // the place for the embedded viewer toolbar, can be either top or bottom
|
||||
}
|
||||
|
||||
@ -38,7 +38,8 @@ public class Goback { // the settings for the Open file location menu button an
|
||||
private String indexMapping;
|
||||
|
||||
@Getter
|
||||
private String url; // the absolute URL to the website address which will be opened when clicking the Open file location menu button
|
||||
private String url; /* the absolute URL to the website address which will be opened
|
||||
when clicking the Open file location menu button */
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
|
||||
@ -31,7 +31,9 @@ import java.util.Locale;
|
||||
@Scope("prototype")
|
||||
@Getter
|
||||
@Setter
|
||||
public class Info { // the additional parameters for the document (document owner, folder where the document is stored, uploading date, sharing settings)
|
||||
/* The additional parameters for the document (document owner, folder where the document is stored,
|
||||
uploading date, sharing settings) */
|
||||
public class Info {
|
||||
private String owner = "Me"; // the name of the document owner/creator
|
||||
private Boolean favorite = null; // the highlighting state of the Favorite icon
|
||||
private String uploaded = getDate(); // the document uploading date
|
||||
|
||||
@ -0,0 +1,48 @@
|
||||
/**
|
||||
*
|
||||
* (c) Copyright Ascensio System SIA 2023
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.onlyoffice.integration.documentserver.models.enums;
|
||||
|
||||
public enum ConvertErrorType {
|
||||
EMPTY_ERROR(0, ""),
|
||||
CONVERTATION_UNKNOWN(-1, "Error convertation unknown"),
|
||||
CONVERTATION_TIMEOUT(-2, "Error convertation timeout"),
|
||||
CONVERTATION_ERROR(-3, "Error convertation error"),
|
||||
DOWNLOAD_ERROR(-4, "Error download error"),
|
||||
UNEXPECTED_GUID_ERROR(-5, "Error unexpected guid"),
|
||||
DATABASE_ERROR(-6, "Error database"),
|
||||
DOCUMENT_REQUEST_ERROR(-7, "Error document request"),
|
||||
DOCUMENT_VKEY_ERROR(-8, "Error document VKey");
|
||||
|
||||
private final int code;
|
||||
private final String label;
|
||||
|
||||
ConvertErrorType(final int codeParam, final String labelParam) {
|
||||
this.code = codeParam;
|
||||
this.label = labelParam;
|
||||
}
|
||||
|
||||
public static String labelOfCode(final int code) {
|
||||
for (ConvertErrorType convertErrorType : values()) {
|
||||
if (convertErrorType.code == code) {
|
||||
return convertErrorType.label;
|
||||
}
|
||||
}
|
||||
return "ErrorCode = " + code;
|
||||
}
|
||||
}
|
||||
@ -31,13 +31,16 @@ import org.springframework.stereotype.Component;
|
||||
@Setter
|
||||
public class Document { // the parameters pertaining to the document (title, url, file type, etc.)
|
||||
@Autowired
|
||||
private Info info; // additional parameters for the document (document owner, folder where the document is stored, uploading date, sharing settings)
|
||||
private Info info; /* additional parameters for the document (document owner, folder where the document is stored,
|
||||
uploading date, sharing settings) */
|
||||
@Autowired
|
||||
private Permission permissions; // the permission for the document to be edited and downloaded or not
|
||||
private String fileType; // the file type for the source viewed or edited document
|
||||
private String key; // the unique document identifier used by the service to recognize the document
|
||||
private String urlUser; // the absolute URL that will allow the document to be saved onto the user personal computer
|
||||
private String title; // the desired file name for the viewed or edited document which will also be used as file name when the document is downloaded
|
||||
private String urlUser; /* the absolute URL that will allow the document to be saved
|
||||
onto the user personal computer */
|
||||
private String title; /* the desired file name for the viewed or edited document which will also be used
|
||||
as file name when the document is downloaded */
|
||||
private String url; // the absolute URL where the source viewed or edited document is stored
|
||||
private String directUrl;
|
||||
}
|
||||
|
||||
@ -21,7 +21,9 @@ package com.onlyoffice.integration.documentserver.models.filemodel;
|
||||
import com.onlyoffice.integration.documentserver.models.configurations.Customization;
|
||||
import com.onlyoffice.integration.documentserver.models.configurations.Embedded;
|
||||
import com.onlyoffice.integration.documentserver.models.enums.Mode;
|
||||
import lombok.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Component;
|
||||
@ -34,18 +36,24 @@ import java.util.List;
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class EditorConfig { // the parameters pertaining to the editor interface: opening mode (viewer or editor), interface language, additional buttons, etc.
|
||||
private HashMap<String, Object> actionLink = null; // the data which contains the information about the action in the document that will be scrolled to
|
||||
public class EditorConfig { /* the parameters pertaining to the editor interface: opening mode (viewer or editor),
|
||||
interface language, additional buttons, etc. */
|
||||
private HashMap<String, Object> actionLink = null; /* the data which contains the information about the
|
||||
action in the document that will be scrolled to */
|
||||
private String callbackUrl; // the absolute URL to the document storage service
|
||||
private HashMap<String, Object> coEditing = null;
|
||||
private String createUrl; // the absolute URL of the document where it will be created and available after creation
|
||||
@Autowired
|
||||
private Customization customization; // the parameters which allow to customize the editor interface so that it looked like your other products (if there are any) and change the presence or absence of the additional buttons, links, change logos and editor owner details
|
||||
private Customization customization; /* the parameters which allow to customize the editor interface
|
||||
so that it looked like your other products (if there are any) and change the presence or absence
|
||||
of the additional buttons, links, change logos and editor owner details */
|
||||
@Autowired
|
||||
private Embedded embedded; // the parameters which allow to change the settings which define the behavior of the buttons in the embedded mode
|
||||
private Embedded embedded; /* the parameters which allow to change the settings which define
|
||||
the behavior of the buttons in the embedded mode */
|
||||
private String lang; // the editor interface language
|
||||
private Mode mode; // the editor opening mode
|
||||
@Autowired
|
||||
private User user; // the user currently viewing or editing the document
|
||||
private List<Template> templates; // the presence or absence of the templates in the <b>Create New...</b> menu option
|
||||
private List<Template> templates; /* the presence or absence
|
||||
of the templates in the <b>Create New...</b> menu option */
|
||||
}
|
||||
|
||||
@ -30,12 +30,15 @@ import org.springframework.stereotype.Component;
|
||||
@Scope("prototype")
|
||||
@Getter
|
||||
@Setter
|
||||
public class FileModel { // the file base parameters which include the platform type used, document display size (width and height) and type of the document opened
|
||||
/* the file base parameters which include the platform type used,
|
||||
document display size (width and height) and type of the document opened */
|
||||
public class FileModel {
|
||||
@Autowired
|
||||
private Document document; // the parameters pertaining to the document (title, url, file type, etc.)
|
||||
private DocumentType documentType; // the document type to be opened
|
||||
@Autowired
|
||||
private EditorConfig editorConfig; // the parameters pertaining to the editor interface: opening mode (viewer or editor), interface language, additional buttons, etc.
|
||||
private EditorConfig editorConfig; /* the parameters pertaining to the
|
||||
editor interface: opening mode (viewer or editor), interface language, additional buttons, etc. */
|
||||
private String token; // the encrypted signature added to the Document Server config
|
||||
private Type type; // the platform type used to access the document
|
||||
}
|
||||
|
||||
@ -40,7 +40,8 @@ public class Permission extends AbstractModel { // the permission for the docum
|
||||
private Boolean edit = true; // if the document can be edited or only viewed
|
||||
private Boolean print = true; // if the document can be printed or not
|
||||
private Boolean fillForms = true; // if the forms can be filled
|
||||
private Boolean modifyFilter = true; // if the filter can applied globally (true) affecting all the other users, or locally (false)
|
||||
private Boolean modifyFilter = true; /* if the filter can applied globally (true) affecting all the
|
||||
other users, or locally (false) */
|
||||
private Boolean modifyContentControl = true; // if the content control settings can be changed
|
||||
private Boolean review = true; // if the document can be reviewed or not
|
||||
private Boolean chat = true; // if a chat can be used
|
||||
|
||||
@ -34,9 +34,9 @@ public class User extends AbstractModel {
|
||||
private String group;
|
||||
|
||||
// the user configuration parameters
|
||||
public void configure(int id, String name, String group){
|
||||
this.id = "uid-"+id; // the user id
|
||||
this.name = name; // the user name
|
||||
this.group = group; // the group the user belongs to
|
||||
public void configure(final int idParam, final String nameParam, final String groupParam) {
|
||||
this.id = "uid-" + idParam; // the user id
|
||||
this.name = nameParam; // the user name
|
||||
this.group = groupParam; // the group the user belongs to
|
||||
}
|
||||
}
|
||||
|
||||
@ -22,13 +22,17 @@ import java.util.List;
|
||||
|
||||
public class SerializerFilter {
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
public boolean equals(final Object obj) {
|
||||
if (obj instanceof List) {
|
||||
if(((List<?>) obj).size() == 1 && ((List<?>) obj).get(0) == FilterState.NULL.toString()){
|
||||
if (((List<?>) obj).size() == 1 && ((List<?>) obj).get(0) == FilterState.NULL.toString()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return super.hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
@ -20,6 +20,7 @@ package com.onlyoffice.integration.documentserver.storage;
|
||||
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Path;
|
||||
@ -34,8 +35,8 @@ public interface FileStorageMutator {
|
||||
boolean writeToFile(String pathName, String payload); // write the payload to the file
|
||||
boolean moveFile(Path source, Path destination); // move a file to the specified destination
|
||||
Resource loadFileAsResource(String fileName); // load file as a resource
|
||||
Resource loadFileAsResourceHistory(String fileName,String version,String file); // load file as a resource
|
||||
Resource loadFileAsResourceHistory(String fileName, String version, String file); // load file as a resource
|
||||
File[] getStoredFiles(); // get a collection of all the stored files
|
||||
void createMeta(String fileName, String uid, String uname); // create the file meta information
|
||||
boolean createOrUpdateFile(Path path, InputStream stream); // create or update a file
|
||||
boolean createOrUpdateFile(Path path, ByteArrayInputStream stream); // create or update a file
|
||||
}
|
||||
|
||||
@ -26,5 +26,6 @@ public interface FileStoragePathBuilder {
|
||||
String getServerUrl(Boolean forDocumentServer); // get the server URL
|
||||
String getHistoryDir(String fileName); // get the history directory
|
||||
int getFileVersion(String historyPath, Boolean ifIndexPage); // get the file version
|
||||
String getForcesavePath(String fileName, Boolean create); // get the path where all the forcely saved file versions are saved or create it
|
||||
String getForcesavePath(String fileName, Boolean create); /* get the path where all the
|
||||
forcely saved file versions are saved or create it */
|
||||
}
|
||||
|
||||
@ -31,8 +31,16 @@ import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.FileSystemUtils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.UnknownHostException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
@ -43,7 +51,9 @@ import java.util.Date;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
//TODO: Refactoring
|
||||
import static com.onlyoffice.integration.documentserver.util.Constants.KILOBYTE_SIZE;
|
||||
|
||||
// todo: Refactoring
|
||||
@Component
|
||||
@Primary
|
||||
public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuilder {
|
||||
@ -69,12 +79,12 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
/*
|
||||
This Storage configuration method should be called whenever a new storage folder is required
|
||||
*/
|
||||
public void configure(String address) {
|
||||
public void configure(final String address) {
|
||||
this.storageAddress = address;
|
||||
if(this.storageAddress == null){
|
||||
try{
|
||||
if (this.storageAddress == null) {
|
||||
try {
|
||||
this.storageAddress = InetAddress.getLocalHost().getHostAddress();
|
||||
} catch (UnknownHostException e){
|
||||
} catch (UnknownHostException e) {
|
||||
this.storageAddress = "unknown_storage";
|
||||
}
|
||||
}
|
||||
@ -83,7 +93,7 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
}
|
||||
|
||||
// get the storage directory
|
||||
public String getStorageLocation(){
|
||||
public String getStorageLocation() {
|
||||
String serverPath = System.getProperty("user.dir"); // get the path to the server
|
||||
String directory; // create the storage directory
|
||||
if (Paths.get(this.storageAddress).isAbsolute()) {
|
||||
@ -102,7 +112,7 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
}
|
||||
|
||||
// get the directory of the specified file
|
||||
public String getFileLocation(String fileName){
|
||||
public String getFileLocation(final String fileName) {
|
||||
if (fileName.contains(File.separator)) {
|
||||
return getStorageLocation() + fileName;
|
||||
}
|
||||
@ -110,8 +120,10 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
}
|
||||
|
||||
// create a new directory if it does not exist
|
||||
public void createDirectory(Path path){
|
||||
if (Files.exists(path)) return;
|
||||
public void createDirectory(final Path path) {
|
||||
if (Files.exists(path)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Files.createDirectories(path);
|
||||
} catch (IOException e) {
|
||||
@ -120,18 +132,16 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
}
|
||||
|
||||
// create a new file if it does not exist
|
||||
public boolean createFile(Path path, InputStream stream){
|
||||
if (Files.exists(path)){
|
||||
public boolean createFile(final Path path, final InputStream stream) {
|
||||
if (Files.exists(path)) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
File file = Files.createFile(path).toFile(); // create a new file in the specified path
|
||||
try (FileOutputStream out = new FileOutputStream(file))
|
||||
{
|
||||
try (FileOutputStream out = new FileOutputStream(file)) {
|
||||
int read;
|
||||
final byte[] bytes = new byte[1024];
|
||||
while ((read = stream.read(bytes)) != -1)
|
||||
{
|
||||
final byte[] bytes = new byte[KILOBYTE_SIZE];
|
||||
while ((read = stream.read(bytes)) != -1) {
|
||||
out.write(bytes, 0, read); // write bytes to the output stream
|
||||
}
|
||||
out.flush(); // force write data to the output stream that can be cached in the current thread
|
||||
@ -143,38 +153,59 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
}
|
||||
|
||||
// delete a file
|
||||
public boolean deleteFile(String fileName){
|
||||
fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8); // decode a x-www-form-urlencoded string
|
||||
if (fileName.isBlank()) return false;
|
||||
public boolean deleteFile(final String fileNameParam) {
|
||||
String fileName = URLDecoder
|
||||
.decode(fileNameParam, StandardCharsets.UTF_8); // decode a x-www-form-urlencoded string
|
||||
if (fileName.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String filenameWithoutExt = fileUtility.getFileNameWithoutExtension(fileName); // get file name without extension
|
||||
String filenameWithoutExt = fileUtility
|
||||
.getFileNameWithoutExtension(fileName); // get file name without extension
|
||||
|
||||
Path filePath = fileName.contains(File.separator) ? Paths.get(fileName) : Paths.get(getFileLocation(fileName)); // get the path to the file
|
||||
Path filePathWithoutExt = fileName.contains(File.separator) ? Paths.get(filenameWithoutExt) : Paths.get(getStorageLocation() + filenameWithoutExt); // get the path to the file without extension
|
||||
Path filePath = fileName.contains(File.separator)
|
||||
? Paths.get(fileName) : Paths.get(getFileLocation(fileName)); // get the path to the file
|
||||
Path filePathWithoutExt = fileName.contains(File.separator)
|
||||
? Paths.get(filenameWithoutExt) : Paths
|
||||
.get(getStorageLocation() + filenameWithoutExt); // get the path to the file without extension
|
||||
|
||||
boolean fileDeleted = FileSystemUtils.deleteRecursively(filePath.toFile()); // delete the specified file; for directories, recursively delete any nested directories or files as well
|
||||
boolean fileWithoutExtDeleted = FileSystemUtils.deleteRecursively(filePathWithoutExt.toFile()); // delete the specified file without extension; for directories, recursively delete any nested directories or files as well
|
||||
// delete the specified file; for directories, recursively delete any nested directories or files as well
|
||||
boolean fileDeleted = FileSystemUtils.deleteRecursively(filePath.toFile());
|
||||
/* delete the specified file without extension; for directories,
|
||||
recursively delete any nested directories or files as well */
|
||||
boolean fileWithoutExtDeleted = FileSystemUtils.deleteRecursively(filePathWithoutExt.toFile());
|
||||
|
||||
return fileDeleted && fileWithoutExtDeleted;
|
||||
}
|
||||
|
||||
// delete file history
|
||||
public boolean deleteFileHistory(String fileName) {
|
||||
fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8); // decode a x-www-form-urlencoded string
|
||||
if (fileName.isBlank()) return false;
|
||||
public boolean deleteFileHistory(final String fileNameParam) {
|
||||
String fileName = URLDecoder
|
||||
.decode(fileNameParam, StandardCharsets.UTF_8); // decode a x-www-form-urlencoded string
|
||||
if (fileName.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Path fileHistoryPath = Paths.get(getStorageLocation() + getHistoryDir(fileName)); // get the path to the history file
|
||||
Path fileHistoryPathWithoutExt = Paths.get(getStorageLocation() + getHistoryDir(fileUtility.getFileNameWithoutExtension(fileName))); // get the path to the history file without extension
|
||||
Path fileHistoryPath = Paths
|
||||
.get(getStorageLocation() + getHistoryDir(fileName)); // get the path to the history file
|
||||
Path fileHistoryPathWithoutExt = Paths.get(getStorageLocation() + getHistoryDir(fileUtility
|
||||
.getFileNameWithoutExtension(fileName))); // get the path to the history file without extension
|
||||
|
||||
boolean historyDeleted = FileSystemUtils.deleteRecursively(fileHistoryPath.toFile()); // delete the specified history file; for directories, recursively delete any nested directories or files as well
|
||||
boolean historyWithoutExtDeleted = FileSystemUtils.deleteRecursively(fileHistoryPathWithoutExt.toFile()); // delete the specified history file without extension; for directories, recursively delete any nested directories or files as well
|
||||
/* delete the specified history file; for directories,
|
||||
recursively delete any nested directories or files as well */
|
||||
boolean historyDeleted = FileSystemUtils.deleteRecursively(fileHistoryPath.toFile());
|
||||
|
||||
/* delete the specified history file without extension; for directories,
|
||||
recursively delete any nested directories or files as well */
|
||||
boolean historyWithoutExtDeleted = FileSystemUtils.deleteRecursively(fileHistoryPathWithoutExt.toFile());
|
||||
|
||||
return historyDeleted || historyWithoutExtDeleted;
|
||||
}
|
||||
|
||||
// update a file
|
||||
public String updateFile(String fileName, byte[] bytes) {
|
||||
Path path = fileUtility.generateFilepath(getStorageLocation(), fileName); // generate the path to the specified file
|
||||
public String updateFile(final String fileName, final byte[] bytes) {
|
||||
Path path = fileUtility
|
||||
.generateFilepath(getStorageLocation(), fileName); // generate the path to the specified file
|
||||
try {
|
||||
Files.write(path, bytes); // write new information in the bytes format to the file
|
||||
return path.getFileName().toString();
|
||||
@ -185,7 +216,7 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
}
|
||||
|
||||
// move a file to the specified destination
|
||||
public boolean moveFile(Path source, Path destination){
|
||||
public boolean moveFile(final Path source, final Path destination) {
|
||||
try {
|
||||
Files.move(source, destination,
|
||||
new StandardCopyOption[]{StandardCopyOption.REPLACE_EXISTING});
|
||||
@ -197,7 +228,7 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
}
|
||||
|
||||
// write the payload to the file
|
||||
public boolean writeToFile(String pathName, String payload){
|
||||
public boolean writeToFile(final String pathName, final String payload) {
|
||||
try (FileWriter fw = new FileWriter(pathName)) {
|
||||
fw.write(payload);
|
||||
return true;
|
||||
@ -208,16 +239,20 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
}
|
||||
|
||||
// get the path where all the forcely saved file versions are saved or create it
|
||||
public String getForcesavePath(String fileName, Boolean create) {
|
||||
public String getForcesavePath(final String fileName, final Boolean create) {
|
||||
String directory = getStorageLocation();
|
||||
|
||||
Path path = Paths.get(directory); // get the storage directory
|
||||
if (!Files.exists(path)) return "";
|
||||
if (!Files.exists(path)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
directory = getFileLocation(fileName) + historyPostfix + File.separator;
|
||||
|
||||
path = Paths.get(directory); // get the history file directory
|
||||
if (!create && !Files.exists(path)) return "";
|
||||
if (!create && !Files.exists(path)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
createDirectory(path); // create a new directory where all the forcely saved file versions will be saved
|
||||
|
||||
@ -231,29 +266,35 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
}
|
||||
|
||||
// load file as a resource
|
||||
public Resource loadFileAsResource(String fileName){
|
||||
String fileLocation = getForcesavePath(fileName, false); // get the path where all the forcely saved file versions are saved
|
||||
if (fileLocation.isBlank()){ // if file location is empty
|
||||
public Resource loadFileAsResource(final String fileName) {
|
||||
String fileLocation = getForcesavePath(fileName,
|
||||
false); // get the path where all the forcely saved file versions are saved
|
||||
if (fileLocation.isBlank()) { // if file location is empty
|
||||
fileLocation = getFileLocation(fileName); // get it by the file name
|
||||
}
|
||||
try {
|
||||
Path filePath = Paths.get(fileLocation); // get the path to the file location
|
||||
Resource resource = new UrlResource(filePath.toUri()); // convert the file path to URL
|
||||
if(resource.exists()) return resource;
|
||||
if (resource.exists()) {
|
||||
return resource;
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Resource loadFileAsResourceHistory(String fileName,String version,String file){
|
||||
public Resource loadFileAsResourceHistory(final String fileName, final String version, final String file) {
|
||||
|
||||
String fileLocation = getStorageLocation() + fileName + "-hist" + File.separator + version + File.separator + file; // get it by the file name
|
||||
String fileLocation = getStorageLocation() + fileName + "-hist" + File.separator + version
|
||||
+ File.separator + file; // get it by the file name
|
||||
|
||||
try {
|
||||
Path filePath = Paths.get(fileLocation); // get the path to the file location
|
||||
Resource resource = new UrlResource(filePath.toUri()); // convert the file path to URL
|
||||
if(resource.exists()) return resource;
|
||||
if (resource.exists()) {
|
||||
return resource;
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@ -261,14 +302,15 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
}
|
||||
|
||||
// get a collection of all the stored files
|
||||
public File[] getStoredFiles()
|
||||
{
|
||||
public File[] getStoredFiles() {
|
||||
File file = new File(getStorageLocation());
|
||||
return file.listFiles(pathname -> pathname.isFile());
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public void createMeta(String fileName, String uid, String uname) { // create the file meta information
|
||||
public void createMeta(final String fileName,
|
||||
final String uid,
|
||||
final String uname) { // create the file meta information
|
||||
String histDir = getHistoryDir(getFileLocation(fileName)); // get the history directory
|
||||
|
||||
Path path = Paths.get(histDir); // get the path to the history directory
|
||||
@ -276,25 +318,28 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
|
||||
// create the json object with the file metadata
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("created", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); // put the file creation date to the json object
|
||||
json.put("created", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
|
||||
.format(new Date())); // put the file creation date to the json object
|
||||
json.put("id", uid); // put the user ID to the json object
|
||||
json.put("name", uname); // put the user name to the json object
|
||||
|
||||
File meta = new File(histDir + File.separator + "createdInfo.json"); // create the createdInfo.json file with the file meta information
|
||||
File meta = new File(histDir + File.separator
|
||||
+ "createdInfo.json"); // create the createdInfo.json file with the file meta information
|
||||
try (FileWriter writer = new FileWriter(meta)) {
|
||||
json.writeJSONString(writer);
|
||||
} catch (IOException ex){
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// create or update a file
|
||||
public boolean createOrUpdateFile(Path path, InputStream stream) {
|
||||
if (!Files.exists(path)){ // if the specified file does not exist
|
||||
public boolean createOrUpdateFile(final Path path, final ByteArrayInputStream stream) {
|
||||
if (!Files.exists(path)) { // if the specified file does not exist
|
||||
return createFile(path, stream); // create it in the specified directory
|
||||
} else {
|
||||
try {
|
||||
Files.write(path, stream.readAllBytes()); // otherwise, write new information in the bytes format to the file
|
||||
Files.write(path, stream
|
||||
.readAllBytes()); // otherwise, write new information in the bytes format to the file
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
@ -304,37 +349,41 @@ public class LocalFileStorage implements FileStorageMutator, FileStoragePathBuil
|
||||
}
|
||||
|
||||
// get the server URL
|
||||
public String getServerUrl(Boolean forDocumentServer) {
|
||||
public String getServerUrl(final Boolean forDocumentServer) {
|
||||
if (forDocumentServer && !docserviceUrlExample.equals("")) {
|
||||
return docserviceUrlExample;
|
||||
} else {
|
||||
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
|
||||
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
|
||||
+ request.getContextPath();
|
||||
}
|
||||
}
|
||||
|
||||
// get the history directory
|
||||
public String getHistoryDir(String path)
|
||||
{
|
||||
public String getHistoryDir(final String path) {
|
||||
return path + historyPostfix;
|
||||
}
|
||||
|
||||
// get the file version
|
||||
public int getFileVersion(String historyPath, Boolean ifIndexPage)
|
||||
{
|
||||
public int getFileVersion(final String historyPath, final Boolean ifIndexPage) {
|
||||
Path path;
|
||||
if (ifIndexPage) { // if the start page is opened
|
||||
path = Paths.get(getStorageLocation() + getHistoryDir(historyPath)); // get the storage directory and add the history directory to it
|
||||
path = Paths.get(getStorageLocation()
|
||||
+ getHistoryDir(historyPath)); // get the storage directory and add the history directory to it
|
||||
} else {
|
||||
path = Paths.get(historyPath); // otherwise, get the path to the history directory
|
||||
if (!Files.exists(path)) return 1; // if the history directory does not exist, then the file version is 1
|
||||
if (!Files.exists(path)) {
|
||||
return 1; // if the history directory does not exist, then the file version is 1
|
||||
}
|
||||
}
|
||||
|
||||
try (Stream<Path> stream = Files.walk(path, 1)) { // run through all the files in the history directory
|
||||
// run through all the files in the history directory
|
||||
try (Stream<Path> stream = Files.walk(path, 1)) {
|
||||
return stream
|
||||
.filter(file -> Files.isDirectory(file)) // take only directories from the history folder
|
||||
.map(Path::getFileName) // get file names
|
||||
.map(Path::toString) // and convert them into strings
|
||||
.collect(Collectors.toSet()).size(); // convert stream into set and get its size which specifies the file version
|
||||
.collect(Collectors.toSet()).size(); /* convert stream into set
|
||||
and get its size which specifies the file version */
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
|
||||
@ -0,0 +1,33 @@
|
||||
/**
|
||||
*
|
||||
* (c) Copyright Ascensio System SIA 2023
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.onlyoffice.integration.documentserver.util;
|
||||
|
||||
public final class Constants {
|
||||
public static final Integer MAX_FILE_SIZE = 5 * 1024 * 1024;
|
||||
public static final Integer CONVERT_TIMEOUT_MS = 120000;
|
||||
public static final String CONVERTATION_ERROR_MESSAGE_TEMPLATE = "Error occurred in the ConvertService: ";
|
||||
public static final Long FULL_LOADING_IN_PERCENT = 100L;
|
||||
public static final Integer FILE_SAVE_TIMEOUT = 5000;
|
||||
public static final Integer MAX_KEY_LENGTH = 20;
|
||||
public static final Integer ANONYMOUS_USER_ID = 4;
|
||||
public static final Integer KILOBYTE_SIZE = 1024;
|
||||
|
||||
private Constants() { }
|
||||
}
|
||||
|
||||
@ -25,9 +25,11 @@ import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class Misc {
|
||||
public String convertUserDescriptions(String username, List<String> description){ // cenvert user descriptions to the specified format
|
||||
String result = "<div class=\"user-descr\"><b>"+username+"</b><br/><ul>"+description.
|
||||
stream().map(text -> "<li>"+text+"</li>")
|
||||
|
||||
// convert user descriptions to the specified format
|
||||
public String convertUserDescriptions(final String username, final List<String> description) {
|
||||
String result = "<div class=\"user-descr\"><b>" + username + "</b><br/><ul>" + description.
|
||||
stream().map(text -> "<li>" + text + "</li>")
|
||||
.collect(Collectors.joining()) + "</ul></div>";
|
||||
return result;
|
||||
}
|
||||
|
||||
@ -41,20 +41,21 @@ public final class SSLUtils {
|
||||
private final HostnameVerifier jvmHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
|
||||
|
||||
private final HostnameVerifier trivialHostnameVerifier = new HostnameVerifier() {
|
||||
public boolean verify(String hostname, SSLSession sslSession) {
|
||||
public boolean verify(final String hostname, final SSLSession sslSession) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[] { new X509TrustManager() {
|
||||
private final TrustManager[] unquestioningTrustManager = new TrustManager[] {
|
||||
new X509TrustManager() {
|
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void checkClientTrusted(X509Certificate[] certs, String authType) {
|
||||
public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
|
||||
}
|
||||
|
||||
public void checkServerTrusted(X509Certificate[] certs, String authType) {
|
||||
public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
|
||||
}
|
||||
} };
|
||||
|
||||
@ -62,7 +63,7 @@ public final class SSLUtils {
|
||||
HttpsURLConnection.setDefaultHostnameVerifier(trivialHostnameVerifier);
|
||||
// Install the all-trusting trust manager
|
||||
SSLContext sc = SSLContext.getInstance("SSL");
|
||||
sc.init(null, UNQUESTIONING_TRUST_MANAGER, null);
|
||||
sc.init(null, unquestioningTrustManager, null);
|
||||
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
|
||||
}
|
||||
|
||||
@ -74,4 +75,4 @@ public final class SSLUtils {
|
||||
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@ -19,7 +19,6 @@
|
||||
package com.onlyoffice.integration.documentserver.util.file;
|
||||
|
||||
import com.onlyoffice.integration.documentserver.models.enums.DocumentType;
|
||||
import lombok.SneakyThrows;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
@ -31,6 +30,8 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static com.onlyoffice.integration.documentserver.util.Constants.MAX_FILE_SIZE;
|
||||
|
||||
@Component
|
||||
@Qualifier("default")
|
||||
public class DefaultFileUtility implements FileUtility {
|
||||
@ -50,7 +51,7 @@ public class DefaultFileUtility implements FileUtility {
|
||||
private String docserviceFillDocs;
|
||||
|
||||
// document extensions
|
||||
private List<String> ExtsDocument = Arrays.asList(
|
||||
private List<String> extsDocument = Arrays.asList(
|
||||
".doc", ".docx", ".docm",
|
||||
".dot", ".dotx", ".dotm",
|
||||
".odt", ".fodt", ".ott", ".rtf", ".txt",
|
||||
@ -58,42 +59,45 @@ public class DefaultFileUtility implements FileUtility {
|
||||
".pdf", ".djvu", ".fb2", ".epub", ".xps", ".oform");
|
||||
|
||||
// spreadsheet extensions
|
||||
private List<String> ExtsSpreadsheet = Arrays.asList(
|
||||
private List<String> extsSpreadsheet = Arrays.asList(
|
||||
".xls", ".xlsx", ".xlsm", ".xlsb",
|
||||
".xlt", ".xltx", ".xltm",
|
||||
".ods", ".fods", ".ots", ".csv");
|
||||
|
||||
// presentation extensions
|
||||
private List<String> ExtsPresentation = Arrays.asList(
|
||||
private List<String> extsPresentation = Arrays.asList(
|
||||
".pps", ".ppsx", ".ppsm",
|
||||
".ppt", ".pptx", ".pptm",
|
||||
".pot", ".potx", ".potm",
|
||||
".odp", ".fodp", ".otp");
|
||||
|
||||
// get the document type
|
||||
public DocumentType getDocumentType(String fileName)
|
||||
{
|
||||
public DocumentType getDocumentType(final String fileName) {
|
||||
String ext = getFileExtension(fileName).toLowerCase(); // get file extension from its name
|
||||
// word type for document extensions
|
||||
if (ExtsDocument.contains(ext))
|
||||
if (extsDocument.contains(ext)) {
|
||||
return DocumentType.word;
|
||||
}
|
||||
|
||||
// cell type for spreadsheet extensions
|
||||
if (ExtsSpreadsheet.contains(ext))
|
||||
if (extsSpreadsheet.contains(ext)) {
|
||||
return DocumentType.cell;
|
||||
}
|
||||
|
||||
// slide type for presentation extensions
|
||||
if (ExtsPresentation.contains(ext))
|
||||
if (extsPresentation.contains(ext)) {
|
||||
return DocumentType.slide;
|
||||
}
|
||||
|
||||
// default file type is word
|
||||
return DocumentType.word;
|
||||
}
|
||||
|
||||
// get file name from its URL
|
||||
public String getFileName(String url)
|
||||
{
|
||||
if (url == null) return "";
|
||||
public String getFileName(final String url) {
|
||||
if (url == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// get file name from the last part of URL
|
||||
String fileName = url.substring(url.lastIndexOf('/') + 1);
|
||||
@ -102,62 +106,62 @@ public class DefaultFileUtility implements FileUtility {
|
||||
}
|
||||
|
||||
// get file name without extension
|
||||
public String getFileNameWithoutExtension(String url)
|
||||
{
|
||||
public String getFileNameWithoutExtension(final String url) {
|
||||
String fileName = getFileName(url);
|
||||
if (fileName == null) return null;
|
||||
if (fileName == null) {
|
||||
return null;
|
||||
}
|
||||
String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
|
||||
return fileNameWithoutExt;
|
||||
}
|
||||
|
||||
// get file extension from URL
|
||||
public String getFileExtension(String url)
|
||||
{
|
||||
public String getFileExtension(final String url) {
|
||||
String fileName = getFileName(url);
|
||||
if (fileName == null) return null;
|
||||
if (fileName == null) {
|
||||
return null;
|
||||
}
|
||||
String fileExt = fileName.substring(fileName.lastIndexOf("."));
|
||||
return fileExt.toLowerCase();
|
||||
}
|
||||
|
||||
// get an editor internal extension
|
||||
public String getInternalExtension(DocumentType type)
|
||||
{
|
||||
public String getInternalExtension(final DocumentType type) {
|
||||
// .docx for word file type
|
||||
if (type.equals(DocumentType.word))
|
||||
if (type.equals(DocumentType.word)) {
|
||||
return ".docx";
|
||||
}
|
||||
|
||||
// .xlsx for cell file type
|
||||
if (type.equals(DocumentType.cell))
|
||||
if (type.equals(DocumentType.cell)) {
|
||||
return ".xlsx";
|
||||
}
|
||||
|
||||
// .pptx for slide file type
|
||||
if (type.equals(DocumentType.slide))
|
||||
if (type.equals(DocumentType.slide)) {
|
||||
return ".pptx";
|
||||
}
|
||||
|
||||
// the default file type is .docx
|
||||
return ".docx";
|
||||
}
|
||||
|
||||
public List<String> getFillExts()
|
||||
{
|
||||
public List<String> getFillExts() {
|
||||
return Arrays.asList(docserviceFillDocs.split("\\|"));
|
||||
}
|
||||
|
||||
// get file extensions that can be viewed
|
||||
public List<String> getViewedExts()
|
||||
{
|
||||
public List<String> getViewedExts() {
|
||||
return Arrays.asList(docserviceViewedDocs.split("\\|"));
|
||||
}
|
||||
|
||||
// get file extensions that can be edited
|
||||
public List<String> getEditedExts()
|
||||
{
|
||||
public List<String> getEditedExts() {
|
||||
return Arrays.asList(docserviceEditedDocs.split("\\|"));
|
||||
}
|
||||
|
||||
// get file extensions that can be converted
|
||||
public List<String> getConvertExts()
|
||||
{
|
||||
public List<String> getConvertExts() {
|
||||
return Arrays.asList(docserviceConvertDocs.split("\\|"));
|
||||
}
|
||||
|
||||
@ -174,23 +178,26 @@ public class DefaultFileUtility implements FileUtility {
|
||||
}
|
||||
|
||||
// generate the file path from file directory and name
|
||||
public Path generateFilepath(String directory, String fullFileName){
|
||||
public Path generateFilepath(final String directory, final String fullFileName) {
|
||||
String fileName = getFileNameWithoutExtension(fullFileName); // get file name without extension
|
||||
String fileExtension = getFileExtension(fullFileName); // get file extension
|
||||
Path path = Paths.get(directory+fullFileName); // get the path to the files with the specified name
|
||||
Path path = Paths.get(directory + fullFileName); // get the path to the files with the specified name
|
||||
|
||||
for(int i = 1; Files.exists(path); i++){ // run through all the files with the specified name
|
||||
fileName = getFileNameWithoutExtension(fullFileName) + "("+i+")"; // get a name of each file without extension and add an index to it
|
||||
path = Paths.get(directory+fileName+fileExtension); // create a new path for this file with the correct name and extension
|
||||
for (int i = 1; Files.exists(path); i++) { // run through all the files with the specified name
|
||||
// get a name of each file without extension and add an index to it
|
||||
fileName = getFileNameWithoutExtension(fullFileName) + "(" + i + ")";
|
||||
|
||||
// create a new path for this file with the correct name and extension
|
||||
path = Paths.get(directory + fileName + fileExtension);
|
||||
}
|
||||
|
||||
path = Paths.get(directory+fileName+fileExtension);
|
||||
path = Paths.get(directory + fileName + fileExtension);
|
||||
return path;
|
||||
}
|
||||
|
||||
// get maximum file size
|
||||
public long getMaxFileSize(){
|
||||
public long getMaxFileSize() {
|
||||
long size = Long.parseLong(filesizeMax);
|
||||
return size > 0 ? size : 5 * 1024 * 1024;
|
||||
return size > 0 ? size : MAX_FILE_SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
@ -35,6 +35,7 @@ public interface FileUtility {
|
||||
List<String> getViewedExts(); // get file extensions that can be viewed
|
||||
List<String> getEditedExts(); // get file extensions that can be edited
|
||||
List<String> getConvertExts(); // get file extensions that can be converted
|
||||
Path generateFilepath(String directory, String fullFileName); // generate the file path from file directory and name
|
||||
Path generateFilepath(String directory, String fullFileName); /* generate the file path
|
||||
from file directory and name */
|
||||
long getMaxFileSize(); // get maximum file size
|
||||
}
|
||||
|
||||
@ -20,6 +20,7 @@ package com.onlyoffice.integration.documentserver.util.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.onlyoffice.integration.documentserver.managers.jwt.JwtManager;
|
||||
import com.onlyoffice.integration.documentserver.models.enums.ConvertErrorType;
|
||||
import com.onlyoffice.integration.documentserver.util.file.FileUtility;
|
||||
import com.onlyoffice.integration.dto.Convert;
|
||||
import lombok.SneakyThrows;
|
||||
@ -27,20 +28,28 @@ import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.*;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
//TODO: Refactoring
|
||||
import static com.onlyoffice.integration.documentserver.util.Constants.CONVERTATION_ERROR_MESSAGE_TEMPLATE;
|
||||
import static com.onlyoffice.integration.documentserver.util.Constants.CONVERT_TIMEOUT_MS;
|
||||
import static com.onlyoffice.integration.documentserver.util.Constants.FULL_LOADING_IN_PERCENT;
|
||||
import static com.onlyoffice.integration.documentserver.util.Constants.MAX_KEY_LENGTH;
|
||||
|
||||
// todo: Refactoring
|
||||
@Component
|
||||
public class DefaultServiceConverter implements ServiceConverter
|
||||
{
|
||||
public class DefaultServiceConverter implements ServiceConverter {
|
||||
@Value("${files.docservice.header}")
|
||||
private String documentJwtHeader;
|
||||
@Value("${files.docservice.url.site}")
|
||||
@ -49,7 +58,7 @@ public class DefaultServiceConverter implements ServiceConverter
|
||||
private String docServiceUrlConverter;
|
||||
@Value("${files.docservice.timeout}")
|
||||
private String docserviceTimeout;
|
||||
private int convertTimeout = 120000;
|
||||
private int convertTimeout;
|
||||
|
||||
@Autowired
|
||||
private JwtManager jwtManager;
|
||||
@ -61,23 +70,24 @@ public class DefaultServiceConverter implements ServiceConverter
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@PostConstruct
|
||||
public void init(){
|
||||
public void init() {
|
||||
int timeout = Integer.parseInt(docserviceTimeout); // parse the dcoument service timeout value
|
||||
if (timeout > 0) convertTimeout = timeout;
|
||||
convertTimeout = timeout > 0 ? timeout : CONVERT_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private String postToServer(Convert body, String headerToken){ // send the POST request to the server
|
||||
String bodyString = objectMapper.writeValueAsString(body); // write the body request to the object mapper in the string format
|
||||
private String postToServer(final Convert body, final String headerToken) { // send the POST request to the server
|
||||
String bodyString = objectMapper
|
||||
.writeValueAsString(body); // write the body request to the object mapper in the string format
|
||||
URL url = null;
|
||||
java.net.HttpURLConnection connection = null;
|
||||
InputStream response = null;
|
||||
String jsonString = null;
|
||||
|
||||
byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8); // convert body string into bytes
|
||||
try{
|
||||
try {
|
||||
// set the request parameters
|
||||
url = new URL(docServiceUrl+docServiceUrlConverter);
|
||||
url = new URL(docServiceUrl + docServiceUrlConverter);
|
||||
connection = (java.net.HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setDoOutput(true);
|
||||
@ -87,17 +97,16 @@ public class DefaultServiceConverter implements ServiceConverter
|
||||
connection.setConnectTimeout(convertTimeout);
|
||||
|
||||
// check if the token is enabled
|
||||
if (jwtManager.tokenEnabled())
|
||||
{
|
||||
if (jwtManager.tokenEnabled()) {
|
||||
// set the JWT header to the request
|
||||
connection.setRequestProperty(documentJwtHeader.isBlank() ?
|
||||
"Authorization" : documentJwtHeader, "Bearer " + headerToken);
|
||||
connection.setRequestProperty(documentJwtHeader.isBlank()
|
||||
? "Authorization" : documentJwtHeader, "Bearer " + headerToken);
|
||||
}
|
||||
|
||||
connection.connect();
|
||||
|
||||
int statusCode = connection.getResponseCode();
|
||||
if (statusCode != 200) { // checking status code
|
||||
if (statusCode != HttpStatus.OK.value()) { // checking status code
|
||||
connection.disconnect();
|
||||
throw new RuntimeException("Convertation service returned status: " + statusCode);
|
||||
}
|
||||
@ -116,37 +125,37 @@ public class DefaultServiceConverter implements ServiceConverter
|
||||
}
|
||||
|
||||
// get the URL to the converted file
|
||||
public String getConvertedUri(String documentUri, String fromExtension,
|
||||
String toExtension, String documentRevisionId,
|
||||
String filePass, Boolean isAsync, String lang)
|
||||
{
|
||||
public String getConvertedUri(final String documentUri, final String fromExtension,
|
||||
final String toExtension, final String documentRevisionId,
|
||||
final String filePass, final Boolean isAsync, final String lang) {
|
||||
// check if the fromExtension parameter is defined; if not, get it from the document url
|
||||
fromExtension = fromExtension == null || fromExtension.isEmpty() ?
|
||||
fileUtility.getFileExtension(documentUri) : fromExtension;
|
||||
String fromExt = fromExtension == null || fromExtension.isEmpty()
|
||||
? fileUtility.getFileExtension(documentUri) : fromExtension;
|
||||
|
||||
// check if the file name parameter is defined; if not, get random uuid for this file
|
||||
String title = fileUtility.getFileName(documentUri);
|
||||
title = title == null || title.isEmpty() ? UUID.randomUUID().toString() : title;
|
||||
|
||||
documentRevisionId = documentRevisionId == null || documentRevisionId.isEmpty() ? documentUri : documentRevisionId;
|
||||
String documentRevId = documentRevisionId == null || documentRevisionId.isEmpty()
|
||||
? documentUri : documentRevisionId;
|
||||
|
||||
documentRevisionId = generateRevisionId(documentRevisionId); // create document token
|
||||
documentRevId = generateRevisionId(documentRevId); // create document token
|
||||
|
||||
// write all the necessary parameters to the body object
|
||||
Convert body = new Convert();
|
||||
body.setLang(lang);
|
||||
body.setUrl(documentUri);
|
||||
body.setOutputtype(toExtension.replace(".", ""));
|
||||
body.setFiletype(fromExtension.replace(".", ""));
|
||||
body.setFiletype(fromExt.replace(".", ""));
|
||||
body.setTitle(title);
|
||||
body.setKey(documentRevisionId);
|
||||
body.setKey(documentRevId);
|
||||
body.setFilePass(filePass);
|
||||
if (isAsync)
|
||||
if (isAsync) {
|
||||
body.setAsync(true);
|
||||
}
|
||||
|
||||
String headerToken = "";
|
||||
if (jwtManager.tokenEnabled())
|
||||
{
|
||||
if (jwtManager.tokenEnabled()) {
|
||||
HashMap<String, Object> map = new HashMap<String, Object>();
|
||||
map.put("region", lang);
|
||||
map.put("url", body.getUrl());
|
||||
@ -155,8 +164,9 @@ public class DefaultServiceConverter implements ServiceConverter
|
||||
map.put("title", body.getTitle());
|
||||
map.put("key", body.getKey());
|
||||
map.put("password", body.getFilePass());
|
||||
if (isAsync)
|
||||
if (isAsync) {
|
||||
map.put("async", body.getAsync());
|
||||
}
|
||||
|
||||
// add token to the body if it is enabled
|
||||
String token = jwtManager.createToken(map);
|
||||
@ -173,98 +183,64 @@ public class DefaultServiceConverter implements ServiceConverter
|
||||
}
|
||||
|
||||
// generate document key
|
||||
public String generateRevisionId(String expectedKey)
|
||||
{
|
||||
if (expectedKey.length() > 20) // if the expected key length is greater than 20
|
||||
expectedKey = Integer.toString(expectedKey.hashCode()); // the expected key is hashed and a fixed length value is stored in the string format
|
||||
public String generateRevisionId(final String expectedKey) {
|
||||
/* if the expected key length is greater than 20
|
||||
then he expected key is hashed and a fixed length value is stored in the string format */
|
||||
String formatKey = expectedKey.length() > MAX_KEY_LENGTH
|
||||
? Integer.toString(expectedKey.hashCode()) : expectedKey;
|
||||
String key = formatKey.replace("[^0-9-.a-zA-Z_=]", "_");
|
||||
|
||||
String key = expectedKey.replace("[^0-9-.a-zA-Z_=]", "_");
|
||||
|
||||
return key.substring(0, Math.min(key.length(), 20)); // the resulting key length is 20 or less
|
||||
return key.substring(0, Math.min(key.length(), MAX_KEY_LENGTH)); // the resulting key length is 20 or less
|
||||
}
|
||||
|
||||
//TODO: Replace with a registry (callbacks package for reference)
|
||||
private void processConvertServiceResponceError(int errorCode) // create an error message for an error code
|
||||
{
|
||||
String errorMessage = "";
|
||||
String errorMessageTemplate = "Error occurred in the ConvertService: ";
|
||||
|
||||
// add the error message to the error message template depending on the error code
|
||||
switch (errorCode)
|
||||
{
|
||||
case -8:
|
||||
errorMessage = errorMessageTemplate + "Error document VKey";
|
||||
break;
|
||||
case -7:
|
||||
errorMessage = errorMessageTemplate + "Error document request";
|
||||
break;
|
||||
case -6:
|
||||
errorMessage = errorMessageTemplate + "Error database";
|
||||
break;
|
||||
case -5:
|
||||
errorMessage = errorMessageTemplate + "Error unexpected guid";
|
||||
break;
|
||||
case -4:
|
||||
errorMessage = errorMessageTemplate + "Error download error";
|
||||
break;
|
||||
case -3:
|
||||
errorMessage = errorMessageTemplate + "Error convertation error";
|
||||
break;
|
||||
case -2:
|
||||
errorMessage = errorMessageTemplate + "Error convertation timeout";
|
||||
break;
|
||||
case -1:
|
||||
errorMessage = errorMessageTemplate + "Error convertation unknown";
|
||||
break;
|
||||
case 0: // if the error code is equal to 0, the error message is empty
|
||||
break;
|
||||
default:
|
||||
errorMessage = "ErrorCode = " + errorCode; // default value for the error message
|
||||
break;
|
||||
}
|
||||
// todo: Replace with a registry (callbacks package for reference)
|
||||
// create an error message for an error code
|
||||
private void processConvertServiceResponceError(final int errorCode) {
|
||||
String errorMessage = CONVERTATION_ERROR_MESSAGE_TEMPLATE + ConvertErrorType.labelOfCode(errorCode);
|
||||
|
||||
throw new RuntimeException(errorMessage);
|
||||
}
|
||||
|
||||
// get the response URL
|
||||
@SneakyThrows
|
||||
private String getResponseUri(String jsonString) // get the response URL
|
||||
{
|
||||
private String getResponseUri(final String jsonString) {
|
||||
JSONObject jsonObj = convertStringToJSON(jsonString);
|
||||
|
||||
Object error = jsonObj.get("error");
|
||||
if (error != null) // if an error occurs
|
||||
processConvertServiceResponceError(Math.toIntExact((long)error)); // then get an error message
|
||||
if (error != null) { // if an error occurs
|
||||
processConvertServiceResponceError(Math.toIntExact((long) error)); // then get an error message
|
||||
}
|
||||
|
||||
// check if the conversion is completed and save the result to a variable
|
||||
Boolean isEndConvert = (Boolean) jsonObj.get("endConvert");
|
||||
|
||||
Long resultPercent = 0l;
|
||||
Long resultPercent = 0L;
|
||||
String responseUri = null;
|
||||
|
||||
if (isEndConvert) // if the conversion is completed
|
||||
{
|
||||
resultPercent = 100l;
|
||||
if (isEndConvert) { // if the conversion is completed
|
||||
resultPercent = FULL_LOADING_IN_PERCENT;
|
||||
responseUri = (String) jsonObj.get("fileUrl"); // get the file URL
|
||||
}
|
||||
else // if the conversion isn't completed
|
||||
{
|
||||
} else { // if the conversion isn't completed
|
||||
resultPercent = (Long) jsonObj.get("percent");
|
||||
resultPercent = resultPercent >= 100l ? 99l : resultPercent; // get the percentage value of the conversion process
|
||||
|
||||
// get the percentage value of the conversion process
|
||||
resultPercent = resultPercent >= FULL_LOADING_IN_PERCENT ? FULL_LOADING_IN_PERCENT - 1 : resultPercent;
|
||||
}
|
||||
|
||||
return resultPercent >= 100l ? responseUri : "";
|
||||
return resultPercent >= FULL_LOADING_IN_PERCENT ? responseUri : "";
|
||||
}
|
||||
|
||||
// convert stream to string
|
||||
@SneakyThrows
|
||||
public String convertStreamToString(InputStream stream) // convert stream to string
|
||||
{
|
||||
public String convertStreamToString(final InputStream stream) {
|
||||
InputStreamReader inputStreamReader = new InputStreamReader(stream); // create an object to get incoming stream
|
||||
StringBuilder stringBuilder = new StringBuilder(); // create a string builder object
|
||||
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // create an object to read incoming streams
|
||||
|
||||
// create an object to read incoming streams
|
||||
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
|
||||
String line = bufferedReader.readLine(); // get incoming streams by lines
|
||||
|
||||
while (line != null)
|
||||
{
|
||||
while (line != null) {
|
||||
stringBuilder.append(line); // concatenate strings using the string builder
|
||||
line = bufferedReader.readLine();
|
||||
}
|
||||
@ -274,12 +250,12 @@ public class DefaultServiceConverter implements ServiceConverter
|
||||
return result;
|
||||
}
|
||||
|
||||
// convert string to json
|
||||
@SneakyThrows
|
||||
public JSONObject convertStringToJSON(String jsonString) // convert string to json
|
||||
{
|
||||
public JSONObject convertStringToJSON(final String jsonString) {
|
||||
Object obj = parser.parse(jsonString); // parse json string
|
||||
JSONObject jsonObj = (JSONObject) obj; // and turn it into a json object
|
||||
|
||||
return jsonObj;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -19,9 +19,6 @@
|
||||
package com.onlyoffice.integration.documentserver.util.service;
|
||||
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.ParseException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
|
||||
|
||||
@ -20,7 +20,9 @@ package com.onlyoffice.integration.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.onlyoffice.integration.documentserver.models.filemodel.User;
|
||||
import lombok.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@ -37,5 +37,5 @@ import java.io.Serializable;
|
||||
public abstract class AbstractEntity implements Serializable {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
int id;
|
||||
private int id;
|
||||
}
|
||||
|
||||
@ -21,7 +21,10 @@ package com.onlyoffice.integration.entities;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.persistence.*;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.persistence.Table;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
|
||||
@ -21,7 +21,9 @@ package com.onlyoffice.integration.entities;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.persistence.*;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.ManyToMany;
|
||||
import javax.persistence.Table;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@ -39,7 +41,7 @@ public class Permission extends AbstractEntity {
|
||||
private Boolean modifyContentControl = true;
|
||||
private Boolean review = true;
|
||||
private Boolean chat = true;
|
||||
private Boolean templates=true;
|
||||
private Boolean templates = true;
|
||||
@ManyToMany
|
||||
private List<Group> reviewGroups;
|
||||
@ManyToMany
|
||||
|
||||
@ -21,7 +21,12 @@ package com.onlyoffice.integration.entities;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.persistence.*;
|
||||
import javax.persistence.CollectionTable;
|
||||
import javax.persistence.ElementCollection;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.OneToOne;
|
||||
import javax.persistence.Table;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
|
||||
@ -28,16 +28,16 @@ import java.util.Objects;
|
||||
|
||||
public abstract class AbstractMapper<E extends AbstractEntity, M extends AbstractModel> implements Mapper<E, M> {
|
||||
@Autowired
|
||||
ModelMapper mapper;
|
||||
private ModelMapper mapper;
|
||||
|
||||
private Class<M> modelClass;
|
||||
|
||||
AbstractMapper(Class<M> modelClass) {
|
||||
this.modelClass = modelClass;
|
||||
AbstractMapper(final Class<M> modelClassParam) {
|
||||
this.modelClass = modelClassParam;
|
||||
}
|
||||
|
||||
@Override
|
||||
public M toModel(E entity) { // convert the entity to the model
|
||||
public M toModel(final E entity) { // convert the entity to the model
|
||||
return Objects.isNull(entity) // check if an entity is not empty
|
||||
? null
|
||||
: mapper.map(entity, modelClass); // and add it to the model mapper
|
||||
@ -53,6 +53,6 @@ public abstract class AbstractMapper<E extends AbstractEntity, M extends Abstrac
|
||||
}
|
||||
|
||||
|
||||
void handleSpecificFields(E source, M destination) {
|
||||
void handleSpecificFields(final E source, final M destination) {
|
||||
}
|
||||
}
|
||||
|
||||
@ -30,7 +30,8 @@ import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
@Primary
|
||||
public class PermissionsMapper extends AbstractMapper<Permission, com.onlyoffice.integration.documentserver.models.filemodel.Permission> {
|
||||
public class PermissionsMapper extends AbstractMapper<Permission,
|
||||
com.onlyoffice.integration.documentserver.models.filemodel.Permission> {
|
||||
@Autowired
|
||||
private ModelMapper mapper;
|
||||
|
||||
@ -40,20 +41,29 @@ public class PermissionsMapper extends AbstractMapper<Permission, com.onlyoffice
|
||||
|
||||
@PostConstruct
|
||||
public void configure() { // configure the permission mapper
|
||||
mapper.createTypeMap(Permission.class, com.onlyoffice.integration.documentserver.models.filemodel.Permission.class) // create the type map
|
||||
mapper.createTypeMap(Permission.class, com.onlyoffice.integration.documentserver.models.filemodel
|
||||
.Permission.class) // create the type map
|
||||
.setPostConverter(modelConverter()); // and apply the post converter to it
|
||||
}
|
||||
|
||||
@Override
|
||||
void handleSpecificFields(Permission source, com.onlyoffice.integration.documentserver.models.filemodel.Permission destination) { // handle specific permission fields
|
||||
destination.setReviewGroups(source.getReviewGroups().stream().map(g -> g.getName()).collect(Collectors.toList())); // set the reviewGroups parameter
|
||||
destination.setCommentGroups( // set the commentGroups parameter
|
||||
void handleSpecificFields(final Permission source,
|
||||
final com.onlyoffice.integration.documentserver.models.filemodel
|
||||
.Permission destination) { // handle specific permission fields
|
||||
destination.setReviewGroups(source.getReviewGroups().stream()
|
||||
.map(g -> g.getName())
|
||||
.collect(Collectors.toList())); // set the reviewGroups parameter
|
||||
|
||||
// set the commentGroups parameter
|
||||
destination.setCommentGroups(
|
||||
new CommentGroup(
|
||||
source.getCommentsViewGroups().stream().map(g -> g.getName()).collect(Collectors.toList()),
|
||||
source.getCommentsEditGroups().stream().map(g -> g.getName()).collect(Collectors.toList()),
|
||||
source.getCommentsRemoveGroups().stream().map(g -> g.getName()).collect(Collectors.toList())
|
||||
)
|
||||
);
|
||||
destination.setUserInfoGroups(source.getUserInfoGroups().stream().map(g -> g.getName()).collect(Collectors.toList()));
|
||||
destination.setUserInfoGroups(source.getUserInfoGroups().stream()
|
||||
.map(g -> g.getName())
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
}
|
||||
|
||||
@ -32,18 +32,22 @@ public class UsersMapper extends AbstractMapper<User, com.onlyoffice.integration
|
||||
@Autowired
|
||||
private ModelMapper mapper;
|
||||
|
||||
public UsersMapper(){
|
||||
public UsersMapper() {
|
||||
super(com.onlyoffice.integration.documentserver.models.filemodel.User.class);
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void configure() { // configure the users mapper
|
||||
mapper.createTypeMap(User.class, com.onlyoffice.integration.documentserver.models.filemodel.User.class) // create the type map
|
||||
mapper.createTypeMap(User.class, com.onlyoffice.integration.documentserver.models.filemodel
|
||||
.User.class) // create the type map
|
||||
.setPostConverter(modelConverter()); // and apply the post converter to it
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleSpecificFields(User source, com.onlyoffice.integration.documentserver.models.filemodel.User destination) { // handle specific users fields
|
||||
destination.setGroup(source.getGroup() != null ? source.getGroup().getName() : null); // set the Group parameter
|
||||
public void handleSpecificFields(final User source,
|
||||
final com.onlyoffice.integration.documentserver.models.filemodel
|
||||
.User destination) { // handle specific users fields
|
||||
destination.setGroup(source.getGroup() != null
|
||||
? source.getGroup().getName() : null); // set the Group parameter
|
||||
}
|
||||
}
|
||||
|
||||
@ -33,10 +33,15 @@ public class GroupServices {
|
||||
private GroupRepository groupRepository;
|
||||
|
||||
// create a new group with the specified name
|
||||
public Group createGroup(String name){
|
||||
if(name == null) return null; // check if a name is specified
|
||||
Optional<Group> group = groupRepository.findGroupByName(name); // check if group with such a name already exists
|
||||
if(group.isPresent()) return group.get(); // if it exists, return it
|
||||
public Group createGroup(final String name) {
|
||||
if (name == null) {
|
||||
return null; // check if a name is specified
|
||||
}
|
||||
Optional<Group> group = groupRepository
|
||||
.findGroupByName(name); // check if group with such a name already exists
|
||||
if (group.isPresent()) {
|
||||
return group.get(); // if it exists, return it
|
||||
}
|
||||
Group newGroup = new Group();
|
||||
newGroup.setName(name); // otherwise, create a new group with the specified name
|
||||
|
||||
@ -46,9 +51,12 @@ public class GroupServices {
|
||||
}
|
||||
|
||||
// create a list of groups from the reviewGroups permission parameter
|
||||
public List<Group> createGroups(List<String> reviewGroups){
|
||||
if(reviewGroups == null) return null; // check if the reviewGroups permission exists
|
||||
return reviewGroups.stream() // convert this parameter to a list of groups whose changes the user can accept/reject
|
||||
public List<Group> createGroups(final List<String> reviewGroups) {
|
||||
if (reviewGroups == null) {
|
||||
return null; // check if the reviewGroups permission exists
|
||||
}
|
||||
// convert this parameter to a list of groups whose changes the user can accept/reject
|
||||
return reviewGroups.stream()
|
||||
.map(group -> createGroup(group))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@ -33,18 +33,19 @@ public class PermissionServices {
|
||||
private PermissionRepository permissionRepository;
|
||||
|
||||
// create permissions with the specified parameters
|
||||
public Permission createPermission(List<Group> reviewGroups,
|
||||
List<Group> commentViewGroups,
|
||||
List<Group> commentEditGroups,
|
||||
List<Group> commentRemoveGroups,
|
||||
List<Group> userInfoGroups,
|
||||
Boolean chat){
|
||||
public Permission createPermission(final List<Group> reviewGroups,
|
||||
final List<Group> commentViewGroups,
|
||||
final List<Group> commentEditGroups,
|
||||
final List<Group> commentRemoveGroups,
|
||||
final List<Group> userInfoGroups,
|
||||
final Boolean chat) {
|
||||
|
||||
Permission permission = new Permission();
|
||||
permission.setReviewGroups(reviewGroups); // define the groups whose changes the user can accept/reject
|
||||
permission.setCommentsViewGroups(commentViewGroups); // defines the groups whose comments the user can view
|
||||
permission.setCommentsEditGroups(commentEditGroups); // defines the groups whose comments the user can edit
|
||||
permission.setCommentsRemoveGroups(commentRemoveGroups); // defines the groups whose comments the user can remove
|
||||
permission.setCommentsRemoveGroups(commentRemoveGroups); /* defines the groups
|
||||
whose comments the user can remove */
|
||||
permission.setUserInfoGroups(userInfoGroups);
|
||||
permission.setChat(chat);
|
||||
|
||||
@ -54,7 +55,7 @@ public class PermissionServices {
|
||||
}
|
||||
|
||||
// update permissions
|
||||
public Permission updatePermission(Permission newPermission){
|
||||
public Permission updatePermission(final Permission newPermission) {
|
||||
permissionRepository.save(newPermission); // save new permissions
|
||||
|
||||
return newPermission;
|
||||
|
||||
@ -27,7 +27,6 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class UserServices {
|
||||
@ -41,24 +40,24 @@ public class UserServices {
|
||||
private PermissionServices permissionService;
|
||||
|
||||
// get a list of all users
|
||||
public List<User> findAll(){
|
||||
public List<User> findAll() {
|
||||
return userRepository.findAll();
|
||||
}
|
||||
|
||||
// get a user by their ID
|
||||
public Optional<User> findUserById(Integer id){
|
||||
public Optional<User> findUserById(final Integer id) {
|
||||
return userRepository.findById(id);
|
||||
}
|
||||
|
||||
// create a user with the specified parameters
|
||||
public User createUser(String name, String email,
|
||||
List<String> description, String group,
|
||||
List<String> reviewGroups,
|
||||
List<String> viewGroups,
|
||||
List<String> editGroups,
|
||||
List<String> removeGroups,
|
||||
List<String> userInfoGroups, Boolean favoriteDoc,
|
||||
Boolean chat){
|
||||
public User createUser(final String name, final String email,
|
||||
final List<String> description, final String group,
|
||||
final List<String> reviewGroups,
|
||||
final List<String> viewGroups,
|
||||
final List<String> editGroups,
|
||||
final List<String> removeGroups,
|
||||
final List<String> userInfoGroups, final Boolean favoriteDoc,
|
||||
final Boolean chat) {
|
||||
User newUser = new User();
|
||||
newUser.setName(name); // set the user name
|
||||
newUser.setEmail(email); // set the user email
|
||||
@ -66,14 +65,23 @@ public class UserServices {
|
||||
newUser.setDescriptions(description); // set the user description
|
||||
newUser.setFavorite(favoriteDoc); // specify if the user has the favorite documents or not
|
||||
|
||||
List<Group> groupsReview = groupServices.createGroups(reviewGroups); // define the groups whose changes the user can accept/reject
|
||||
List<Group> commentGroupsView = groupServices.createGroups(viewGroups); // defines the groups whose comments the user can view
|
||||
List<Group> commentGroupsEdit = groupServices.createGroups(editGroups); // defines the groups whose comments the user can edit
|
||||
List<Group> commentGroupsRemove = groupServices.createGroups(removeGroups); // defines the groups whose comments the user can remove
|
||||
List<Group> groupsReview = groupServices
|
||||
.createGroups(reviewGroups); // define the groups whose changes the user can accept/reject
|
||||
List<Group> commentGroupsView = groupServices
|
||||
.createGroups(viewGroups); // defines the groups whose comments the user can view
|
||||
List<Group> commentGroupsEdit = groupServices
|
||||
.createGroups(editGroups); // defines the groups whose comments the user can edit
|
||||
List<Group> commentGroupsRemove = groupServices
|
||||
.createGroups(removeGroups); // defines the groups whose comments the user can remove
|
||||
List<Group> usInfoGroups = groupServices.createGroups(userInfoGroups);
|
||||
|
||||
Permission permission = permissionService
|
||||
.createPermission(groupsReview, commentGroupsView, commentGroupsEdit, commentGroupsRemove, usInfoGroups, chat); // specify permissions for the current user
|
||||
.createPermission(groupsReview,
|
||||
commentGroupsView,
|
||||
commentGroupsEdit,
|
||||
commentGroupsRemove,
|
||||
usInfoGroups,
|
||||
chat); // specify permissions for the current user
|
||||
newUser.setPermissions(permission);
|
||||
|
||||
userRepository.save(newUser); // save a new user
|
||||
|
||||
@ -30,9 +30,10 @@ import org.springframework.stereotype.Service;
|
||||
@Primary
|
||||
public class DefaultCustomizationConfigurer implements CustomizationConfigurer<DefaultCustomizationWrapper> {
|
||||
@Override
|
||||
public void configure(Customization customization, DefaultCustomizationWrapper wrapper) { // define the customization configurer
|
||||
// define the customization configurer
|
||||
public void configure(final Customization customization, final DefaultCustomizationWrapper wrapper) {
|
||||
Action action = wrapper.getAction(); // get the action parameter from the customization wrapper
|
||||
User user = wrapper.getUser();
|
||||
customization.setSubmitForm(action.equals(Action.fillForms) && user.getId() == 1 && false); // set the submitForm parameter to the customization config
|
||||
customization.setSubmitForm(false); // set the submitForm parameter to the customization config
|
||||
}
|
||||
}
|
||||
|
||||
@ -48,19 +48,26 @@ public class DefaultDocumentConfigurer implements DocumentConfigurer<DefaultDocu
|
||||
@Autowired
|
||||
private ServiceConverter serviceConverter;
|
||||
|
||||
public void configure(Document document, DefaultDocumentWrapper wrapper){ // define the document configurer
|
||||
public void configure(final Document document,
|
||||
final DefaultDocumentWrapper wrapper) { // define the document configurer
|
||||
String fileName = wrapper.getFileName(); // get the fileName parameter from the document wrapper
|
||||
Permission permission = wrapper.getPermission(); // get the permission parameter from the document wrapper
|
||||
|
||||
document.setTitle(fileName); // set the title to the document config
|
||||
document.setUrl(documentManager.getDownloadUrl(fileName, true)); // set the URL to download a file to the document config
|
||||
document.setUrlUser(documentManager.getFileUri(fileName, false)); // set the file URL to the document config
|
||||
document.setDirectUrl(wrapper.getIsEnableDirectUrl() ? documentManager.getDownloadUrl(fileName, false) : "");
|
||||
document.setFileType(fileUtility.getFileExtension(fileName).replace(".","")); // set the file type to the document config
|
||||
|
||||
// set the URL to download a file to the document config
|
||||
document.setUrl(documentManager.getDownloadUrl(fileName, true));
|
||||
document.setUrlUser(documentManager
|
||||
.getFileUri(fileName, false)); // set the file URL to the document config
|
||||
document.setDirectUrl(wrapper.getIsEnableDirectUrl() ? documentManager
|
||||
.getDownloadUrl(fileName, false) : "");
|
||||
document.setFileType(fileUtility.getFileExtension(fileName)
|
||||
.replace(".", "")); // set the file type to the document config
|
||||
document.getInfo().setFavorite(wrapper.getFavorite()); // set the favorite parameter to the document config
|
||||
|
||||
String key = serviceConverter. // get the document key
|
||||
generateRevisionId(storagePathBuilder.getStorageLocation()
|
||||
// get the document key
|
||||
String key = serviceConverter
|
||||
.generateRevisionId(storagePathBuilder.getStorageLocation()
|
||||
+ "/" + fileName + "/"
|
||||
+ new File(storagePathBuilder.getFileLocation(fileName)).lastModified());
|
||||
|
||||
|
||||
@ -68,26 +68,35 @@ public class DefaultEditorConfigConfigurer implements EditorConfigConfigurer<Def
|
||||
private FileUtility fileUtility;
|
||||
|
||||
@SneakyThrows
|
||||
public void configure(EditorConfig config, DefaultFileWrapper wrapper){ // define the editorConfig configurer
|
||||
public void configure(final EditorConfig config,
|
||||
final DefaultFileWrapper wrapper) { // define the editorConfig configurer
|
||||
if (wrapper.getActionData() != null) { // check if the actionData is not empty in the editorConfig wrapper
|
||||
config.setActionLink(objectMapper.readValue(wrapper.getActionData(), (JavaType) new TypeToken<HashMap<String, Object>>() { }.getType())); // set actionLink to the editorConfig
|
||||
|
||||
// set actionLink to the editorConfig
|
||||
config.setActionLink(objectMapper.readValue(wrapper.getActionData(),
|
||||
(JavaType) new TypeToken<HashMap<String, Object>>() { }.getType()));
|
||||
}
|
||||
String fileName = wrapper.getFileName(); // set the fileName parameter from the editorConfig wrapper
|
||||
String fileExt = fileUtility.getFileExtension(fileName);
|
||||
boolean userIsAnon = wrapper.getUser().getName().equals("Anonymous"); // check if the user from the editorConfig wrapper is anonymous or not
|
||||
boolean userIsAnon = wrapper.getUser()
|
||||
.getName().equals("Anonymous"); // check if the user from the editorConfig wrapper is anonymous or not
|
||||
|
||||
config.setTemplates(userIsAnon ? null : templateManager.createTemplates(fileName)); // set a template to the editorConfig if the user is not anonymous
|
||||
// set a template to the editorConfig if the user is not anonymous
|
||||
config.setTemplates(userIsAnon ? null : templateManager.createTemplates(fileName));
|
||||
config.setCallbackUrl(documentManager.getCallback(fileName)); // set the callback URL to the editorConfig
|
||||
config.setCreateUrl(userIsAnon ? null : documentManager.getCreateUrl(fileName, false)); // set the document URL where it will be created to the editorConfig if the user is not anonymous
|
||||
|
||||
// set the document URL where it will be created to the editorConfig if the user is not anonymous
|
||||
config.setCreateUrl(userIsAnon ? null : documentManager.getCreateUrl(fileName, false));
|
||||
config.setLang(wrapper.getLang()); // set the language to the editorConfig
|
||||
Boolean canEdit = wrapper.getCanEdit(); // check if the file of the specified type can be edited or not
|
||||
Action action = wrapper.getAction(); // get the action parameter from the editorConfig wrapper
|
||||
config.setCoEditing(action.equals(Action.view) && userIsAnon ? new HashMap<String, Object>() {{
|
||||
config.setCoEditing(action.equals(Action.view) && userIsAnon ? new HashMap<String, Object>() {{
|
||||
put("mode", "strict");
|
||||
put("change", false);
|
||||
}} : null);
|
||||
|
||||
defaultCustomizationConfigurer.configure(config.getCustomization(), DefaultCustomizationWrapper.builder() // define the customization configurer
|
||||
defaultCustomizationConfigurer.configure(config.getCustomization(),
|
||||
DefaultCustomizationWrapper.builder() // define the customization configurer
|
||||
.action(action)
|
||||
.user(userIsAnon ? null : wrapper.getUser())
|
||||
.build());
|
||||
|
||||
@ -35,13 +35,27 @@ public class DefaultEmbeddedConfigurer implements EmbeddedConfigurer<DefaultEmbe
|
||||
@Autowired
|
||||
private DocumentManager documentManager;
|
||||
|
||||
public void configure(Embedded embedded, DefaultEmbeddedWrapper wrapper){ // define the embedded configurer
|
||||
if(wrapper.getType().equals(Type.embedded)) { // check if the type from the embedded wrapper is embedded
|
||||
String url = documentManager.getDownloadUrl(wrapper.getFileName(), false); // get file URL of the specified file
|
||||
embedded.setEmbedUrl(url); // set the embedURL parameter to the embedded config (the absolute URL to the document serving as a source file for the document embedded into the web page)
|
||||
embedded.setSaveUrl(url); // set the saveURL parameter to the embedded config (the absolute URL that will allow the document to be saved onto the user personal computer)
|
||||
embedded.setShareUrl(url); // set the shareURL parameter to the embedded config (the absolute URL that will allow other users to share this document)
|
||||
embedded.setToolbarDocked(ToolbarDocked.top); // set the top toolbarDocked parameter to the embedded config (the place for the embedded viewer toolbar, can be either top or bottom)
|
||||
};
|
||||
public void configure(final Embedded embedded,
|
||||
final DefaultEmbeddedWrapper wrapper) { // define the embedded configurer
|
||||
if (wrapper.getType().equals(Type.embedded)) { // check if the type from the embedded wrapper is embedded
|
||||
String url = documentManager.getDownloadUrl(wrapper
|
||||
.getFileName(), false); // get file URL of the specified file
|
||||
|
||||
/* set the embedURL parameter to the embedded config (the absolute URL to the document serving
|
||||
as a source file for the document embedded into the web page) */
|
||||
embedded.setEmbedUrl(url);
|
||||
|
||||
/* set the saveURL parameter to the embedded config (the absolute URL that will allow
|
||||
the document to be saved onto the user personal computer) */
|
||||
embedded.setSaveUrl(url);
|
||||
|
||||
/* set the shareURL parameter to the embedded config (the absolute URL
|
||||
that will allow other users to share this document) */
|
||||
embedded.setShareUrl(url);
|
||||
|
||||
/* set the top toolbarDocked parameter to the embedded config (the place for the
|
||||
embedded viewer toolbar, can be either top or bottom) */
|
||||
embedded.setToolbarDocked(ToolbarDocked.top);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -20,13 +20,14 @@ package com.onlyoffice.integration.services.configurers.implementations;
|
||||
|
||||
import com.onlyoffice.integration.documentserver.managers.jwt.JwtManager;
|
||||
import com.onlyoffice.integration.documentserver.models.enums.Action;
|
||||
import com.onlyoffice.integration.mappers.Mapper;
|
||||
import com.onlyoffice.integration.documentserver.models.enums.DocumentType;
|
||||
import com.onlyoffice.integration.documentserver.models.filemodel.*;
|
||||
import com.onlyoffice.integration.documentserver.models.filemodel.FileModel;
|
||||
import com.onlyoffice.integration.documentserver.models.filemodel.Permission;
|
||||
import com.onlyoffice.integration.documentserver.util.file.FileUtility;
|
||||
import com.onlyoffice.integration.mappers.Mapper;
|
||||
import com.onlyoffice.integration.services.configurers.FileConfigurer;
|
||||
import com.onlyoffice.integration.services.configurers.wrappers.DefaultDocumentWrapper;
|
||||
import com.onlyoffice.integration.services.configurers.wrappers.DefaultFileWrapper;
|
||||
import com.onlyoffice.integration.documentserver.util.file.FileUtility;
|
||||
import org.springframework.beans.factory.ObjectFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
@ -56,20 +57,23 @@ public class DefaultFileConfigurer implements FileConfigurer<DefaultFileWrapper>
|
||||
@Autowired
|
||||
private DefaultEditorConfigConfigurer defaultEditorConfigConfigurer;
|
||||
|
||||
public void configure(FileModel fileModel, DefaultFileWrapper wrapper){ // define the file configurer
|
||||
if (fileModel != null){ // check if the file model is specified
|
||||
public void configure(final FileModel fileModel, final DefaultFileWrapper wrapper) { // define the file configurer
|
||||
if (fileModel != null) { // check if the file model is specified
|
||||
String fileName = wrapper.getFileName(); // get the fileName parameter from the file wrapper
|
||||
Action action = wrapper.getAction(); // get the action parameter from the file wrapper
|
||||
|
||||
DocumentType documentType = fileUtility.getDocumentType(fileName); // get the document type of the specified file
|
||||
DocumentType documentType = fileUtility
|
||||
.getDocumentType(fileName); // get the document type of the specified file
|
||||
fileModel.setDocumentType(documentType); // set the document type to the file model
|
||||
fileModel.setType(wrapper.getType()); // set the platform type to the file model
|
||||
|
||||
Permission userPermissions = mapper.toModel(wrapper.getUser().getPermissions()); // convert the permission entity to the model
|
||||
Permission userPermissions = mapper.toModel(wrapper.getUser()
|
||||
.getPermissions()); // convert the permission entity to the model
|
||||
|
||||
String fileExt = fileUtility.getFileExtension(wrapper.getFileName());
|
||||
Boolean canEdit = fileUtility.getEditedExts().contains(fileExt);
|
||||
if ((!canEdit && action.equals(Action.edit) || action.equals(Action.fillForms)) && fileUtility.getFillExts().contains(fileExt)) {
|
||||
if ((!canEdit && action.equals(Action.edit) || action.equals(Action.fillForms)) && fileUtility
|
||||
.getFillExts().contains(fileExt)) {
|
||||
canEdit = true;
|
||||
wrapper.setAction(Action.fillForms);
|
||||
}
|
||||
@ -83,8 +87,10 @@ public class DefaultFileConfigurer implements FileConfigurer<DefaultFileWrapper>
|
||||
.isEnableDirectUrl(wrapper.getIsEnableDirectUrl())
|
||||
.build();
|
||||
|
||||
defaultDocumentConfigurer.configure(fileModel.getDocument(), documentWrapper); // define the document configurer
|
||||
defaultEditorConfigConfigurer.configure(fileModel.getEditorConfig(), wrapper); // define the editorConfig configurer
|
||||
defaultDocumentConfigurer
|
||||
.configure(fileModel.getDocument(), documentWrapper); // define the document configurer
|
||||
defaultEditorConfigConfigurer
|
||||
.configure(fileModel.getEditorConfig(), wrapper); // define the editorConfig configurer
|
||||
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("type", fileModel.getType());
|
||||
@ -97,13 +103,13 @@ public class DefaultFileConfigurer implements FileConfigurer<DefaultFileWrapper>
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileModel getFileModel(DefaultFileWrapper wrapper) { // get file model
|
||||
public FileModel getFileModel(final DefaultFileWrapper wrapper) { // get file model
|
||||
FileModel fileModel = fileModelObjectFactory.getObject();
|
||||
configure(fileModel, wrapper); // and configure it
|
||||
return fileModel;
|
||||
}
|
||||
|
||||
private Permission updatePermissions(Permission userPermissions, Action action, Boolean canEdit) {
|
||||
private Permission updatePermissions(final Permission userPermissions, final Action action, final Boolean canEdit) {
|
||||
userPermissions.setComment(
|
||||
!action.equals(Action.view)
|
||||
&& !action.equals(Action.fillForms)
|
||||
@ -118,11 +124,11 @@ public class DefaultFileConfigurer implements FileConfigurer<DefaultFileWrapper>
|
||||
&& !action.equals(Action.blockcontent)
|
||||
);
|
||||
|
||||
userPermissions.setReview(canEdit &&
|
||||
(action.equals(Action.review) || action.equals(Action.edit)));
|
||||
userPermissions.setReview(canEdit
|
||||
&& (action.equals(Action.review) || action.equals(Action.edit)));
|
||||
|
||||
userPermissions.setEdit(canEdit &&
|
||||
(action.equals(Action.view)
|
||||
userPermissions.setEdit(canEdit
|
||||
&& (action.equals(Action.view)
|
||||
|| action.equals(Action.edit)
|
||||
|| action.equals(Action.filter)
|
||||
|| action.equals(Action.blockcontent)));
|
||||
|
||||
@ -1,7 +1,11 @@
|
||||
server.version=1.4.0
|
||||
server.version=1.5.0
|
||||
|
||||
server.address=
|
||||
server.port=4000
|
||||
server.port=8443
|
||||
server.ssl.key-store=classpath:springboot.p12
|
||||
server.ssl.key-store-password=111111
|
||||
server.ssl.key-alias=springboot
|
||||
server.ssl.key-password=111111
|
||||
|
||||
filesize-max=5242880
|
||||
|
||||
@ -46,4 +50,4 @@ url.download=/download
|
||||
|
||||
logo.image=
|
||||
logo.imageEmbedded=
|
||||
logo.url=https://www.onlyoffice.com
|
||||
logo.url=https://www.onlyoffice.com
|
||||
|
||||
Binary file not shown.
@ -1,6 +1,5 @@
|
||||
FROM maven:3.6.1-jdk-8-alpine AS MVN_BLDR
|
||||
COPY pom.xml /tmp/
|
||||
COPY src /tmp/src/
|
||||
COPY ./ /tmp/
|
||||
WORKDIR /tmp/
|
||||
RUN mvn package
|
||||
|
||||
|
||||
12
web/documentserver-example/java/checkstyle-suppressions.xml
Normal file
12
web/documentserver-example/java/checkstyle-suppressions.xml
Normal file
@ -0,0 +1,12 @@
|
||||
<?xml version="1.0"?>
|
||||
<!DOCTYPE suppressions PUBLIC
|
||||
"-//Checkstyle//DTD SuppressionFilter Configuration 1.0//EN"
|
||||
"https://checkstyle.org/dtds/suppressions_1_0.dtd">
|
||||
|
||||
<suppressions>
|
||||
<suppress checks="ParameterNumber" files="."/>
|
||||
<suppress checks="DesignForExtension" files="."/>
|
||||
<suppress checks="JavadocPackage" files="."/>
|
||||
<suppress checks="JavadocVariable" files="."/>
|
||||
<suppress checks="MissingJavadocMethod" files="."/>
|
||||
</suppressions>
|
||||
199
web/documentserver-example/java/checkstyle.xml
Normal file
199
web/documentserver-example/java/checkstyle.xml
Normal file
@ -0,0 +1,199 @@
|
||||
<?xml version="1.0"?>
|
||||
<!DOCTYPE module PUBLIC
|
||||
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
|
||||
"https://checkstyle.org/dtds/configuration_1_3.dtd">
|
||||
|
||||
<!--
|
||||
|
||||
Checkstyle configuration that checks the sun coding conventions from:
|
||||
|
||||
- the Java Language Specification at
|
||||
https://docs.oracle.com/javase/specs/jls/se11/html/index.html
|
||||
|
||||
- the Sun Code Conventions at https://www.oracle.com/java/technologies/javase/codeconventions-contents.html
|
||||
|
||||
- the Javadoc guidelines at
|
||||
https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html
|
||||
|
||||
- the JDK Api documentation https://docs.oracle.com/en/java/javase/11/
|
||||
|
||||
- some best practices
|
||||
|
||||
Checkstyle is very configurable. Be sure to read the documentation at
|
||||
https://checkstyle.org (or in your downloaded distribution).
|
||||
|
||||
Most Checks are configurable, be sure to consult the documentation.
|
||||
|
||||
To completely disable a check, just comment it out or delete it from the file.
|
||||
To suppress certain violations please review suppression filters.
|
||||
|
||||
Finally, it is worth reading the documentation.
|
||||
|
||||
-->
|
||||
|
||||
<module name="Checker">
|
||||
<!--
|
||||
If you set the basedir property below, then all reported file
|
||||
names will be relative to the specified directory. See
|
||||
https://checkstyle.org/config.html#Checker
|
||||
|
||||
<property name="basedir" value="${basedir}"/>
|
||||
-->
|
||||
<property name="severity" value="error"/>
|
||||
|
||||
<property name="fileExtensions" value="java, properties, xml"/>
|
||||
|
||||
<!-- Excludes all 'module-info.java' files -->
|
||||
<!-- See https://checkstyle.org/config_filefilters.html -->
|
||||
<module name="BeforeExecutionExclusionFileFilter">
|
||||
<property name="fileNamePattern" value="module\-info\.java$"/>
|
||||
</module>
|
||||
|
||||
<!-- https://checkstyle.org/config_filters.html#SuppressionFilter -->
|
||||
<module name="SuppressionFilter">
|
||||
<property name="file" value="${org.checkstyle.sun.suppressionfilter.config}"
|
||||
default="checkstyle-suppressions.xml" />
|
||||
<property name="optional" value="true"/>
|
||||
</module>
|
||||
|
||||
<!-- Checks that a package-info.java file exists for each package. -->
|
||||
<!-- See https://checkstyle.org/config_javadoc.html#JavadocPackage -->
|
||||
<module name="JavadocPackage"/>
|
||||
|
||||
<!-- Checks whether files end with a new line. -->
|
||||
<!-- See https://checkstyle.org/config_misc.html#NewlineAtEndOfFile -->
|
||||
<module name="NewlineAtEndOfFile"/>
|
||||
|
||||
<!-- Checks that property files contain the same keys. -->
|
||||
<!-- See https://checkstyle.org/config_misc.html#Translation -->
|
||||
<module name="Translation"/>
|
||||
|
||||
<!-- Checks for Size Violations. -->
|
||||
<!-- See https://checkstyle.org/config_sizes.html -->
|
||||
<module name="FileLength"/>
|
||||
<module name="LineLength">
|
||||
<property name="fileExtensions" value="java"/>
|
||||
<property name="max" value="120"/>
|
||||
</module>
|
||||
|
||||
<!-- Checks for whitespace -->
|
||||
<!-- See https://checkstyle.org/config_whitespace.html -->
|
||||
<module name="FileTabCharacter"/>
|
||||
|
||||
<!-- Miscellaneous other checks. -->
|
||||
<!-- See https://checkstyle.org/config_misc.html -->
|
||||
<module name="RegexpSingleline">
|
||||
<property name="format" value="\s+$"/>
|
||||
<property name="minimum" value="0"/>
|
||||
<property name="maximum" value="0"/>
|
||||
<property name="message" value="Line has trailing spaces."/>
|
||||
</module>
|
||||
|
||||
<!-- Checks for Headers -->
|
||||
<!-- See https://checkstyle.org/config_header.html -->
|
||||
<module name="Header">
|
||||
<property name="headerFile" value="onlyoffice.header"/>
|
||||
<property name="fileExtensions" value="java"/>
|
||||
</module>
|
||||
|
||||
<module name="TreeWalker">
|
||||
|
||||
<!-- Checks for Javadoc comments. -->
|
||||
<!-- See https://checkstyle.org/config_javadoc.html -->
|
||||
<module name="InvalidJavadocPosition"/>
|
||||
<module name="JavadocMethod"/>
|
||||
<module name="JavadocType"/>
|
||||
<module name="JavadocVariable"/>
|
||||
<module name="JavadocStyle"/>
|
||||
<module name="MissingJavadocMethod"/>
|
||||
|
||||
<!-- Checks for Naming Conventions. -->
|
||||
<!-- See https://checkstyle.org/config_naming.html -->
|
||||
<module name="ConstantName"/>
|
||||
<module name="LocalFinalVariableName"/>
|
||||
<module name="LocalVariableName"/>
|
||||
<module name="MemberName"/>
|
||||
<module name="MethodName"/>
|
||||
<module name="PackageName"/>
|
||||
<module name="ParameterName"/>
|
||||
<module name="StaticVariableName"/>
|
||||
<module name="TypeName"/>
|
||||
|
||||
<!-- Checks for imports -->
|
||||
<!-- See https://checkstyle.org/config_imports.html -->
|
||||
<module name="AvoidStarImport"/>
|
||||
<module name="IllegalImport"/> <!-- defaults to sun.* packages -->
|
||||
<module name="RedundantImport"/>
|
||||
<module name="UnusedImports">
|
||||
<property name="processJavadoc" value="false"/>
|
||||
</module>
|
||||
|
||||
<!-- Checks for Size Violations. -->
|
||||
<!-- See https://checkstyle.org/config_sizes.html -->
|
||||
<module name="MethodLength"/>
|
||||
<module name="ParameterNumber"/>
|
||||
|
||||
<!-- Checks for whitespace -->
|
||||
<!-- See https://checkstyle.org/config_whitespace.html -->
|
||||
<module name="EmptyForIteratorPad"/>
|
||||
<module name="GenericWhitespace"/>
|
||||
<module name="MethodParamPad"/>
|
||||
<module name="NoWhitespaceAfter"/>
|
||||
<module name="NoWhitespaceBefore"/>
|
||||
<module name="OperatorWrap"/>
|
||||
<module name="ParenPad"/>
|
||||
<module name="TypecastParenPad"/>
|
||||
<module name="WhitespaceAfter"/>
|
||||
<module name="WhitespaceAround"/>
|
||||
|
||||
<!-- Modifier Checks -->
|
||||
<!-- See https://checkstyle.org/config_modifier.html -->
|
||||
<module name="ModifierOrder"/>
|
||||
<module name="RedundantModifier"/>
|
||||
|
||||
<!-- Checks for blocks. You know, those {}'s -->
|
||||
<!-- See https://checkstyle.org/config_blocks.html -->
|
||||
<module name="AvoidNestedBlocks"/>
|
||||
<module name="EmptyBlock"/>
|
||||
<module name="LeftCurly"/>
|
||||
<module name="NeedBraces"/>
|
||||
<module name="RightCurly"/>
|
||||
|
||||
<!-- Checks for common coding problems -->
|
||||
<!-- See https://checkstyle.org/config_coding.html -->
|
||||
<module name="EmptyStatement"/>
|
||||
<module name="EqualsHashCode"/>
|
||||
<module name="HiddenField"/>
|
||||
<module name="IllegalInstantiation"/>
|
||||
<module name="InnerAssignment"/>
|
||||
<module name="MagicNumber"/>
|
||||
<module name="MissingSwitchDefault"/>
|
||||
<module name="MultipleVariableDeclarations"/>
|
||||
<module name="SimplifyBooleanExpression"/>
|
||||
<module name="SimplifyBooleanReturn"/>
|
||||
|
||||
<!-- Checks for class design -->
|
||||
<!-- See https://checkstyle.org/config_design.html -->
|
||||
<module name="DesignForExtension"/>
|
||||
<module name="FinalClass"/>
|
||||
<module name="HideUtilityClassConstructor"/>
|
||||
<module name="InterfaceIsType"/>
|
||||
<module name="VisibilityModifier"/>
|
||||
|
||||
<!-- Miscellaneous other checks. -->
|
||||
<!-- See https://checkstyle.org/config_misc.html -->
|
||||
<module name="ArrayTypeStyle"/>
|
||||
<module name="FinalParameters"/>
|
||||
<module name="TodoComment"/>
|
||||
<module name="UpperEll"/>
|
||||
|
||||
<!-- https://checkstyle.org/config_filters.html#SuppressionXpathFilter -->
|
||||
<module name="SuppressionXpathFilter">
|
||||
<property name="file" value="${org.checkstyle.sun.suppressionxpathfilter.config}"
|
||||
default="checkstyle-xpath-suppressions.xml" />
|
||||
<property name="optional" value="true"/>
|
||||
</module>
|
||||
|
||||
</module>
|
||||
|
||||
</module>
|
||||
17
web/documentserver-example/java/onlyoffice.header
Normal file
17
web/documentserver-example/java/onlyoffice.header
Normal file
@ -0,0 +1,17 @@
|
||||
/**
|
||||
*
|
||||
* (c) Copyright Ascensio System SIA 2023
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
@ -88,14 +88,13 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-checkstyle-plugin</artifactId>
|
||||
<version>2.17</version>
|
||||
<version>3.2.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>validate</id>
|
||||
<phase>validate</phase>
|
||||
<configuration>
|
||||
<configLocation>google_checks.xml</configLocation>
|
||||
<encoding>UTF-8</encoding>
|
||||
<configLocation>checkstyle.xml</configLocation>
|
||||
<failsOnError>true</failsOnError>
|
||||
<failOnViolation>true</failOnViolation>
|
||||
<logViolationsToConsole>true</logViolationsToConsole>
|
||||
|
||||
@ -19,32 +19,34 @@
|
||||
package controllers;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import entities.FileModel;
|
||||
import entities.User;
|
||||
import helpers.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.*;
|
||||
import helpers.ConfigManager;
|
||||
import helpers.CookieManager;
|
||||
import helpers.DocumentManager;
|
||||
import helpers.FileUtility;
|
||||
import helpers.Users;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import entities.FileModel;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
@WebServlet(name = "EditorServlet", urlPatterns = {"/EditorServlet"})
|
||||
public class EditorServlet extends HttpServlet
|
||||
{
|
||||
public class EditorServlet extends HttpServlet {
|
||||
// process request
|
||||
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
DocumentManager.Init(request, response);
|
||||
protected void processRequest(final HttpServletRequest request,
|
||||
final HttpServletResponse response) throws ServletException, IOException {
|
||||
DocumentManager.init(request, response);
|
||||
|
||||
String fileName = FileUtility.GetFileName(request.getParameter("fileName"));
|
||||
String fileName = FileUtility.getFileName(request.getParameter("fileName"));
|
||||
String fileExt = request.getParameter("fileExt");
|
||||
String sample = request.getParameter("sample");
|
||||
Boolean isEnableDirectUrl = Boolean.valueOf(request.getParameter("directUrl"));
|
||||
@ -55,90 +57,100 @@ public class EditorServlet extends HttpServlet
|
||||
CookieManager cm = new CookieManager(request);
|
||||
User user = Users.getUser(cm.getCookie("uid"));
|
||||
|
||||
if (fileExt != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (fileExt != null) {
|
||||
try {
|
||||
// create demo document
|
||||
fileName = DocumentManager.CreateDemo(fileExt, sampleData, user);
|
||||
response.sendRedirect("EditorServlet?fileName=" + URLEncoder.encode(fileName, "UTF-8")); // redirect the request
|
||||
fileName = DocumentManager.createDemo(fileExt, sampleData, user);
|
||||
|
||||
// redirect the request
|
||||
response.sendRedirect("EditorServlet?fileName=" + URLEncoder.encode(fileName, "UTF-8"));
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
response.getWriter().write("Error: " + ex.getMessage());
|
||||
} catch (Exception ex) {
|
||||
response.getWriter().write("Error: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// create file model (get all the necessary parameters from cookies)
|
||||
FileModel file = new FileModel(fileName, cm.getCookie("ulang"), request.getParameter("actionLink"), user, isEnableDirectUrl);
|
||||
FileModel file = new FileModel(fileName, cm.getCookie("ulang"), request.getParameter("actionLink"),
|
||||
user, isEnableDirectUrl);
|
||||
// change type parameter if needed
|
||||
file.changeType(request.getParameter("mode"), request.getParameter("type"), user, fileName);
|
||||
|
||||
// an image that will be inserted into the document
|
||||
Map<String, Object> dataInsertImage = new HashMap<>();
|
||||
dataInsertImage.put("fileType", "png");
|
||||
dataInsertImage.put("url", DocumentManager.GetServerUrl(true) + "/css/img/logo.png");
|
||||
dataInsertImage.put("url", DocumentManager.getServerUrl(true) + "/css/img/logo.png");
|
||||
if (isEnableDirectUrl) {
|
||||
dataInsertImage.put("directUrl", DocumentManager.GetServerUrl(false) + "/css/img/logo.png");
|
||||
dataInsertImage.put("directUrl", DocumentManager.getServerUrl(false) + "/css/img/logo.png");
|
||||
}
|
||||
|
||||
// a document that will be compared with the current document
|
||||
Map<String, Object> dataCompareFile = new HashMap<>();
|
||||
dataCompareFile.put("fileType", "docx");
|
||||
dataCompareFile.put("url", DocumentManager.GetServerUrl(true) + "/IndexServlet?type=assets&name=sample.docx");
|
||||
dataCompareFile.put("url", DocumentManager.getServerUrl(true) + "/IndexServlet?type=assets&"
|
||||
+ "name=sample.docx");
|
||||
if (isEnableDirectUrl) {
|
||||
dataCompareFile.put("directUrl", DocumentManager.GetServerUrl(false) + "/IndexServlet?type=assets&name=sample.docx");
|
||||
dataCompareFile.put("directUrl", DocumentManager.getServerUrl(false) + "/IndexServlet?"
|
||||
+ "type=assets&name=sample.docx");
|
||||
}
|
||||
|
||||
// recipients data for mail merging
|
||||
Map<String, Object> dataMailMergeRecipients = new HashMap<>();
|
||||
dataMailMergeRecipients.put("fileType", "csv");
|
||||
dataMailMergeRecipients.put("url", DocumentManager.GetServerUrl(true) + "/IndexServlet?type=csv");
|
||||
dataMailMergeRecipients.put("url", DocumentManager.getServerUrl(true) + "/IndexServlet?"
|
||||
+ "type=csv");
|
||||
if (isEnableDirectUrl) {
|
||||
dataMailMergeRecipients.put("directUrl", DocumentManager.GetServerUrl(false) + "/IndexServlet?type=csv");
|
||||
dataMailMergeRecipients.put("directUrl", DocumentManager.getServerUrl(false)
|
||||
+ "/IndexServlet?type=csv");
|
||||
}
|
||||
|
||||
// users data for mentions
|
||||
List<Map<String, Object>> usersForMentions = Users.getUsersForMentions(user.id);
|
||||
List<Map<String, Object>> usersForMentions = Users.getUsersForMentions(user.getId());
|
||||
|
||||
// check if the document token is enabled
|
||||
if (DocumentManager.TokenEnabled())
|
||||
{
|
||||
file.BuildToken(); // generate document token
|
||||
dataInsertImage.put("token", DocumentManager.CreateToken(dataInsertImage)); // create token from the dataInsertImage object
|
||||
dataCompareFile.put("token", DocumentManager.CreateToken(dataCompareFile)); // create token from the dataCompareFile object
|
||||
dataMailMergeRecipients.put("token", DocumentManager.CreateToken(dataMailMergeRecipients)); // create token from the dataMailMergeRecipients object
|
||||
if (DocumentManager.tokenEnabled()) {
|
||||
file.buildToken(); // generate document token
|
||||
|
||||
// create token from the dataInsertImage object
|
||||
dataInsertImage.put("token", DocumentManager.createToken(dataInsertImage));
|
||||
|
||||
// create token from the dataCompareFile object
|
||||
dataCompareFile.put("token", DocumentManager.createToken(dataCompareFile));
|
||||
|
||||
// create token from the dataMailMergeRecipients object
|
||||
dataMailMergeRecipients.put("token", DocumentManager.createToken(dataMailMergeRecipients));
|
||||
}
|
||||
|
||||
Gson gson = new Gson();
|
||||
request.setAttribute("file", file);
|
||||
request.setAttribute("docserviceApiUrl", ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.api"));
|
||||
request.setAttribute("dataInsertImage", gson.toJson(dataInsertImage).substring(1, gson.toJson(dataInsertImage).length()-1));
|
||||
request.setAttribute("docserviceApiUrl", ConfigManager.getProperty("files.docservice.url.site")
|
||||
+ ConfigManager.getProperty("files.docservice.url.api"));
|
||||
request.setAttribute("dataInsertImage", gson.toJson(dataInsertImage)
|
||||
.substring(1, gson.toJson(dataInsertImage).length() - 1));
|
||||
request.setAttribute("dataCompareFile", gson.toJson(dataCompareFile));
|
||||
request.setAttribute("dataMailMergeRecipients", gson.toJson(dataMailMergeRecipients));
|
||||
request.setAttribute("usersForMentions", !user.id.equals("uid-0") ? gson.toJson(usersForMentions) : null);
|
||||
request.setAttribute("usersForMentions", !user.getId()
|
||||
.equals("uid-0") ? gson.toJson(usersForMentions) : null);
|
||||
request.getRequestDispatcher("editor.jsp").forward(request, response);
|
||||
}
|
||||
|
||||
// create get request
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
|
||||
IOException {
|
||||
processRequest(request, response);
|
||||
}
|
||||
|
||||
// create post request
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
protected void doPost(final HttpServletRequest request,
|
||||
final HttpServletResponse response) throws ServletException, IOException {
|
||||
processRequest(request, response);
|
||||
}
|
||||
|
||||
// get servlet information
|
||||
@Override
|
||||
public String getServletInfo()
|
||||
{
|
||||
public String getServletInfo() {
|
||||
return "Editor page";
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,9 +18,8 @@
|
||||
|
||||
package controllers;
|
||||
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import helpers.ConfigManager;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.SSLContext;
|
||||
@ -29,68 +28,56 @@ import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
import helpers.*;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
public class GlobalServletContextListener implements ServletContextListener
|
||||
{
|
||||
public class GlobalServletContextListener implements ServletContextListener {
|
||||
// destroy ServletContextListener interface
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent arg0)
|
||||
{
|
||||
public void contextDestroyed(final ServletContextEvent arg0) {
|
||||
System.out.println("ServletContextListener destroyed");
|
||||
}
|
||||
|
||||
// start ServletContextListener interface
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent arg0)
|
||||
{
|
||||
TrustManager[] trustAllCerts = new TrustManager[]
|
||||
{
|
||||
new X509TrustManager()
|
||||
{
|
||||
public void contextInitialized(final ServletContextEvent arg0) {
|
||||
TrustManager[] trustAllCerts = new TrustManager[] {
|
||||
new X509TrustManager() {
|
||||
// return an array of certificates which are trusted
|
||||
@Override
|
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers()
|
||||
{
|
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
|
||||
// check whether the X509 certificate chain can be validated and is trusted for client authentication
|
||||
@Override
|
||||
public void checkClientTrusted(X509Certificate[] certs, String authType)
|
||||
{
|
||||
public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
|
||||
}
|
||||
|
||||
// check whether the X509 certificate chain can be validated and is trusted for server authentication
|
||||
@Override
|
||||
public void checkServerTrusted(X509Certificate[] certs, String authType)
|
||||
{
|
||||
public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
SSLContext sc;
|
||||
|
||||
if(!ConfigManager.GetProperty("files.docservice.verify-peer-off").isEmpty()) {
|
||||
try
|
||||
{
|
||||
if (!ConfigManager.getProperty("files.docservice.verify-peer-off").isEmpty()) {
|
||||
try {
|
||||
// register the all-trusting trust manager for HTTPS
|
||||
sc = SSLContext.getInstance("SSL");
|
||||
sc.init(null, trustAllCerts, new java.security.SecureRandom());
|
||||
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
|
||||
}
|
||||
catch (NoSuchAlgorithmException | KeyManagementException ex)
|
||||
{
|
||||
} catch (NoSuchAlgorithmException | KeyManagementException ex) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// create all-trusting host name verifier
|
||||
HostnameVerifier allHostsValid = new HostnameVerifier()
|
||||
{
|
||||
HostnameVerifier allHostsValid = new HostnameVerifier() {
|
||||
@Override
|
||||
public boolean verify(String hostname, SSLSession session)
|
||||
{
|
||||
public boolean verify(final String hostname, final SSLSession session) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
@ -100,4 +87,4 @@ public class GlobalServletContextListener implements ServletContextListener
|
||||
|
||||
System.out.println("ServletContextListener started");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -19,17 +19,22 @@
|
||||
package controllers;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import entities.FileType;
|
||||
import entities.User;
|
||||
import helpers.*;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import helpers.ConfigManager;
|
||||
import helpers.CookieManager;
|
||||
import helpers.DocumentManager;
|
||||
import helpers.FileUtility;
|
||||
import helpers.ServiceConverter;
|
||||
import helpers.TrackManager;
|
||||
import helpers.Users;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.primeframework.jwt.Verifier;
|
||||
import org.primeframework.jwt.domain.JWT;
|
||||
import org.primeframework.jwt.hmac.HMACVerifier;
|
||||
import utils.StatusType;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.MultipartConfig;
|
||||
@ -38,77 +43,89 @@ import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.Part;
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Scanner;
|
||||
|
||||
import entities.FileType;
|
||||
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
import org.primeframework.jwt.Verifier;
|
||||
import org.primeframework.jwt.domain.JWT;
|
||||
import org.primeframework.jwt.hmac.HMACVerifier;
|
||||
import static utils.Constants.KILOBYTE_SIZE;
|
||||
|
||||
|
||||
@WebServlet(name = "IndexServlet", urlPatterns = {"/IndexServlet"})
|
||||
@MultipartConfig
|
||||
public class IndexServlet extends HttpServlet
|
||||
{
|
||||
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
public class IndexServlet extends HttpServlet {
|
||||
protected void processRequest(final HttpServletRequest request,
|
||||
final HttpServletResponse response) throws ServletException, IOException {
|
||||
// get the type parameter from the request
|
||||
String action = request.getParameter("type");
|
||||
|
||||
if (action == null)
|
||||
{
|
||||
if (action == null) {
|
||||
// forward the request and response objects to the index.jsp
|
||||
request.getRequestDispatcher("index.jsp").forward(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
DocumentManager.Init(request, response);
|
||||
PrintWriter writer = response.getWriter(); // create a variable to display information about the application and error messages
|
||||
DocumentManager.init(request, response);
|
||||
|
||||
// create a variable to display information about the application and error messages
|
||||
PrintWriter writer = response.getWriter();
|
||||
|
||||
// define functions for each type of operation
|
||||
switch (action.toLowerCase())
|
||||
{
|
||||
switch (action.toLowerCase()) {
|
||||
case "upload":
|
||||
Upload(request, response, writer);
|
||||
upload(request, response, writer);
|
||||
break;
|
||||
case "download":
|
||||
Download(request, response, writer);
|
||||
download(request, response, writer);
|
||||
break;
|
||||
case "downloadhistory":
|
||||
DownloadHistory(request, response, writer);
|
||||
downloadHistory(request, response, writer);
|
||||
break;
|
||||
case "convert":
|
||||
Convert(request, response, writer);
|
||||
convert(request, response, writer);
|
||||
break;
|
||||
case "track":
|
||||
Track(request, response, writer);
|
||||
track(request, response, writer);
|
||||
break;
|
||||
case "remove":
|
||||
Remove(request, response, writer);
|
||||
remove(request, response, writer);
|
||||
break;
|
||||
case "assets":
|
||||
Assets(request, response, writer);
|
||||
assets(request, response, writer);
|
||||
break;
|
||||
case "csv":
|
||||
CSV(request, response, writer);
|
||||
csv(request, response, writer);
|
||||
break;
|
||||
case "files":
|
||||
Files(request, response, writer);
|
||||
files(request, response, writer);
|
||||
break;
|
||||
case "saveas":
|
||||
SaveAs(request, response, writer);
|
||||
saveAs(request, response, writer);
|
||||
break;
|
||||
case "rename":
|
||||
Rename(request, response, writer);
|
||||
rename(request, response, writer);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void SaveAs(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) {
|
||||
private static void saveAs(final HttpServletRequest request,
|
||||
final HttpServletResponse response,
|
||||
final PrintWriter writer) {
|
||||
response.setContentType("text/plain");
|
||||
try {
|
||||
Scanner scanner = new Scanner(request.getInputStream());
|
||||
@ -124,22 +141,22 @@ public class IndexServlet extends HttpServlet
|
||||
|
||||
String title = (String) body.get("title");
|
||||
String saveAsFileUrl = (String) body.get("url");
|
||||
int filesizeMax = Integer.parseInt(ConfigManager.GetProperty("filesize-max"));
|
||||
int filesizeMax = Integer.parseInt(ConfigManager.getProperty("filesize-max"));
|
||||
|
||||
URL url = new URL(saveAsFileUrl);
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
|
||||
InputStream stream = connection.getInputStream();
|
||||
|
||||
if (filesizeMax < stream.available() || stream.available() <= 0) {
|
||||
writer.write( "{\"error\":\"File size is incorrect\"}");
|
||||
writer.write("{\"error\":\"File size is incorrect\"}");
|
||||
}
|
||||
|
||||
String fileName = DocumentManager.GetCorrectName(title, null);
|
||||
DocumentManager.CreateFile(Paths.get(DocumentManager.StoragePath(fileName, null)), stream);
|
||||
String fileName = DocumentManager.getCorrectName(title, null);
|
||||
DocumentManager.createFile(Paths.get(DocumentManager.storagePath(fileName, null)), stream);
|
||||
|
||||
DocumentManager.CreateMeta(fileName, user.id, user.name, null);
|
||||
DocumentManager.createMeta(fileName, user.getId(), user.getName(), null);
|
||||
|
||||
writer.write( "{\"file\": \"" + fileName + "\"}");
|
||||
writer.write("{\"file\": \"" + fileName + "\"}");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
writer.write("{ \"error\" : 1, \"message\" : \"" + e.getMessage() + "\"}");
|
||||
@ -148,52 +165,61 @@ public class IndexServlet extends HttpServlet
|
||||
|
||||
|
||||
// upload a file
|
||||
private static void Upload(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
private static void upload(final HttpServletRequest request,
|
||||
final HttpServletResponse response,
|
||||
final PrintWriter writer) {
|
||||
response.setContentType("text/plain");
|
||||
|
||||
try
|
||||
{
|
||||
try {
|
||||
Part httpPostedFile = request.getPart("file");
|
||||
|
||||
// get file name from the content-disposition response header
|
||||
String fileName = "";
|
||||
for (String content : httpPostedFile.getHeader("content-disposition").split(";"))
|
||||
{
|
||||
if (content.trim().startsWith("filename"))
|
||||
{
|
||||
fileName = content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
|
||||
for (String content : httpPostedFile.getHeader("content-disposition").split(";")) {
|
||||
if (content.trim().startsWith("filename")) {
|
||||
fileName = content
|
||||
.substring(content.indexOf('=') + 1)
|
||||
.trim()
|
||||
.replace("\"", "");
|
||||
}
|
||||
}
|
||||
|
||||
long curSize = httpPostedFile.getSize(); // get file size
|
||||
if (DocumentManager.GetMaxFileSize() < curSize || curSize <= 0) // check if the file size exceeds the maximum file size or is less than 0
|
||||
{
|
||||
writer.write("{ \"error\": \"File size is incorrect\"}"); // if so, write the error status and message to the response
|
||||
|
||||
// check if the file size exceeds the maximum file size or is less than 0
|
||||
if (DocumentManager.getMaxFileSize() < curSize || curSize <= 0) {
|
||||
|
||||
// if so, write the error status and message to the response
|
||||
writer.write("{ \"error\": \"File size is incorrect\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
String curExt = FileUtility.GetFileExtension(fileName); // get current file extension
|
||||
if (!DocumentManager.GetFileExts().contains(curExt)) // check if this extension is supported by the editor
|
||||
{
|
||||
writer.write("{ \"error\": \"File type is not supported\"}"); // if not, write the error status and message to the response
|
||||
String curExt = FileUtility.getFileExtension(fileName); // get current file extension
|
||||
|
||||
// check if this extension is supported by the editor
|
||||
if (!DocumentManager.getFileExts().contains(curExt)) {
|
||||
|
||||
// if not, write the error status and message to the response
|
||||
writer.write("{ \"error\": \"File type is not supported\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
InputStream fileStream = httpPostedFile.getInputStream(); // get input file stream
|
||||
// get input file stream
|
||||
InputStream fileStream = httpPostedFile.getInputStream();
|
||||
|
||||
fileName = DocumentManager.GetCorrectName(fileName, null); // get a file name with an index if the file with such a name already exists
|
||||
String fileStoragePath = DocumentManager.StoragePath(fileName, null); // get the storage path of the file
|
||||
String documentType = FileUtility.GetFileType(fileName).toString().toLowerCase();
|
||||
// get a file name with an index if the file with such a name already exists
|
||||
fileName = DocumentManager.getCorrectName(fileName, null);
|
||||
|
||||
// get the storage path of the file
|
||||
String fileStoragePath = DocumentManager.storagePath(fileName, null);
|
||||
String documentType = FileUtility.getFileType(fileName).toString().toLowerCase();
|
||||
|
||||
File file = new File(fileStoragePath);
|
||||
|
||||
try (FileOutputStream out = new FileOutputStream(file))
|
||||
{
|
||||
try (FileOutputStream out = new FileOutputStream(file)) {
|
||||
int read;
|
||||
final byte[] bytes = new byte[1024];
|
||||
while ((read = fileStream.read(bytes)) != -1)
|
||||
{
|
||||
final byte[] bytes = new byte[KILOBYTE_SIZE];
|
||||
while ((read = fileStream.read(bytes)) != -1) {
|
||||
out.write(bytes, 0, read); // write bytes to the output stream
|
||||
}
|
||||
|
||||
@ -205,24 +231,23 @@ public class IndexServlet extends HttpServlet
|
||||
CookieManager cm = new CookieManager(request);
|
||||
User user = Users.getUser(cm.getCookie("uid"));
|
||||
|
||||
DocumentManager.CreateMeta(fileName, user.id, user.name, null);
|
||||
DocumentManager.createMeta(fileName, user.getId(), user.getName(), null);
|
||||
|
||||
writer.write("{ \"filename\": \"" + fileName + "\", \"documentType\": \"" + documentType + "\" }");
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
writer.write("{ \"error\": \"" + e.getMessage() + "\"}");
|
||||
}
|
||||
}
|
||||
|
||||
// convert a file
|
||||
private static void Convert(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) throws UnsupportedEncodingException {
|
||||
private static void convert(final HttpServletRequest request,
|
||||
final HttpServletResponse response,
|
||||
final PrintWriter writer) throws UnsupportedEncodingException {
|
||||
CookieManager cm = new CookieManager(request);
|
||||
response.setContentType("text/plain");
|
||||
|
||||
try
|
||||
{
|
||||
try {
|
||||
Scanner scanner = new Scanner(request.getInputStream());
|
||||
scanner.useDelimiter("\\A");
|
||||
String bodyString = scanner.hasNext() ? scanner.next() : "";
|
||||
@ -231,48 +256,46 @@ public class IndexServlet extends HttpServlet
|
||||
JSONParser parser = new JSONParser();
|
||||
JSONObject body = (JSONObject) parser.parse(bodyString);
|
||||
|
||||
String fileName = FileUtility.GetFileName((String) body.get("filename"));
|
||||
String fileName = FileUtility.getFileName((String) body.get("filename"));
|
||||
String lang = cm.getCookie("ulang");
|
||||
String filePass = body.get("filePass") != null ? (String) body.get("filePass") : null;
|
||||
String fileUri = DocumentManager.GetDownloadUrl(fileName, true);
|
||||
String fileExt = FileUtility.GetFileExtension(fileName);
|
||||
FileType fileType = FileUtility.GetFileType(fileName);
|
||||
String internalFileExt = DocumentManager.GetInternalExtension(fileType);
|
||||
String fileUri = DocumentManager.getDownloadUrl(fileName, true);
|
||||
String fileExt = FileUtility.getFileExtension(fileName);
|
||||
FileType fileType = FileUtility.getFileType(fileName);
|
||||
String internalFileExt = DocumentManager.getInternalExtension(fileType);
|
||||
|
||||
// check if the file with such an extension can be converted
|
||||
if (DocumentManager.GetConvertExts().contains(fileExt))
|
||||
{
|
||||
if (DocumentManager.getConvertExts().contains(fileExt)) {
|
||||
// generate document key
|
||||
String key = ServiceConverter.GenerateRevisionId(fileUri);
|
||||
String key = ServiceConverter.generateRevisionId(fileUri);
|
||||
|
||||
// get the url to the converted file
|
||||
String newFileUri = ServiceConverter.GetConvertedUri(fileUri, fileExt, internalFileExt, key, filePass, true, lang);
|
||||
String newFileUri = ServiceConverter
|
||||
.getConvertedUri(fileUri, fileExt, internalFileExt, key, filePass, true, lang);
|
||||
|
||||
if (newFileUri.isEmpty())
|
||||
{
|
||||
if (newFileUri.isEmpty()) {
|
||||
writer.write("{ \"step\" : \"0\", \"filename\" : \"" + fileName + "\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
// get a file name of an internal file extension with an index if the file with such a name already exists
|
||||
String correctName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + internalFileExt, null);
|
||||
/* get a file name of an internal file extension with an index if the file
|
||||
with such a name already exists */
|
||||
String correctName = DocumentManager.getCorrectName(FileUtility
|
||||
.getFileNameWithoutExtension(fileName) + internalFileExt, null);
|
||||
|
||||
URL url = new URL(newFileUri);
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
|
||||
InputStream stream = connection.getInputStream(); // get input stream of the converted file
|
||||
|
||||
if (stream == null)
|
||||
{
|
||||
if (stream == null) {
|
||||
throw new Exception("Stream is null");
|
||||
}
|
||||
|
||||
File convertedFile = new File(DocumentManager.StoragePath(correctName, null));
|
||||
try (FileOutputStream out = new FileOutputStream(convertedFile))
|
||||
{
|
||||
File convertedFile = new File(DocumentManager.storagePath(correctName, null));
|
||||
try (FileOutputStream out = new FileOutputStream(convertedFile)) {
|
||||
int read;
|
||||
final byte[] bytes = new byte[1024];
|
||||
while ((read = stream.read(bytes)) != -1)
|
||||
{
|
||||
final byte[] bytes = new byte[KILOBYTE_SIZE];
|
||||
while ((read = stream.read(bytes)) != -1) {
|
||||
out.write(bytes, 0, read); // write bytes to the output stream
|
||||
}
|
||||
|
||||
@ -291,21 +314,20 @@ public class IndexServlet extends HttpServlet
|
||||
// create meta information about the converted file with the user id and name specified
|
||||
User user = Users.getUser(cm.getCookie("uid"));
|
||||
|
||||
DocumentManager.CreateMeta(fileName, user.id, user.name, null);
|
||||
DocumentManager.createMeta(fileName, user.getId(), user.getName(), null);
|
||||
}
|
||||
|
||||
writer.write("{ \"filename\" : \"" + fileName + "\"}");
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
} catch (Exception ex) {
|
||||
writer.write("{ \"error\": \"" + ex.getMessage() + "\"}");
|
||||
}
|
||||
}
|
||||
|
||||
// track file changes
|
||||
private static void Track(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
private static void track(final HttpServletRequest request,
|
||||
final HttpServletResponse response,
|
||||
final PrintWriter writer) {
|
||||
JSONObject body = null;
|
||||
|
||||
// read request body
|
||||
@ -320,7 +342,7 @@ public class IndexServlet extends HttpServlet
|
||||
int status = Math.toIntExact((long) body.get("status"));
|
||||
int saved = 0;
|
||||
|
||||
if (status == 1) { // editing
|
||||
if (status == StatusType.EDITING.getCode()) { // editing
|
||||
JSONArray actions = (JSONArray) body.get("actions");
|
||||
JSONArray users = (JSONArray) body.get("users");
|
||||
JSONObject action = (JSONObject) actions.get(0);
|
||||
@ -329,7 +351,9 @@ public class IndexServlet extends HttpServlet
|
||||
if (users.indexOf(user) == -1) {
|
||||
String key = (String) body.get("key");
|
||||
try {
|
||||
TrackManager.commandRequest("forcesave", key, null); // create a command request with the forcesave method
|
||||
|
||||
// create a command request with the forcesave method
|
||||
TrackManager.commandRequest("forcesave", key, null);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@ -338,9 +362,10 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
|
||||
String userAddress = request.getParameter("userAddress");
|
||||
String fileName = FileUtility.GetFileName(request.getParameter("fileName"));
|
||||
String fileName = FileUtility.getFileName(request.getParameter("fileName"));
|
||||
|
||||
if (status == 2 || status == 3) { // MustSave, Corrupted
|
||||
// MustSave, Corrupted
|
||||
if (status == StatusType.MUST_SAVE.getCode() || status == StatusType.CORRUPTED.getCode()) {
|
||||
try {
|
||||
TrackManager.processSave(body, fileName, userAddress);
|
||||
} catch (Exception ex) {
|
||||
@ -350,7 +375,8 @@ public class IndexServlet extends HttpServlet
|
||||
|
||||
}
|
||||
|
||||
if (status == 6 || status == 7) { // MustForceSave, CorruptedForceSave
|
||||
// MustForceSave, CorruptedForceSave
|
||||
if (status == StatusType.MUST_FORCE_SAVE.getCode() || status == StatusType.CORRUPTED_FORCE_SAVE.getCode()) {
|
||||
try {
|
||||
TrackManager.processForceSave(body, fileName, userAddress);
|
||||
} catch (Exception ex) {
|
||||
@ -363,32 +389,31 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
|
||||
// remove a file
|
||||
private static void Remove(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
try
|
||||
{
|
||||
String fileName = FileUtility.GetFileName(request.getParameter("filename"));
|
||||
String path = DocumentManager.StoragePath(fileName, null);
|
||||
private static void remove(final HttpServletRequest request,
|
||||
final HttpServletResponse response,
|
||||
final PrintWriter writer) {
|
||||
try {
|
||||
String fileName = FileUtility.getFileName(request.getParameter("filename"));
|
||||
String path = DocumentManager.storagePath(fileName, null);
|
||||
|
||||
// delete file
|
||||
File f = new File(path);
|
||||
delete(f);
|
||||
|
||||
// delete file history
|
||||
File hist = new File(DocumentManager.HistoryDir(path));
|
||||
File hist = new File(DocumentManager.historyDir(path));
|
||||
delete(hist);
|
||||
|
||||
writer.write("{ \"success\": true }");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
writer.write("{ \"error\": \"" + e.getMessage() + "\"}");
|
||||
}
|
||||
}
|
||||
|
||||
// get files information
|
||||
private static void Files(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
private static void files(final HttpServletRequest request,
|
||||
final HttpServletResponse response,
|
||||
final PrintWriter writer) {
|
||||
ArrayList<Map<String, Object>> files = null;
|
||||
|
||||
try {
|
||||
@ -396,27 +421,26 @@ public class IndexServlet extends HttpServlet
|
||||
response.setContentType("application/json");
|
||||
|
||||
if (request.getParameter("fileId") == null) {
|
||||
files = DocumentManager.GetFilesInfo(); // get the information about the files from the storage path
|
||||
files = DocumentManager.getFilesInfo(); // get the information about the files from the storage path
|
||||
writer.write(gson.toJson(files));
|
||||
}else {
|
||||
} else {
|
||||
String fileId = request.getParameter("fileId"); // get file id from the request
|
||||
files = DocumentManager.GetFilesInfo(fileId);
|
||||
if(files.isEmpty()) {
|
||||
files = DocumentManager.getFilesInfo(fileId);
|
||||
if (files.isEmpty()) {
|
||||
writer.write("\"File not found\"");
|
||||
}else {
|
||||
} else {
|
||||
writer.write(gson.toJson(files));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
writer.write("{ \"error\": \"" + e.getMessage() + "\"}");
|
||||
}
|
||||
}
|
||||
|
||||
// download a csv file
|
||||
private static void CSV(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
private static void csv(final HttpServletRequest request,
|
||||
final HttpServletResponse response,
|
||||
final PrintWriter writer) {
|
||||
String fileName = "assets/sample/csv.csv";
|
||||
URL fileUrl = Thread.currentThread().getContextClassLoader().getResource(fileName);
|
||||
Path filePath = null;
|
||||
@ -429,9 +453,10 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
|
||||
// get sample files from the assests
|
||||
private static void Assets(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
String fileName = "assets/sample/" + FileUtility.GetFileName(request.getParameter("name"));
|
||||
private static void assets(final HttpServletRequest request,
|
||||
final HttpServletResponse response,
|
||||
final PrintWriter writer) {
|
||||
String fileName = "assets/sample/" + FileUtility.getFileName(request.getParameter("name"));
|
||||
URL fileUrl = Thread.currentThread().getContextClassLoader().getResource(fileName);
|
||||
Path filePath = null;
|
||||
try {
|
||||
@ -443,36 +468,39 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
|
||||
// download a file from history
|
||||
private static void DownloadHistory(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
private static void downloadHistory(final HttpServletRequest request,
|
||||
final HttpServletResponse response,
|
||||
final PrintWriter writer) {
|
||||
try {
|
||||
if (DocumentManager.TokenEnabled()) {
|
||||
if (DocumentManager.tokenEnabled()) {
|
||||
|
||||
String DocumentJwtHeader = ConfigManager.GetProperty("files.docservice.header");
|
||||
String documentJwtHeader = ConfigManager.getProperty("files.docservice.header");
|
||||
|
||||
String header = (String) request.getHeader(DocumentJwtHeader == null || DocumentJwtHeader.isEmpty() ? "Authorization" : DocumentJwtHeader);
|
||||
String header = (String) request.getHeader(documentJwtHeader == null || documentJwtHeader.isEmpty()
|
||||
? "Authorization" : documentJwtHeader);
|
||||
if (header != null && !header.isEmpty()) {
|
||||
String token = header.startsWith("Bearer ") ? header.substring(7) : header;
|
||||
String bearerPrefix = "Bearer ";
|
||||
String token = header.startsWith(bearerPrefix) ? header.substring(bearerPrefix.length()) : header;
|
||||
try {
|
||||
Verifier verifier = HMACVerifier.newVerifier(DocumentManager.GetTokenSecret());
|
||||
Verifier verifier = HMACVerifier.newVerifier(DocumentManager.getTokenSecret());
|
||||
JWT jwt = JWT.getDecoder().decode(token, verifier);
|
||||
} catch (Exception e) {
|
||||
response.sendError(403, "JWT validation failed");
|
||||
response.sendError(HttpServletResponse.SC_FORBIDDEN, "JWT validation failed");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
response.sendError(403, "JWT validation failed");
|
||||
response.sendError(HttpServletResponse.SC_FORBIDDEN, "JWT validation failed");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
String fileName = FileUtility.GetFileName(request.getParameter("fileName"));
|
||||
String fileName = FileUtility.getFileName(request.getParameter("fileName"));
|
||||
String userAddress = request.getParameter("userAddress");
|
||||
|
||||
String ver = request.getParameter("ver"); // Document version
|
||||
String file = request.getParameter("file"); // File. If not defined, then Prev.*
|
||||
|
||||
String filePath = DocumentManager.HistoryPath(fileName, userAddress, ver, file);
|
||||
String filePath = DocumentManager.historyPath(fileName, userAddress, ver, file);
|
||||
|
||||
download(filePath, response, writer);
|
||||
} catch (Exception e) {
|
||||
@ -481,33 +509,38 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
|
||||
// download a file
|
||||
private static void Download(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
private static void download(final HttpServletRequest request,
|
||||
final HttpServletResponse response,
|
||||
final PrintWriter writer) {
|
||||
try {
|
||||
String fileName = FileUtility.GetFileName(request.getParameter("fileName"));
|
||||
String fileName = FileUtility.getFileName(request.getParameter("fileName"));
|
||||
String userAddress = request.getParameter("userAddress");
|
||||
String isEmbedded = request.getParameter("dmode");
|
||||
|
||||
if (DocumentManager.TokenEnabled() && isEmbedded == null) {
|
||||
if (DocumentManager.tokenEnabled() && isEmbedded == null && userAddress != null) {
|
||||
|
||||
String DocumentJwtHeader = ConfigManager.GetProperty("files.docservice.header");
|
||||
String documentJwtHeader = ConfigManager.getProperty("files.docservice.header");
|
||||
|
||||
String header = (String) request.getHeader(DocumentJwtHeader == null || DocumentJwtHeader.isEmpty() ? "Authorization" : DocumentJwtHeader);
|
||||
String header = (String) request.getHeader(documentJwtHeader == null || documentJwtHeader.isEmpty()
|
||||
? "Authorization" : documentJwtHeader);
|
||||
String token = "";
|
||||
if (header != null && !header.isEmpty()) {
|
||||
String token = header.startsWith("Bearer ") ? header.substring(7) : header;
|
||||
try {
|
||||
Verifier verifier = HMACVerifier.newVerifier(DocumentManager.GetTokenSecret());
|
||||
JWT jwt = JWT.getDecoder().decode(token, verifier);
|
||||
} catch (Exception e) {
|
||||
response.sendError(403, "JWT validation failed");
|
||||
return;
|
||||
}
|
||||
String bearerPrefix = "Bearer ";
|
||||
token = header.startsWith(bearerPrefix) ? header.substring(bearerPrefix.length()) : header;
|
||||
}
|
||||
try {
|
||||
Verifier verifier = HMACVerifier.newVerifier(DocumentManager.getTokenSecret());
|
||||
JWT jwt = JWT.getDecoder().decode(token, verifier);
|
||||
} catch (Exception e) {
|
||||
response.sendError(HttpServletResponse.SC_FORBIDDEN, "JWT validation failed");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
String filePath = DocumentManager.ForcesavePath(fileName, userAddress, false); // get the path to the force saved document version
|
||||
// get the path to the force saved document version
|
||||
String filePath = DocumentManager.forcesavePath(fileName, userAddress, false);
|
||||
if (filePath.equals("")) {
|
||||
filePath = DocumentManager.StoragePath(fileName, userAddress); // or to the original document
|
||||
filePath = DocumentManager.storagePath(fileName, userAddress); // or to the original document
|
||||
}
|
||||
download(filePath, response, writer);
|
||||
} catch (Exception e) {
|
||||
@ -515,18 +548,20 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
}
|
||||
|
||||
private static void delete(File f) throws Exception {
|
||||
private static void delete(final File f) throws Exception {
|
||||
// to delete a directory
|
||||
if (f.isDirectory()) {
|
||||
for (File c : f.listFiles()) // run through all the files in it
|
||||
delete(c); // and delete them
|
||||
for (File c : f.listFiles()) { // run through all the files in it
|
||||
delete(c); // and delete them
|
||||
}
|
||||
}
|
||||
if (!f.delete())
|
||||
if (!f.delete()) {
|
||||
throw new Exception("Failed to delete file: " + f);
|
||||
}
|
||||
}
|
||||
|
||||
// download data from the url to the file
|
||||
private static void download(String filePath, HttpServletResponse response, PrintWriter writer) {
|
||||
private static void download(final String filePath, final HttpServletResponse response, final PrintWriter writer) {
|
||||
String fileType = null;
|
||||
try {
|
||||
fileType = Files.probeContentType(Paths.get(filePath));
|
||||
@ -546,11 +581,12 @@ public class IndexServlet extends HttpServlet
|
||||
FileInputStream fileInputStream = new FileInputStream(file);
|
||||
inputStream = new BufferedInputStream(fileInputStream);
|
||||
int readBytes = 0;
|
||||
while ((readBytes = inputStream.read()) != -1) // write bytes to the output stream
|
||||
while ((readBytes = inputStream.read()) != -1) { // write bytes to the output stream
|
||||
writer.write(readBytes);
|
||||
}catch (Exception e){
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}finally {
|
||||
} finally {
|
||||
try {
|
||||
inputStream.close();
|
||||
} catch (IOException e) {
|
||||
@ -560,7 +596,9 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
|
||||
// rename a file
|
||||
private static void Rename(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) {
|
||||
private static void rename(final HttpServletRequest request,
|
||||
final HttpServletResponse response,
|
||||
final PrintWriter writer) {
|
||||
try {
|
||||
Scanner scanner = new Scanner(request.getInputStream());
|
||||
scanner.useDelimiter("\\A");
|
||||
@ -576,11 +614,11 @@ public class IndexServlet extends HttpServlet
|
||||
String origExt = "." + (String) body.get("ext");
|
||||
String curExt = newfilename;
|
||||
|
||||
if(newfilename.indexOf(".") != -1) {
|
||||
curExt = (String) FileUtility.GetFileExtension(newfilename);
|
||||
if (newfilename.indexOf(".") != -1) {
|
||||
curExt = (String) FileUtility.getFileExtension(newfilename);
|
||||
}
|
||||
|
||||
if(origExt.compareTo(curExt) != 0) {
|
||||
if (origExt.compareTo(curExt) != 0) {
|
||||
newfilename += origExt;
|
||||
}
|
||||
|
||||
@ -598,22 +636,21 @@ public class IndexServlet extends HttpServlet
|
||||
|
||||
// process get request
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
protected void doGet(final HttpServletRequest request,
|
||||
final HttpServletResponse response) throws ServletException, IOException {
|
||||
processRequest(request, response);
|
||||
}
|
||||
|
||||
// process post request
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
protected void doPost(final HttpServletRequest request,
|
||||
final HttpServletResponse response) throws ServletException, IOException {
|
||||
processRequest(request, response);
|
||||
}
|
||||
|
||||
// get servlet information
|
||||
@Override
|
||||
public String getServletInfo()
|
||||
{
|
||||
public String getServletInfo() {
|
||||
return "Handler";
|
||||
}
|
||||
}
|
||||
|
||||
@ -21,15 +21,15 @@ package entities;
|
||||
import java.util.List;
|
||||
|
||||
public class CommentGroups {
|
||||
public List<String> view;
|
||||
public List<String> edit;
|
||||
public List<String> remove;
|
||||
public CommentGroups(){
|
||||
private List<String> view;
|
||||
private List<String> edit;
|
||||
private List<String> remove;
|
||||
public CommentGroups() {
|
||||
|
||||
}
|
||||
public CommentGroups(List<String> view, List<String> edit, List<String> remove){
|
||||
this.view = view;
|
||||
this.edit = edit;
|
||||
this.remove = remove;
|
||||
public CommentGroups(final List<String> viewParam, final List<String> editParam, final List<String> removeParam) {
|
||||
this.view = viewParam;
|
||||
this.edit = editParam;
|
||||
this.remove = removeParam;
|
||||
}
|
||||
}
|
||||
|
||||
@ -20,7 +20,9 @@ package entities;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import helpers.*;
|
||||
import helpers.DocumentManager;
|
||||
import helpers.FileUtility;
|
||||
import helpers.ServiceConverter;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
@ -28,40 +30,57 @@ import org.json.simple.parser.JSONParser;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class FileModel
|
||||
{
|
||||
public String type = "desktop";
|
||||
public String mode = "edit";
|
||||
public String documentType;
|
||||
public Document document;
|
||||
public EditorConfig editorConfig;
|
||||
public String token;
|
||||
public class FileModel {
|
||||
private String type = "desktop";
|
||||
private String mode = "edit";
|
||||
private String documentType;
|
||||
private Document document;
|
||||
private EditorConfig editorConfig;
|
||||
private String token;
|
||||
|
||||
// create file model
|
||||
public FileModel(String fileName, String lang, String actionData, User user, Boolean isEnableDirectUrl)
|
||||
{
|
||||
if (fileName == null) fileName = "";
|
||||
fileName = fileName.trim(); // remove extra spaces in the file name
|
||||
public FileModel(final String fileNameParam,
|
||||
final String lang,
|
||||
final String actionData,
|
||||
final User user,
|
||||
final Boolean isEnableDirectUrl) {
|
||||
|
||||
// remove extra spaces in the file name if not null
|
||||
String fileName = fileNameParam == null ? "" : fileNameParam.trim();
|
||||
|
||||
// get file type from the file name (word, cell or slide)
|
||||
documentType = FileUtility.GetFileType(fileName).toString().toLowerCase();
|
||||
documentType = FileUtility.getFileType(fileName).toString().toLowerCase();
|
||||
|
||||
// set the document parameters
|
||||
document = new Document();
|
||||
document.title = fileName;
|
||||
document.url = DocumentManager.GetDownloadUrl(fileName, true); // get file url
|
||||
document.directUrl = isEnableDirectUrl ? DocumentManager.GetDownloadUrl(fileName, false) : ""; // get direct url
|
||||
document.fileType = FileUtility.GetFileExtension(fileName).replace(".", ""); // get file extension from the file name
|
||||
// generate document key
|
||||
document.key = ServiceConverter.GenerateRevisionId(DocumentManager.CurUserHostAddress(null) + "/" + fileName + "/" + Long.toString(new File(DocumentManager.StoragePath(fileName, null)).lastModified()));
|
||||
document.info = new Info();
|
||||
document.info.favorite = user.favorite;
|
||||
document.setTitle(fileName);
|
||||
document.setUrl(DocumentManager.getDownloadUrl(fileName, true)); // get file url
|
||||
|
||||
String templatesImageUrl = DocumentManager.GetTemplateImageUrl(FileUtility.GetFileType(fileName));
|
||||
// get direct url
|
||||
document.setDirectUrl(isEnableDirectUrl ? DocumentManager.getDownloadUrl(fileName, false) : "");
|
||||
|
||||
// get file extension from the file name
|
||||
document.setFileType(FileUtility.getFileExtension(fileName).replace(".", ""));
|
||||
// generate document key
|
||||
document.setKey(ServiceConverter
|
||||
.generateRevisionId(DocumentManager
|
||||
.curUserHostAddress(null) + "/" + fileName + "/"
|
||||
+ Long.toString(new File(DocumentManager.storagePath(fileName, null))
|
||||
.lastModified())));
|
||||
document.setInfo(new Info());
|
||||
document.getInfo().setFavorite(user.getFavorite());
|
||||
|
||||
String templatesImageUrl = DocumentManager.getTemplateImageUrl(FileUtility.getFileType(fileName));
|
||||
List<Map<String, String>> templates = new ArrayList<>();
|
||||
String createUrl = DocumentManager.GetCreateUrl(FileUtility.GetFileType(fileName));
|
||||
String createUrl = DocumentManager.getCreateUrl(FileUtility.getFileType(fileName));
|
||||
|
||||
// add templates for the "Create New" from menu option
|
||||
Map<String, String> templateForBlankDocument = new HashMap<>();
|
||||
@ -77,63 +96,70 @@ public class FileModel
|
||||
|
||||
// set the editor config parameters
|
||||
editorConfig = new EditorConfig(actionData);
|
||||
editorConfig.callbackUrl = DocumentManager.GetCallback(fileName); // get callback url
|
||||
editorConfig.setCallbackUrl(DocumentManager.getCallback(fileName)); // get callback url
|
||||
|
||||
editorConfig.coEditing = mode.equals("view") && user.id.equals("uid-0") ?
|
||||
new HashMap<String, Object>() {{
|
||||
HashMap<String, Object> coEditing = mode.equals("view") && user.getId().equals("uid-0")
|
||||
? new HashMap<String, Object>() {{
|
||||
put("mode", "strict");
|
||||
put("change", false);
|
||||
}} : null;
|
||||
|
||||
if (lang != null) editorConfig.lang = lang; // write language parameter to the config
|
||||
editorConfig.setCoEditing(coEditing);
|
||||
if (lang != null) {
|
||||
editorConfig.setLang(lang); // write language parameter to the config
|
||||
}
|
||||
|
||||
editorConfig.createUrl = !user.id.equals("uid-0") ? createUrl : null;
|
||||
editorConfig.templates = user.templates ? templates : null;
|
||||
editorConfig.setCreateUrl(!user.getId().equals("uid-0") ? createUrl : null);
|
||||
editorConfig.setTemplates(user.getTemplates() ? templates : null);
|
||||
|
||||
// write user information to the config (id, name and group)
|
||||
editorConfig.user.id = !user.id.equals("uid-0") ? user.id : null;
|
||||
editorConfig.user.name = user.name;
|
||||
editorConfig.user.group = user.group;
|
||||
editorConfig.getUser().setId(!user.getId().equals("uid-0") ? user.getId() : null);
|
||||
editorConfig.getUser().setName(user.getName());
|
||||
editorConfig.getUser().setGroup(user.getGroup());
|
||||
|
||||
// write the absolute URL to the file location
|
||||
editorConfig.customization.goback.url = DocumentManager.GetServerUrl(false) + "/IndexServlet";
|
||||
editorConfig.getCustomization().getGoback()
|
||||
.setUrl(DocumentManager.getServerUrl(false) + "/IndexServlet");
|
||||
|
||||
changeType(mode, type, user, fileName);
|
||||
}
|
||||
|
||||
// change the document type
|
||||
public void changeType(String _mode, String _type, User user, String fileName)
|
||||
{
|
||||
if (_mode != null) mode = _mode;
|
||||
if (_type != null) type = _type;
|
||||
public void changeType(final String modeParam, final String typeParam, final User user, final String fileName) {
|
||||
if (modeParam != null) {
|
||||
mode = modeParam;
|
||||
}
|
||||
if (typeParam != null) {
|
||||
type = typeParam;
|
||||
}
|
||||
|
||||
// check if the file with such an extension can be edited
|
||||
String fileExt = FileUtility.GetFileExtension(document.title);
|
||||
Boolean canEdit = DocumentManager.GetEditedExts().contains(fileExt);
|
||||
String fileExt = FileUtility.getFileExtension(document.getTitle());
|
||||
Boolean canEdit = DocumentManager.getEditedExts().contains(fileExt);
|
||||
// check if the Submit form button is displayed or not
|
||||
editorConfig.customization.submitForm = mode.equals("fillForms") && user.id.equals("uid-1") && false;
|
||||
editorConfig.getCustomization().setSubmitForm(false);
|
||||
|
||||
if ((!canEdit && mode.equals("edit") || mode.equals("fillForms")) && DocumentManager.GetFillExts().contains(fileExt)) {
|
||||
if ((!canEdit && mode.equals("edit") || mode.equals("fillForms"))
|
||||
&& DocumentManager.getFillExts().contains(fileExt)) {
|
||||
canEdit = true;
|
||||
mode = "fillForms";
|
||||
}
|
||||
// set the mode parameter: change it to view if the document can't be edited
|
||||
editorConfig.mode = canEdit && !mode.equals("view") ? "edit" : "view";
|
||||
editorConfig.setMode(canEdit && !mode.equals("view") ? "edit" : "view");
|
||||
|
||||
// set document permissions
|
||||
document.permissions = new Permissions(mode, type, canEdit, user);
|
||||
document.setPermissions(new Permissions(mode, type, canEdit, user));
|
||||
|
||||
if (type.equals("embedded")) InitDesktop(fileName); // set parameters for the embedded document
|
||||
if (type.equals("embedded")) {
|
||||
initDesktop(fileName); // set parameters for the embedded document
|
||||
}
|
||||
}
|
||||
|
||||
public void InitDesktop(String fileName)
|
||||
{
|
||||
editorConfig.InitDesktop(DocumentManager.GetDownloadUrl(fileName, false) + "&dmode=emb");
|
||||
public void initDesktop(final String fileName) {
|
||||
editorConfig.initDesktop(DocumentManager.getDownloadUrl(fileName, false) + "&dmode=emb");
|
||||
}
|
||||
|
||||
// generate document token
|
||||
public void BuildToken()
|
||||
{
|
||||
public void buildToken() {
|
||||
// write all the necessary document parameters to the map
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("type", type);
|
||||
@ -142,16 +168,19 @@ public class FileModel
|
||||
map.put("editorConfig", editorConfig);
|
||||
|
||||
// and create token from them
|
||||
token = DocumentManager.CreateToken(map);
|
||||
token = DocumentManager.createToken(map);
|
||||
}
|
||||
|
||||
// get document history
|
||||
public String[] GetHistory()
|
||||
{
|
||||
public String[] getHistory() {
|
||||
JSONParser parser = new JSONParser();
|
||||
String histDir = DocumentManager.HistoryDir(DocumentManager.StoragePath(document.title, null)); // get history directory
|
||||
if (DocumentManager.GetFileVersion(histDir) > 0) {
|
||||
Integer curVer = DocumentManager.GetFileVersion(histDir); // get current file version if it is greater than 0
|
||||
|
||||
// get history directory
|
||||
String histDir = DocumentManager.historyDir(DocumentManager.storagePath(document.getTitle(), null));
|
||||
if (DocumentManager.getFileVersion(histDir) > 0) {
|
||||
|
||||
// get current file version if it is greater than 0
|
||||
Integer curVer = DocumentManager.getFileVersion(histDir);
|
||||
|
||||
List<Object> hist = new ArrayList<>();
|
||||
Map<String, Object> histData = new HashMap<String, Object>();
|
||||
@ -159,19 +188,21 @@ public class FileModel
|
||||
for (Integer i = 1; i <= curVer; i++) { // run through all the file versions
|
||||
Map<String, Object> obj = new HashMap<String, Object>();
|
||||
Map<String, Object> dataObj = new HashMap<String, Object>();
|
||||
String verDir = DocumentManager.VersionDir(histDir, i); // get the path to the given file version
|
||||
String verDir = DocumentManager.versionDir(histDir, i); // get the path to the given file version
|
||||
|
||||
try {
|
||||
String key = null;
|
||||
|
||||
// get document key
|
||||
key = i == curVer ? document.key : readFileToEnd(new File(verDir + File.separator + "key.txt"));
|
||||
key = i == curVer
|
||||
? document.getKey() : readFileToEnd(new File(verDir + File.separator + "key.txt"));
|
||||
|
||||
obj.put("key", key);
|
||||
obj.put("version", i);
|
||||
|
||||
if (i == 1) { // check if the version number is equal to 1
|
||||
String createdInfo = readFileToEnd(new File(histDir + File.separator + "createdInfo.json")); // get file with meta data
|
||||
String createdInfo = readFileToEnd(new File(histDir + File.separator
|
||||
+ "createdInfo.json")); // get file with meta data
|
||||
JSONObject json = (JSONObject) parser.parse(createdInfo); // and turn it into json object
|
||||
|
||||
// write meta information to the object (user information and creation date)
|
||||
@ -182,17 +213,22 @@ public class FileModel
|
||||
obj.put("user", user);
|
||||
}
|
||||
|
||||
dataObj.put("fileType", FileUtility.GetFileExtension(document.title).substring(1));
|
||||
dataObj.put("fileType", FileUtility.getFileExtension(document.getTitle()).substring(1));
|
||||
dataObj.put("key", key);
|
||||
dataObj.put("url", i == curVer ? document.url : DocumentManager.GetDownloadHistoryUrl(document.title, i, "prev" + FileUtility.GetFileExtension(document.title), true));
|
||||
if (!document.directUrl.equals("")) {
|
||||
dataObj.put("directUrl", i == curVer ? document.url : DocumentManager.GetDownloadHistoryUrl(document.title, i, "prev" + FileUtility.GetFileExtension(document.title), false));
|
||||
dataObj.put("url", i == curVer ? document.getUrl() : DocumentManager
|
||||
.getDownloadHistoryUrl(document.getTitle(), i, "prev" + FileUtility
|
||||
.getFileExtension(document.getTitle()), true));
|
||||
if (!document.getDirectUrl().equals("")) {
|
||||
dataObj.put("directUrl", i == curVer ? document.getUrl() : DocumentManager
|
||||
.getDownloadHistoryUrl(document.getTitle(), i, "prev" + FileUtility
|
||||
.getFileExtension(document.getTitle()), false));
|
||||
}
|
||||
dataObj.put("version", i);
|
||||
|
||||
if (i > 1) { //check if the version number is greater than 1
|
||||
// if so, get the path to the changes.json file
|
||||
JSONObject changes = (JSONObject) parser.parse(readFileToEnd(new File(DocumentManager.VersionDir(histDir, i - 1) + File.separator + "changes.json")));
|
||||
JSONObject changes = (JSONObject) parser.parse(readFileToEnd(new File(DocumentManager
|
||||
.versionDir(histDir, i - 1) + File.separator + "changes.json")));
|
||||
JSONObject change = (JSONObject) ((JSONArray) changes.get("changes")).get(0);
|
||||
|
||||
// write information about changes to the object
|
||||
@ -201,21 +237,27 @@ public class FileModel
|
||||
obj.put("created", !change.isEmpty() ? change.get("created") : null);
|
||||
obj.put("user", !change.isEmpty() ? change.get("user") : null);
|
||||
|
||||
Map<String, Object> prev = (Map<String, Object>) histData.get(Integer.toString(i - 2)); // get the history data from the previous file version
|
||||
// get the history data from the previous file version
|
||||
Map<String, Object> prev = (Map<String, Object>) histData.get(Integer.toString(i - 2));
|
||||
Map<String, Object> prevInfo = new HashMap<String, Object>();
|
||||
prevInfo.put("fileType", prev.get("fileType"));
|
||||
prevInfo.put("key", prev.get("key")); // write key and url information about previous file version
|
||||
|
||||
// write key and url information about previous file version
|
||||
prevInfo.put("key", prev.get("key"));
|
||||
prevInfo.put("url", prev.get("url"));
|
||||
dataObj.put("previous", prevInfo); // write information about previous file version to the data object
|
||||
|
||||
// write information about previous file version to the data object
|
||||
dataObj.put("previous", prevInfo);
|
||||
// write the path to the diff.zip archive with differences in this file version
|
||||
Integer verdiff = i - 1;
|
||||
String changesUrl = DocumentManager.GetDownloadHistoryUrl(document.title, verdiff, "diff.zip", true);
|
||||
String changesUrl = DocumentManager
|
||||
.getDownloadHistoryUrl(document.getTitle(), verdiff,
|
||||
"diff.zip", true);
|
||||
dataObj.put("changesUrl", changesUrl);
|
||||
}
|
||||
|
||||
if (DocumentManager.TokenEnabled())
|
||||
{
|
||||
dataObj.put("token", DocumentManager.CreateToken(dataObj));
|
||||
if (DocumentManager.tokenEnabled()) {
|
||||
dataObj.put("token", DocumentManager.createToken(dataObj));
|
||||
}
|
||||
|
||||
hist.add(obj);
|
||||
@ -230,17 +272,16 @@ public class FileModel
|
||||
histObj.put("history", hist);
|
||||
|
||||
Gson gson = new Gson();
|
||||
return new String[] { gson.toJson(histObj), gson.toJson(histData) };
|
||||
return new String[] {gson.toJson(histObj), gson.toJson(histData) };
|
||||
}
|
||||
return new String[] { "", "" };
|
||||
return new String[] {"", "" };
|
||||
}
|
||||
|
||||
// read a file
|
||||
private String readFileToEnd(File file) {
|
||||
private String readFileToEnd(final File file) {
|
||||
String output = "";
|
||||
try {
|
||||
try(FileInputStream is = new FileInputStream(file))
|
||||
{
|
||||
try (FileInputStream is = new FileInputStream(file)) {
|
||||
Scanner scanner = new Scanner(is); // read data from the source
|
||||
scanner.useDelimiter("\\A");
|
||||
while (scanner.hasNext()) {
|
||||
@ -253,82 +294,135 @@ public class FileModel
|
||||
}
|
||||
|
||||
// the document parameters
|
||||
public class Document
|
||||
{
|
||||
public String title;
|
||||
public String url;
|
||||
public String directUrl;
|
||||
public String fileType;
|
||||
public String key;
|
||||
public Info info;
|
||||
public Permissions permissions;
|
||||
public class Document {
|
||||
private String title;
|
||||
private String url;
|
||||
private String directUrl;
|
||||
private String fileType;
|
||||
private String key;
|
||||
private Info info;
|
||||
private Permissions permissions;
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(final String titleParam) {
|
||||
this.title = titleParam;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(final String urlParam) {
|
||||
this.url = urlParam;
|
||||
}
|
||||
|
||||
public String getDirectUrl() {
|
||||
return directUrl;
|
||||
}
|
||||
|
||||
public void setDirectUrl(final String directUrlParam) {
|
||||
this.directUrl = directUrlParam;
|
||||
}
|
||||
|
||||
public void setFileType(final String fileTypeParam) {
|
||||
this.fileType = fileTypeParam;
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public void setKey(final String keyParam) {
|
||||
this.key = keyParam;
|
||||
}
|
||||
|
||||
public Info getInfo() {
|
||||
return info;
|
||||
}
|
||||
|
||||
public void setInfo(final Info infoParam) {
|
||||
this.info = infoParam;
|
||||
}
|
||||
|
||||
public Permissions getPermissions() {
|
||||
return permissions;
|
||||
}
|
||||
|
||||
public void setPermissions(final Permissions permissionsParam) {
|
||||
this.permissions = permissionsParam;
|
||||
}
|
||||
}
|
||||
|
||||
// the permissions parameters
|
||||
public class Permissions
|
||||
{
|
||||
public Boolean comment;
|
||||
public Boolean сopy;
|
||||
public Boolean download;
|
||||
public Boolean edit;
|
||||
public Boolean print;
|
||||
public Boolean fillForms;
|
||||
public Boolean modifyFilter;
|
||||
public Boolean modifyContentControl;
|
||||
public Boolean review;
|
||||
public Boolean chat;
|
||||
public List<String> reviewGroups;
|
||||
public CommentGroups commentGroups;
|
||||
public List<String> userInfoGroups;
|
||||
public class Permissions {
|
||||
private final Boolean comment;
|
||||
private final Boolean copy;
|
||||
private final Boolean download;
|
||||
private final Boolean edit;
|
||||
private final Boolean print;
|
||||
private final Boolean fillForms;
|
||||
private final Boolean modifyFilter;
|
||||
private final Boolean modifyContentControl;
|
||||
private final Boolean review;
|
||||
private final Boolean chat;
|
||||
private final List<String> reviewGroups;
|
||||
private final CommentGroups commentGroups;
|
||||
private final List<String> userInfoGroups;
|
||||
//public Gson gson = new Gson();
|
||||
|
||||
// defines what can be done with a document
|
||||
public Permissions(String mode, String type, Boolean canEdit, User user)
|
||||
{
|
||||
comment = !mode.equals("view") && !mode.equals("fillForms") && !mode.equals("embedded") && !mode.equals("blockcontent");
|
||||
сopy = !user.deniedPermissions.contains("сopy");
|
||||
download = !user.deniedPermissions.contains("download");
|
||||
edit = canEdit && (mode.equals("edit") || mode.equals("view") || mode.equals("filter") || mode.equals("blockcontent"));
|
||||
print = !user.deniedPermissions.contains("print");
|
||||
fillForms = !mode.equals("view") && !mode.equals("comment") && !mode.equals("embedded") && !mode.equals("blockcontent");
|
||||
modifyFilter = !mode.equals("filter");
|
||||
modifyContentControl = !mode.equals("blockcontent");
|
||||
review = canEdit && (mode.equals("edit") || mode.equals("review"));
|
||||
chat = !user.id.equals("uid-0");
|
||||
reviewGroups = user.reviewGroups;
|
||||
commentGroups = user.commentGroups;
|
||||
userInfoGroups = user.userInfoGroups;
|
||||
public Permissions(final String modeParam, final String typeParam, final Boolean canEdit, final User user) {
|
||||
comment = !modeParam.equals("view") && !modeParam.equals("fillForms") && !modeParam.equals("embedded")
|
||||
&& !modeParam.equals("blockcontent");
|
||||
copy = !user.getDeniedPermissions().contains("сopy");
|
||||
download = !user.getDeniedPermissions().contains("download");
|
||||
edit = canEdit && (modeParam.equals("edit") || modeParam.equals("view") || modeParam.equals("filter")
|
||||
|| modeParam.equals("blockcontent"));
|
||||
print = !user.getDeniedPermissions().contains("print");
|
||||
fillForms = !modeParam.equals("view") && !modeParam.equals("comment") && !modeParam.equals("embedded")
|
||||
&& !modeParam.equals("blockcontent");
|
||||
modifyFilter = !modeParam.equals("filter");
|
||||
modifyContentControl = !modeParam.equals("blockcontent");
|
||||
review = canEdit && (modeParam.equals("edit") || modeParam.equals("review"));
|
||||
chat = !user.getId().equals("uid-0");
|
||||
reviewGroups = user.getReviewGroups();
|
||||
commentGroups = user.getCommentGroups();
|
||||
userInfoGroups = user.getUserInfoGroups();
|
||||
}
|
||||
}
|
||||
|
||||
// the Favorite icon state
|
||||
public class Info
|
||||
{
|
||||
public String owner = "Me";
|
||||
public Boolean favorite;
|
||||
public String uploaded = getDate();
|
||||
public class Info {
|
||||
private String owner = "Me";
|
||||
private Boolean favorite;
|
||||
private String uploaded = getDate();
|
||||
|
||||
private String getDate() {
|
||||
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd yyyy", Locale.US);
|
||||
return simpleDateFormat.format(new Date());
|
||||
}
|
||||
|
||||
public void setFavorite(final Boolean favoriteParam) {
|
||||
this.favorite = favoriteParam;
|
||||
}
|
||||
}
|
||||
// the editor config parameters
|
||||
public class EditorConfig
|
||||
{
|
||||
public HashMap<String, Object> actionLink = null;
|
||||
public String mode = "edit";
|
||||
public String callbackUrl;
|
||||
public HashMap<String, Object> coEditing = null;
|
||||
public String lang = "en";
|
||||
public String createUrl;
|
||||
public List<Map<String, String>> templates;
|
||||
public User user;
|
||||
public Customization customization;
|
||||
public Embedded embedded;
|
||||
public class EditorConfig {
|
||||
private HashMap<String, Object> actionLink = null;
|
||||
private String mode = "edit";
|
||||
private String callbackUrl;
|
||||
private HashMap<String, Object> coEditing = null;
|
||||
private String lang = "en";
|
||||
private String createUrl;
|
||||
private List<Map<String, String>> templates;
|
||||
private User user;
|
||||
private Customization customization;
|
||||
private Embedded embedded;
|
||||
|
||||
public EditorConfig(String actionData)
|
||||
{
|
||||
public EditorConfig(final String actionData) {
|
||||
// get the action in the document that will be scrolled to (bookmark or comment)
|
||||
if (actionData != null) {
|
||||
Gson gson = new Gson();
|
||||
@ -339,35 +433,111 @@ public class FileModel
|
||||
}
|
||||
|
||||
// set parameters for the embedded document
|
||||
public void InitDesktop(String url)
|
||||
{
|
||||
public void initDesktop(final String url) {
|
||||
embedded = new Embedded();
|
||||
embedded.saveUrl = url; // the absolute URL that will allow the document to be saved onto the user personal computer
|
||||
embedded.embedUrl = url; // the absolute URL to the document serving as a source file for the document embedded into the web page
|
||||
embedded.shareUrl = url; // the absolute URL that will allow other users to share this document
|
||||
embedded.toolbarDocked = "top"; // the place for the embedded viewer toolbar, can be either top or bottom
|
||||
|
||||
// the absolute URL that will allow the document to be saved onto the user personal computer
|
||||
embedded.setSaveUrl(url);
|
||||
|
||||
// the absolute URL to the document serving as a source file for the document embedded into the web page
|
||||
embedded.setEmbedUrl(url);
|
||||
|
||||
// the absolute URL that will allow other users to share this document
|
||||
embedded.setShareUrl(url);
|
||||
|
||||
// the place for the embedded viewer toolbar, can be either top or bottom
|
||||
embedded.setToolbarDocked("top");
|
||||
}
|
||||
|
||||
public String getMode() {
|
||||
return mode;
|
||||
}
|
||||
|
||||
public void setMode(final String modeParam) {
|
||||
this.mode = modeParam;
|
||||
}
|
||||
|
||||
public void setCallbackUrl(final String callbackUrlParam) {
|
||||
this.callbackUrl = callbackUrlParam;
|
||||
}
|
||||
|
||||
public void setCoEditing(final HashMap<String, Object> coEditingParam) {
|
||||
this.coEditing = coEditingParam;
|
||||
}
|
||||
|
||||
public void setLang(final String langParam) {
|
||||
this.lang = langParam;
|
||||
}
|
||||
|
||||
public void setCreateUrl(final String createUrlParam) {
|
||||
this.createUrl = createUrlParam;
|
||||
}
|
||||
|
||||
public void setTemplates(final List<Map<String, String>> templatesParam) {
|
||||
this.templates = templatesParam;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(final User userParam) {
|
||||
this.user = userParam;
|
||||
}
|
||||
|
||||
public Customization getCustomization() {
|
||||
return customization;
|
||||
}
|
||||
|
||||
// default user parameters (id, name and group)
|
||||
public class User
|
||||
{
|
||||
public String id;
|
||||
public String name;
|
||||
public String group;
|
||||
public class User {
|
||||
private String id;
|
||||
private String name;
|
||||
private String group;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final String idParam) {
|
||||
this.id = idParam;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String nameParam) {
|
||||
this.name = nameParam;
|
||||
}
|
||||
|
||||
public String getGroup() {
|
||||
return group;
|
||||
}
|
||||
|
||||
public void setGroup(final String groupParam) {
|
||||
this.group = groupParam;
|
||||
}
|
||||
}
|
||||
|
||||
// customization parameters
|
||||
public class Customization
|
||||
{
|
||||
public Goback goback;
|
||||
public Boolean forcesave;
|
||||
public Boolean submitForm;
|
||||
public Boolean about;
|
||||
public Boolean comments;
|
||||
public Boolean feedback;
|
||||
public class Customization {
|
||||
private Goback goback;
|
||||
private Boolean forcesave;
|
||||
private Boolean submitForm;
|
||||
private Boolean about;
|
||||
private Boolean comments;
|
||||
private Boolean feedback;
|
||||
|
||||
public Customization()
|
||||
{
|
||||
public Goback getGoback() {
|
||||
return goback;
|
||||
}
|
||||
|
||||
public void setSubmitForm(final Boolean submitFormParam) {
|
||||
this.submitForm = submitFormParam;
|
||||
}
|
||||
|
||||
public Customization() {
|
||||
about = true;
|
||||
comments = true;
|
||||
feedback = true;
|
||||
@ -375,27 +545,52 @@ public class FileModel
|
||||
goback = new Goback();
|
||||
}
|
||||
|
||||
public class Goback
|
||||
{
|
||||
public String url;
|
||||
public class Goback {
|
||||
private String url;
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(final String urlParam) {
|
||||
this.url = urlParam;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parameters for embedded document
|
||||
public class Embedded
|
||||
{
|
||||
public String saveUrl;
|
||||
public String embedUrl;
|
||||
public String shareUrl;
|
||||
public String toolbarDocked;
|
||||
public class Embedded {
|
||||
private String saveUrl;
|
||||
private String embedUrl;
|
||||
private String shareUrl;
|
||||
private String toolbarDocked;
|
||||
|
||||
public void setSaveUrl(final String saveUrlParam) {
|
||||
this.saveUrl = saveUrlParam;
|
||||
}
|
||||
|
||||
public void setEmbedUrl(final String embedUrlParam) {
|
||||
this.embedUrl = embedUrlParam;
|
||||
}
|
||||
|
||||
public void setShareUrl(final String shareUrlParam) {
|
||||
this.shareUrl = shareUrlParam;
|
||||
}
|
||||
|
||||
public void setToolbarDocked(final String toolbarDockedParam) {
|
||||
this.toolbarDocked = toolbarDockedParam;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// turn java objects into json strings
|
||||
public static String Serialize(FileModel model)
|
||||
{
|
||||
public static String serialize(final FileModel model) {
|
||||
Gson gson = new Gson();
|
||||
return gson.toJson(model);
|
||||
}
|
||||
|
||||
public String getDocumentType() {
|
||||
return documentType;
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,9 +18,8 @@
|
||||
|
||||
package entities;
|
||||
|
||||
public enum FileType
|
||||
{
|
||||
public enum FileType {
|
||||
Word,
|
||||
Cell,
|
||||
Slide
|
||||
}
|
||||
}
|
||||
|
||||
@ -21,30 +21,77 @@ package entities;
|
||||
import java.util.List;
|
||||
|
||||
public class User {
|
||||
public String id;
|
||||
public String name;
|
||||
public String email;
|
||||
public String group;
|
||||
public List<String> reviewGroups;
|
||||
public CommentGroups commentGroups;
|
||||
public Boolean favorite;
|
||||
public List<String> deniedPermissions;
|
||||
public List<String> descriptions;
|
||||
public Boolean templates;
|
||||
public List<String> userInfoGroups;
|
||||
private final String id;
|
||||
private final String name;
|
||||
private final String email;
|
||||
private final String group;
|
||||
private final List<String> reviewGroups;
|
||||
private final CommentGroups commentGroups;
|
||||
private final Boolean favorite;
|
||||
private final List<String> deniedPermissions;
|
||||
private final List<String> descriptions;
|
||||
private final Boolean templates;
|
||||
private final List<String> userInfoGroups;
|
||||
|
||||
public User(String id, String name, String email, String group, List<String> reviewGroups, CommentGroups commentGroups, List<String> userInfoGroups,
|
||||
Boolean favorite, List<String> deniedPermissions, List<String> descriptions, Boolean templates) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
this.group = group;
|
||||
this.reviewGroups = reviewGroups;
|
||||
this.commentGroups = commentGroups;
|
||||
this.favorite = favorite;
|
||||
this.deniedPermissions = deniedPermissions;
|
||||
this.descriptions = descriptions;
|
||||
this.templates = templates;
|
||||
this.userInfoGroups = userInfoGroups;
|
||||
public User(final String idParam, final String nameParam, final String emailParam, final String groupParam,
|
||||
final List<String> reviewGroupsParam, final CommentGroups commentGroupsParam,
|
||||
final List<String> userInfoGroupsParam, final Boolean favoriteParam,
|
||||
final List<String> deniedPermissionsParam, final List<String> descriptionsParam,
|
||||
final Boolean templatesParam) {
|
||||
this.id = idParam;
|
||||
this.name = nameParam;
|
||||
this.email = emailParam;
|
||||
this.group = groupParam;
|
||||
this.reviewGroups = reviewGroupsParam;
|
||||
this.commentGroups = commentGroupsParam;
|
||||
this.favorite = favoriteParam;
|
||||
this.deniedPermissions = deniedPermissionsParam;
|
||||
this.descriptions = descriptionsParam;
|
||||
this.templates = templatesParam;
|
||||
this.userInfoGroups = userInfoGroupsParam;
|
||||
}
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public String getGroup() {
|
||||
return group;
|
||||
}
|
||||
|
||||
public List<String> getReviewGroups() {
|
||||
return reviewGroups;
|
||||
}
|
||||
|
||||
public CommentGroups getCommentGroups() {
|
||||
return commentGroups;
|
||||
}
|
||||
|
||||
public Boolean getFavorite() {
|
||||
return favorite;
|
||||
}
|
||||
|
||||
public List<String> getDeniedPermissions() {
|
||||
return deniedPermissions;
|
||||
}
|
||||
|
||||
public List<String> getDescriptions() {
|
||||
return descriptions;
|
||||
}
|
||||
|
||||
public Boolean getTemplates() {
|
||||
return templates;
|
||||
}
|
||||
|
||||
public List<String> getUserInfoGroups() {
|
||||
return userInfoGroups;
|
||||
}
|
||||
}
|
||||
|
||||
@ -21,35 +21,30 @@ package helpers;
|
||||
import java.io.InputStream;
|
||||
import java.util.Properties;
|
||||
|
||||
public class ConfigManager
|
||||
{
|
||||
public final class ConfigManager {
|
||||
private static Properties properties;
|
||||
|
||||
static
|
||||
{
|
||||
Init();
|
||||
private ConfigManager() { }
|
||||
|
||||
static {
|
||||
init();
|
||||
}
|
||||
|
||||
private static void Init()
|
||||
{
|
||||
try
|
||||
{
|
||||
private static void init() {
|
||||
try {
|
||||
// get stream from the settings.properties resource and load it
|
||||
properties = new Properties();
|
||||
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("settings.properties");
|
||||
InputStream stream = Thread.currentThread().getContextClassLoader()
|
||||
.getResourceAsStream("settings.properties");
|
||||
properties.load(stream);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
} catch (Exception ex) {
|
||||
properties = null;
|
||||
}
|
||||
}
|
||||
|
||||
// get name from the settings.properties file
|
||||
public static String GetProperty(String name)
|
||||
{
|
||||
if (properties == null)
|
||||
{
|
||||
public static String getProperty(final String name) {
|
||||
if (properties == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@ -58,4 +53,4 @@ public class ConfigManager
|
||||
|
||||
return property == null ? "" : property;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -28,19 +28,21 @@ import javax.servlet.http.HttpServletRequest;
|
||||
public class CookieManager {
|
||||
private HashMap<String, String> cookiesMap;
|
||||
|
||||
public CookieManager(HttpServletRequest request) throws UnsupportedEncodingException {
|
||||
public CookieManager(final HttpServletRequest request) throws UnsupportedEncodingException {
|
||||
cookiesMap = new HashMap<String, String>();
|
||||
|
||||
Cookie[] cookies = request.getCookies(); // get all the cookies from the request
|
||||
if (cookies != null) {
|
||||
for (Cookie cookie : cookies) { // run through all the cookies
|
||||
cookiesMap.putIfAbsent(cookie.getName(), URLDecoder.decode(cookie.getValue(), "UTF-8")); // add cookie to the cookies map if its name isn't in the map yet
|
||||
|
||||
// add cookie to the cookies map if its name isn't in the map yet
|
||||
cookiesMap.putIfAbsent(cookie.getName(), URLDecoder.decode(cookie.getValue(), "UTF-8"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// get cookie by its name
|
||||
public String getCookie(String name) {
|
||||
public String getCookie(final String name) {
|
||||
return cookiesMap.get(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,7 +18,24 @@
|
||||
|
||||
package helpers;
|
||||
|
||||
import java.io.*;
|
||||
import entities.FileType;
|
||||
import entities.User;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.primeframework.jwt.Signer;
|
||||
import org.primeframework.jwt.Verifier;
|
||||
import org.primeframework.jwt.domain.JWT;
|
||||
import org.primeframework.jwt.hmac.HMACSigner;
|
||||
import org.primeframework.jwt.hmac.HMACVerifier;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.FileFilter;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.net.InetAddress;
|
||||
@ -27,109 +44,93 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import entities.FileType;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import entities.User;
|
||||
import org.primeframework.jwt.domain.JWT;
|
||||
import org.primeframework.jwt.hmac.HMACSigner;
|
||||
import org.primeframework.jwt.hmac.HMACVerifier;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.primeframework.jwt.Signer;
|
||||
import org.primeframework.jwt.Verifier;
|
||||
import static utils.Constants.KILOBYTE_SIZE;
|
||||
import static utils.Constants.MAX_FILE_SIZE;
|
||||
|
||||
public class DocumentManager
|
||||
{
|
||||
public final class DocumentManager {
|
||||
private static HttpServletRequest request;
|
||||
|
||||
public static void Init(HttpServletRequest req, HttpServletResponse resp)
|
||||
{
|
||||
private DocumentManager() { }
|
||||
|
||||
public static void init(final HttpServletRequest req, final HttpServletResponse resp) {
|
||||
request = req;
|
||||
}
|
||||
|
||||
// get max file size
|
||||
public static long GetMaxFileSize()
|
||||
{
|
||||
public static long getMaxFileSize() {
|
||||
long size;
|
||||
|
||||
try
|
||||
{
|
||||
size = Long.parseLong(ConfigManager.GetProperty("filesize-max"));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try {
|
||||
size = Long.parseLong(ConfigManager.getProperty("filesize-max"));
|
||||
} catch (Exception ex) {
|
||||
size = 0;
|
||||
}
|
||||
|
||||
return size > 0 ? size : 5 * 1024 * 1024;
|
||||
return size > 0 ? size : MAX_FILE_SIZE;
|
||||
}
|
||||
|
||||
// get all the supported file extensions
|
||||
public static List<String> GetFileExts()
|
||||
{
|
||||
public static List<String> getFileExts() {
|
||||
List<String> res = new ArrayList<>();
|
||||
|
||||
res.addAll(GetViewedExts());
|
||||
res.addAll(GetEditedExts());
|
||||
res.addAll(GetConvertExts());
|
||||
res.addAll(GetFillExts());
|
||||
res.addAll(getViewedExts());
|
||||
res.addAll(getEditedExts());
|
||||
res.addAll(getConvertExts());
|
||||
res.addAll(getFillExts());
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
public static List<String> GetFillExts() {
|
||||
String exts = ConfigManager.GetProperty("files.docservice.fill-docs");
|
||||
public static List<String> getFillExts() {
|
||||
String exts = ConfigManager.getProperty("files.docservice.fill-docs");
|
||||
return Arrays.asList(exts.split("\\|"));
|
||||
}
|
||||
|
||||
// get file extensions that can be viewed
|
||||
public static List<String> GetViewedExts()
|
||||
{
|
||||
String exts = ConfigManager.GetProperty("files.docservice.viewed-docs");
|
||||
public static List<String> getViewedExts() {
|
||||
String exts = ConfigManager.getProperty("files.docservice.viewed-docs");
|
||||
return Arrays.asList(exts.split("\\|"));
|
||||
}
|
||||
|
||||
// get file extensions that can be edited
|
||||
public static List<String> GetEditedExts()
|
||||
{
|
||||
String exts = ConfigManager.GetProperty("files.docservice.edited-docs");
|
||||
public static List<String> getEditedExts() {
|
||||
String exts = ConfigManager.getProperty("files.docservice.edited-docs");
|
||||
return Arrays.asList(exts.split("\\|"));
|
||||
}
|
||||
|
||||
// get file extensions that can be converted
|
||||
public static List<String> GetConvertExts()
|
||||
{
|
||||
String exts = ConfigManager.GetProperty("files.docservice.convert-docs");
|
||||
public static List<String> getConvertExts() {
|
||||
String exts = ConfigManager.getProperty("files.docservice.convert-docs");
|
||||
return Arrays.asList(exts.split("\\|"));
|
||||
}
|
||||
|
||||
// get current user host address
|
||||
public static String CurUserHostAddress(String userAddress)
|
||||
{
|
||||
if(userAddress == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
public static String curUserHostAddress(final String userAddress) {
|
||||
String userAddr = userAddress;
|
||||
if (userAddr == null) {
|
||||
try {
|
||||
// use InetAddress class to get the user address if it wasn't passed to the function
|
||||
userAddress = InetAddress.getLocalHost().getHostAddress();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
userAddress = "";
|
||||
userAddr = InetAddress.getLocalHost().getHostAddress();
|
||||
} catch (Exception ex) {
|
||||
userAddr = "";
|
||||
}
|
||||
}
|
||||
|
||||
return userAddress.replaceAll("[^0-9a-zA-Z.=]", "_");
|
||||
return userAddr.replaceAll("[^0-9a-zA-Z.=]", "_");
|
||||
}
|
||||
|
||||
// get the root directory of the user host
|
||||
public static String FilesRootPath(String userAddress)
|
||||
{
|
||||
String hostAddress = CurUserHostAddress(userAddress); // get current user host address
|
||||
public static String filesRootPath(final String userAddress) {
|
||||
String hostAddress = curUserHostAddress(userAddress); // get current user host address
|
||||
String serverPath = request.getSession().getServletContext().getRealPath(""); // get the server url
|
||||
String storagePath = ConfigManager.GetProperty("storage-folder"); // get the storage directory
|
||||
String storagePath = ConfigManager.getProperty("storage-folder"); // get the storage directory
|
||||
File f = new File(storagePath);
|
||||
|
||||
if (f.isAbsolute()) {
|
||||
@ -143,13 +144,13 @@ public class DocumentManager
|
||||
throw new SecurityException("The path to the file is specified instead of the folder");
|
||||
}
|
||||
}
|
||||
String directory = !f.isAbsolute() ? serverPath + storagePath + File.separator + hostAddress + File.separator : storagePath + File.separator;
|
||||
String directory = !f.isAbsolute() ? serverPath + storagePath
|
||||
+ File.separator + hostAddress + File.separator : storagePath + File.separator;
|
||||
|
||||
File file = new File(directory);
|
||||
|
||||
// if the root directory doesn't exist
|
||||
if (!file.exists())
|
||||
{
|
||||
if (!file.exists()) {
|
||||
// create it
|
||||
file.mkdirs();
|
||||
}
|
||||
@ -158,21 +159,20 @@ public class DocumentManager
|
||||
}
|
||||
|
||||
// get the storage path of the file
|
||||
public static String StoragePath(String fileName, String userAddress)
|
||||
{
|
||||
String directory = FilesRootPath(userAddress);
|
||||
return directory + FileUtility.GetFileName(fileName);
|
||||
public static String storagePath(final String fileName, final String userAddress) {
|
||||
String directory = filesRootPath(userAddress);
|
||||
return directory + FileUtility.getFileName(fileName);
|
||||
}
|
||||
|
||||
// get the path to history file
|
||||
public static String HistoryPath(String fileName, String userAddress, String version, String file)
|
||||
{
|
||||
String hostAddress = CurUserHostAddress(userAddress);
|
||||
public static String historyPath(final String fileName, final String userAddress, final String version,
|
||||
final String file) {
|
||||
String hostAddress = curUserHostAddress(userAddress);
|
||||
String serverPath = request.getSession().getServletContext().getRealPath("");
|
||||
String storagePath = ConfigManager.GetProperty("storage-folder");
|
||||
String storagePath = ConfigManager.getProperty("storage-folder");
|
||||
String directory = serverPath + storagePath + File.separator + hostAddress + File.separator;
|
||||
if (new File(storagePath).isAbsolute()) {
|
||||
directory = FilesRootPath(userAddress);
|
||||
directory = filesRootPath(userAddress);
|
||||
}
|
||||
|
||||
directory = directory + fileName + "-hist" + File.separator + version + File.separator + file;
|
||||
@ -181,22 +181,25 @@ public class DocumentManager
|
||||
}
|
||||
|
||||
// get the path to the forcesaved file version
|
||||
public static String ForcesavePath(String fileName, String userAddress, Boolean create)
|
||||
{
|
||||
String hostAddress = CurUserHostAddress(userAddress);
|
||||
public static String forcesavePath(final String fileName, final String userAddress, final Boolean create) {
|
||||
String hostAddress = curUserHostAddress(userAddress);
|
||||
String serverPath = request.getSession().getServletContext().getRealPath("");
|
||||
String storagePath = ConfigManager.GetProperty("storage-folder");
|
||||
String storagePath = ConfigManager.getProperty("storage-folder");
|
||||
|
||||
// create the directory to this file version
|
||||
String directory = serverPath + storagePath + File.separator + hostAddress + File.separator;
|
||||
|
||||
File file = new File(directory);
|
||||
if (!file.exists()) return "";
|
||||
if (!file.exists()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// create the directory to the history of this file version
|
||||
directory = directory + fileName + "-hist" + File.separator;
|
||||
file = new File(directory);
|
||||
if (!create && !file.exists()) return "";
|
||||
if (!create && !file.exists()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
file.mkdirs();
|
||||
|
||||
@ -210,33 +213,31 @@ public class DocumentManager
|
||||
}
|
||||
|
||||
// get the history directory
|
||||
public static String HistoryDir(String storagePath)
|
||||
{
|
||||
return storagePath += "-hist";
|
||||
public static String historyDir(final String storagePath) {
|
||||
return storagePath + "-hist";
|
||||
}
|
||||
|
||||
// get the path to the file version by the history path and file version
|
||||
public static String VersionDir(String histPath, Integer version)
|
||||
{
|
||||
public static String versionDir(final String histPath, final Integer version) {
|
||||
return histPath + File.separator + Integer.toString(version);
|
||||
}
|
||||
|
||||
// get the path to the file version by the file name, user address and file version
|
||||
public static String VersionDir(String fileName, String userAddress, Integer version)
|
||||
{
|
||||
return VersionDir(HistoryDir(StoragePath(fileName, userAddress)), version);
|
||||
public static String versionDir(final String fileName, final String userAddress, final Integer version) {
|
||||
return versionDir(historyDir(storagePath(fileName, userAddress)), version);
|
||||
}
|
||||
|
||||
// get the file version by the history path
|
||||
public static Integer GetFileVersion(String historyPath)
|
||||
{
|
||||
public static Integer getFileVersion(final String historyPath) {
|
||||
File dir = new File(historyPath);
|
||||
|
||||
if (!dir.exists()) return 1; // if the history path doesn't exist, then the file version is 1
|
||||
if (!dir.exists()) {
|
||||
return 1; // if the history path doesn't exist, then the file version is 1
|
||||
}
|
||||
|
||||
File[] dirs = dir.listFiles(new FileFilter() { // take only directories from the history folder
|
||||
@Override
|
||||
public boolean accept(File pathname) {
|
||||
public boolean accept(final File pathname) {
|
||||
return pathname.isDirectory();
|
||||
}
|
||||
});
|
||||
@ -245,33 +246,30 @@ public class DocumentManager
|
||||
}
|
||||
|
||||
// get the file version by the file name and user address
|
||||
public static int GetFileVersion(String fileName, String userAddress)
|
||||
{
|
||||
return GetFileVersion(HistoryDir(StoragePath(fileName, userAddress)));
|
||||
public static int getFileVersion(final String fileName, final String userAddress) {
|
||||
return getFileVersion(historyDir(storagePath(fileName, userAddress)));
|
||||
}
|
||||
|
||||
// get a file name with an index if the file with such a name already exists
|
||||
public static String GetCorrectName(String fileName, String userAddress)
|
||||
{
|
||||
String baseName = FileUtility.GetFileNameWithoutExtension(fileName);
|
||||
String ext = FileUtility.GetFileExtension(fileName);
|
||||
public static String getCorrectName(final String fileName, final String userAddress) {
|
||||
String baseName = FileUtility.getFileNameWithoutExtension(fileName);
|
||||
String ext = FileUtility.getFileExtension(fileName);
|
||||
String name = baseName + ext;
|
||||
|
||||
File file = new File(StoragePath(name, userAddress));
|
||||
File file = new File(storagePath(name, userAddress));
|
||||
|
||||
for (int i = 1; file.exists(); i++) // run through all the files with such a name in the storage directory
|
||||
{
|
||||
for (int i = 1; file.exists(); i++) { // run through all the files with such a name in the storage directory
|
||||
name = baseName + " (" + i + ")" + ext; // and add an index to the base name
|
||||
file = new File(StoragePath(name, userAddress));
|
||||
file = new File(storagePath(name, userAddress));
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
// create meta information
|
||||
public static void CreateMeta(String fileName, String uid, String uname, String userAddress) throws Exception
|
||||
{
|
||||
String histDir = HistoryDir(StoragePath(fileName, userAddress));
|
||||
public static void createMeta(final String fileName, final String uid, final String uname,
|
||||
final String userAddress) throws Exception {
|
||||
String histDir = historyDir(storagePath(fileName, userAddress));
|
||||
|
||||
File dir = new File(histDir); // create history directory
|
||||
dir.mkdir();
|
||||
@ -290,48 +288,52 @@ public class DocumentManager
|
||||
}
|
||||
|
||||
// get all the stored files from the user host address
|
||||
public static File[] GetStoredFiles(String userAddress)
|
||||
{
|
||||
String directory = FilesRootPath(userAddress);
|
||||
public static File[] getStoredFiles(final String userAddress) {
|
||||
String directory = filesRootPath(userAddress);
|
||||
|
||||
File file = new File(directory);
|
||||
return file.listFiles(new FileFilter() { // take only files from the root directory
|
||||
@Override
|
||||
public boolean accept(File pathname) {
|
||||
public boolean accept(final File pathname) {
|
||||
return pathname.isFile();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// create demo document
|
||||
public static String CreateDemo(String fileExt, Boolean sample, User user) throws Exception
|
||||
{
|
||||
String demoName = (sample ? "sample." : "new.") + fileExt; // create sample or new template file with the necessary extension
|
||||
String demoPath = "assets" + File.separator + (sample ? "sample" : "new") + File.separator; // get the path to the sample document
|
||||
String fileName = GetCorrectName(demoName, null); // get a file name with an index if the file with such a name already exists
|
||||
public static String createDemo(final String fileExt, final Boolean sample, final User user) throws Exception {
|
||||
// create sample or new template file with the necessary extension
|
||||
String demoName = (sample ? "sample." : "new.") + fileExt;
|
||||
|
||||
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(demoPath + demoName); // get the input file stream
|
||||
// get the path to the sample document
|
||||
String demoPath = "assets" + File.separator + (sample ? "sample" : "new") + File.separator;
|
||||
|
||||
CreateFile(Paths.get(StoragePath(fileName, null)), stream);
|
||||
// get a file name with an index if the file with such a name already exists
|
||||
String fileName = getCorrectName(demoName, null);
|
||||
|
||||
// get the input file stream
|
||||
InputStream stream = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResourceAsStream(demoPath + demoName);
|
||||
|
||||
createFile(Paths.get(storagePath(fileName, null)), stream);
|
||||
|
||||
// create meta information of the demo file
|
||||
CreateMeta(fileName, user.id, user.name, null);
|
||||
createMeta(fileName, user.getId(), user.getName(), null);
|
||||
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public static boolean CreateFile(Path path, InputStream stream) {
|
||||
if (Files.exists(path)){
|
||||
public static boolean createFile(final Path path, final InputStream stream) {
|
||||
if (Files.exists(path)) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
File file = Files.createFile(path).toFile();
|
||||
try (FileOutputStream out = new FileOutputStream(file))
|
||||
{
|
||||
try (FileOutputStream out = new FileOutputStream(file)) {
|
||||
int read;
|
||||
final byte[] bytes = new byte[1024];
|
||||
while ((read = stream.read(bytes)) != -1)
|
||||
{
|
||||
final byte[] bytes = new byte[KILOBYTE_SIZE];
|
||||
while ((read = stream.read(bytes)) != -1) {
|
||||
out.write(bytes, 0, read);
|
||||
}
|
||||
out.flush();
|
||||
@ -343,41 +345,42 @@ public class DocumentManager
|
||||
}
|
||||
|
||||
// get file url
|
||||
public static String GetFileUri(String fileName, Boolean forDocumentServer)
|
||||
{
|
||||
try
|
||||
{
|
||||
String serverPath = GetServerUrl(forDocumentServer);
|
||||
String storagePath = ConfigManager.GetProperty("storage-folder");
|
||||
public static String getFileUri(final String fileName, final Boolean forDocumentServer) {
|
||||
try {
|
||||
String serverPath = getServerUrl(forDocumentServer);
|
||||
String storagePath = ConfigManager.getProperty("storage-folder");
|
||||
File f = new File(storagePath);
|
||||
String hostAddress = CurUserHostAddress(null);
|
||||
String hostAddress = curUserHostAddress(null);
|
||||
|
||||
String filePath = serverPath + "/" + storagePath + "/" + hostAddress + "/" + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString()).replace("+", "%20");
|
||||
String filePath = serverPath + "/" + storagePath + "/" + hostAddress + "/"
|
||||
+ URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString())
|
||||
.replace("+", "%20");
|
||||
if (f.isAbsolute() && f.isFile()) {
|
||||
filePath = GetDownloadUrl(fileName, true);
|
||||
filePath = getDownloadUrl(fileName, true);
|
||||
if (!Files.isWritable(f.toPath())) {
|
||||
throw new SecurityException("No write permission to path: " + f.toPath());
|
||||
}
|
||||
}
|
||||
|
||||
return filePath;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// get file information
|
||||
public static ArrayList<Map<String, Object>> GetFilesInfo(){
|
||||
public static ArrayList<Map<String, Object>> getFilesInfo() {
|
||||
ArrayList<Map<String, Object>> files = new ArrayList<>();
|
||||
|
||||
// run through all the stored files
|
||||
for(File file : GetStoredFiles(null)){
|
||||
for (File file : getStoredFiles(null)) {
|
||||
Map<String, Object> map = new LinkedHashMap<>(); // write all the parameters to the map
|
||||
map.put("version", GetFileVersion(file.getName(), null));
|
||||
map.put("id", ServiceConverter.GenerateRevisionId(CurUserHostAddress(null) + "/" + file.getName() + "/" + Long.toString(new File(StoragePath(file.getName(), null)).lastModified())));
|
||||
map.put("contentLength", new BigDecimal(String.valueOf((file.length()/1024.0))).setScale(2, RoundingMode.HALF_UP) + " KB");
|
||||
map.put("version", getFileVersion(file.getName(), null));
|
||||
map.put("id", ServiceConverter
|
||||
.generateRevisionId(curUserHostAddress(null) + "/" + file.getName() + "/"
|
||||
+ Long.toString(new File(storagePath(file.getName(), null)).lastModified())));
|
||||
map.put("contentLength", new BigDecimal(String.valueOf((file.length() / Double.valueOf(KILOBYTE_SIZE))))
|
||||
.setScale(2, RoundingMode.HALF_UP) + " KB");
|
||||
map.put("pureContentLength", file.length());
|
||||
map.put("title", file.getName());
|
||||
map.put("updated", String.valueOf(new Date(file.lastModified())));
|
||||
@ -388,11 +391,11 @@ public class DocumentManager
|
||||
}
|
||||
|
||||
// get file information by its id
|
||||
public static ArrayList<Map<String, Object>> GetFilesInfo(String fileId){
|
||||
public static ArrayList<Map<String, Object>> getFilesInfo(final String fileId) {
|
||||
ArrayList<Map<String, Object>> file = new ArrayList<>();
|
||||
|
||||
for (Map<String, Object> map : GetFilesInfo()){
|
||||
if (map.get("id").equals(fileId)){
|
||||
for (Map<String, Object> map : getFilesInfo()) {
|
||||
if (map.get("id").equals(fileId)) {
|
||||
file.add(map);
|
||||
break;
|
||||
}
|
||||
@ -402,179 +405,174 @@ public class DocumentManager
|
||||
}
|
||||
|
||||
// get the path url
|
||||
public static String GetPathUri(String path)
|
||||
{
|
||||
String serverPath = GetServerUrl(true);
|
||||
String storagePath = ConfigManager.GetProperty("storage-folder");
|
||||
String hostAddress = CurUserHostAddress(null);
|
||||
public static String getPathUri(final String path) {
|
||||
String serverPath = getServerUrl(true);
|
||||
String storagePath = ConfigManager.getProperty("storage-folder");
|
||||
String hostAddress = curUserHostAddress(null);
|
||||
|
||||
String filePath = serverPath + "/" + storagePath + "/" + hostAddress + "/" + path.replace(File.separator, "/").substring(FilesRootPath(null).length()).replace(" ", "%20");
|
||||
String filePath = serverPath + "/" + storagePath + "/" + hostAddress + "/"
|
||||
+ path.replace(File.separator, "/").substring(filesRootPath(null).length())
|
||||
.replace(" ", "%20");
|
||||
|
||||
return filePath;
|
||||
}
|
||||
|
||||
|
||||
// get the server url
|
||||
public static String GetServerUrl(Boolean forDocumentServer) {
|
||||
if (forDocumentServer && !ConfigManager.GetProperty("files.docservice.url.example").equals("")) {
|
||||
return ConfigManager.GetProperty("files.docservice.url.example");
|
||||
public static String getServerUrl(final Boolean forDocumentServer) {
|
||||
if (forDocumentServer && !ConfigManager.getProperty("files.docservice.url.example").equals("")) {
|
||||
return ConfigManager.getProperty("files.docservice.url.example");
|
||||
} else {
|
||||
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
|
||||
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
|
||||
+ request.getContextPath();
|
||||
}
|
||||
}
|
||||
|
||||
// get the callback url
|
||||
public static String GetCallback(String fileName)
|
||||
{
|
||||
String serverPath = GetServerUrl(true);
|
||||
String hostAddress = CurUserHostAddress(null);
|
||||
try
|
||||
{
|
||||
String query = "?type=track&fileName=" + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString()) + "&userAddress=" + URLEncoder.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString());
|
||||
public static String getCallback(final String fileName) {
|
||||
String serverPath = getServerUrl(true);
|
||||
String hostAddress = curUserHostAddress(null);
|
||||
try {
|
||||
String query = "?type=track&fileName="
|
||||
+ URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString())
|
||||
+ "&userAddress=" + URLEncoder
|
||||
.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString());
|
||||
|
||||
return serverPath + "/IndexServlet" + query;
|
||||
}
|
||||
catch (UnsupportedEncodingException e)
|
||||
{
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// get url to the created file
|
||||
public static String GetCreateUrl (FileType fileType) {
|
||||
String serverPath = GetServerUrl(false);
|
||||
String fileExt = GetInternalExtension(fileType).replace(".", "");
|
||||
public static String getCreateUrl(final FileType fileType) {
|
||||
String serverPath = getServerUrl(false);
|
||||
String fileExt = getInternalExtension(fileType).replace(".", "");
|
||||
String query = "?fileExt=" + fileExt;
|
||||
|
||||
return serverPath + "/EditorServlet" + query;
|
||||
}
|
||||
|
||||
// get url to download a file
|
||||
public static String GetDownloadUrl(String fileName, Boolean forDocumentServer) {
|
||||
String serverPath = GetServerUrl(forDocumentServer);
|
||||
String hostAddress = CurUserHostAddress(null);
|
||||
try
|
||||
{
|
||||
String userAddress = forDocumentServer ? "&userAddress=" + URLEncoder.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString()) : "";
|
||||
String query = "?type=download&fileName=" + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString()) + userAddress;
|
||||
public static String getDownloadUrl(final String fileName, final Boolean forDocumentServer) {
|
||||
String serverPath = getServerUrl(forDocumentServer);
|
||||
String hostAddress = curUserHostAddress(null);
|
||||
try {
|
||||
String userAddress = forDocumentServer ? "&userAddress=" + URLEncoder
|
||||
.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString()) : "";
|
||||
String query = "?type=download&fileName=" + URLEncoder
|
||||
.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString()) + userAddress;
|
||||
|
||||
return serverPath + "/IndexServlet" + query;
|
||||
}
|
||||
catch (UnsupportedEncodingException e)
|
||||
{
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// get url to download a file to History prev.*
|
||||
public static String GetDownloadHistoryUrl(String fileName, Integer version, String file, Boolean forDocumentServer) {
|
||||
String serverPath = GetServerUrl(forDocumentServer);
|
||||
String hostAddress = CurUserHostAddress(null);
|
||||
try
|
||||
{
|
||||
String userAddress = forDocumentServer ? "&userAddress=" + URLEncoder.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString()) : "";
|
||||
String query = "?type=downloadhistory&fileName=" + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString()) + userAddress;
|
||||
query = query + "&ver=" + version + "&file=" + URLEncoder.encode(file, java.nio.charset.StandardCharsets.UTF_8.toString());
|
||||
public static String getDownloadHistoryUrl(final String fileName, final Integer version, final String file,
|
||||
final Boolean forDocumentServer) {
|
||||
String serverPath = getServerUrl(forDocumentServer);
|
||||
String hostAddress = curUserHostAddress(null);
|
||||
try {
|
||||
String userAddress = forDocumentServer ? "&userAddress=" + URLEncoder
|
||||
.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString()) : "";
|
||||
String query = "?type=downloadhistory&fileName=" + URLEncoder
|
||||
.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString()) + userAddress;
|
||||
query = query + "&ver=" + version + "&file=" + URLEncoder.
|
||||
encode(file, java.nio.charset.StandardCharsets.UTF_8.toString());
|
||||
|
||||
return serverPath + "/IndexServlet" + query;
|
||||
}
|
||||
catch (UnsupportedEncodingException e)
|
||||
{
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// get an editor internal extension
|
||||
public static String GetInternalExtension(FileType fileType)
|
||||
{
|
||||
public static String getInternalExtension(final FileType fileType) {
|
||||
// .docx for word file type
|
||||
if (fileType.equals(FileType.Word))
|
||||
if (fileType.equals(FileType.Word)) {
|
||||
return ".docx";
|
||||
}
|
||||
|
||||
// .xlsx for cell file type
|
||||
if (fileType.equals(FileType.Cell))
|
||||
if (fileType.equals(FileType.Cell)) {
|
||||
return ".xlsx";
|
||||
}
|
||||
|
||||
// .pptx for slide file type
|
||||
if (fileType.equals(FileType.Slide))
|
||||
if (fileType.equals(FileType.Slide)) {
|
||||
return ".pptx";
|
||||
}
|
||||
|
||||
// the default file type is .docx
|
||||
return ".docx";
|
||||
}
|
||||
|
||||
// get image url for templates
|
||||
public static String GetTemplateImageUrl(FileType fileType)
|
||||
{
|
||||
String path = GetServerUrl(true) + "/css/img/";
|
||||
public static String getTemplateImageUrl(final FileType fileType) {
|
||||
String path = getServerUrl(true) + "/css/img/";
|
||||
// for word file type
|
||||
if (fileType.equals(FileType.Word))
|
||||
if (fileType.equals(FileType.Word)) {
|
||||
return path + "file_docx.svg";
|
||||
}
|
||||
|
||||
// .xlsx for cell file type
|
||||
if (fileType.equals(FileType.Cell))
|
||||
if (fileType.equals(FileType.Cell)) {
|
||||
return path + "file_xlsx.svg";
|
||||
}
|
||||
|
||||
// .pptx for slide file type
|
||||
if (fileType.equals(FileType.Slide))
|
||||
if (fileType.equals(FileType.Slide)) {
|
||||
return path + "file_pptx.svg";
|
||||
}
|
||||
|
||||
// the default file type
|
||||
return path + "file_docx.svg";
|
||||
}
|
||||
|
||||
// create document token
|
||||
public static String CreateToken(Map<String, Object> payloadClaims)
|
||||
{
|
||||
try
|
||||
{
|
||||
public static String createToken(final Map<String, Object> payloadClaims) {
|
||||
try {
|
||||
// build a HMAC signer using a SHA-256 hash
|
||||
Signer signer = HMACSigner.newSHA256Signer(GetTokenSecret());
|
||||
Signer signer = HMACSigner.newSHA256Signer(getTokenSecret());
|
||||
JWT jwt = new JWT();
|
||||
for (String key : payloadClaims.keySet()) // run through all the keys from the payload
|
||||
{
|
||||
for (String key : payloadClaims.keySet()) { // run through all the keys from the payload
|
||||
jwt.addClaim(key, payloadClaims.get(key)); // and write each claim to the jwt
|
||||
}
|
||||
return JWT.getEncoder().encode(jwt, signer); // sign and encode the JWT to a JSON string representation
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// read document token
|
||||
public static JWT ReadToken(String token)
|
||||
{
|
||||
try
|
||||
{
|
||||
public static JWT readToken(final String token) {
|
||||
try {
|
||||
// build a HMAC verifier using the token secret
|
||||
Verifier verifier = HMACVerifier.newVerifier(GetTokenSecret());
|
||||
return JWT.getDecoder().decode(token, verifier); // verify and decode the encoded string JWT to a rich object
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Verifier verifier = HMACVerifier.newVerifier(getTokenSecret());
|
||||
|
||||
// verify and decode the encoded string JWT to a rich object
|
||||
return JWT.getDecoder().decode(token, verifier);
|
||||
} catch (Exception exception) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// check if the token is enabled
|
||||
public static Boolean TokenEnabled()
|
||||
{
|
||||
String secret = GetTokenSecret();
|
||||
public static Boolean tokenEnabled() {
|
||||
String secret = getTokenSecret();
|
||||
return secret != null && !secret.isEmpty();
|
||||
}
|
||||
|
||||
// get token secret from the config parameters
|
||||
public static String GetTokenSecret()
|
||||
{
|
||||
return ConfigManager.GetProperty("files.docservice.secret");
|
||||
public static String getTokenSecret() {
|
||||
return ConfigManager.getProperty("files.docservice.secret");
|
||||
}
|
||||
|
||||
// get languages
|
||||
public static Map<String, String> GetLanguages()
|
||||
{
|
||||
String langs = ConfigManager.GetProperty("files.docservice.languages");
|
||||
public static Map<String, String> getLanguages() {
|
||||
String langs = ConfigManager.getProperty("files.docservice.languages");
|
||||
List<String> langsAndKeys = Arrays.asList(langs.split("\\|"));
|
||||
|
||||
Map<String, String> languages = new LinkedHashMap<>();
|
||||
@ -585,4 +583,4 @@ public class DocumentManager
|
||||
});
|
||||
return languages;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -25,63 +25,63 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class FileUtility
|
||||
{
|
||||
static {}
|
||||
public final class FileUtility {
|
||||
|
||||
private FileUtility() { }
|
||||
|
||||
// get file type
|
||||
public static FileType GetFileType(String fileName)
|
||||
{
|
||||
String ext = GetFileExtension(fileName).toLowerCase();
|
||||
public static FileType getFileType(final String fileName) {
|
||||
String ext = getFileExtension(fileName).toLowerCase();
|
||||
|
||||
// word type for document extensions
|
||||
if (ExtsDocument.contains(ext))
|
||||
if (extsDocument.contains(ext)) {
|
||||
return FileType.Word;
|
||||
}
|
||||
|
||||
// cell type for spreadsheet extensions
|
||||
if (ExtsSpreadsheet.contains(ext))
|
||||
if (extsSpreadsheet.contains(ext)) {
|
||||
return FileType.Cell;
|
||||
}
|
||||
|
||||
// slide type for presentation extensions
|
||||
if (ExtsPresentation.contains(ext))
|
||||
if (extsPresentation.contains(ext)) {
|
||||
return FileType.Slide;
|
||||
}
|
||||
|
||||
// default file type is word
|
||||
return FileType.Word;
|
||||
}
|
||||
|
||||
// document extensions
|
||||
public static List<String> ExtsDocument = Arrays.asList
|
||||
(
|
||||
".doc", ".docx", ".docm",
|
||||
".dot", ".dotx", ".dotm",
|
||||
".odt", ".fodt", ".ott", ".rtf", ".txt",
|
||||
".html", ".htm", ".mht", ".xml",
|
||||
".pdf", ".djvu", ".fb2", ".epub", ".xps", ".oxps", ".oform"
|
||||
);
|
||||
private static List<String> extsDocument = Arrays.asList(
|
||||
".doc", ".docx", ".docm",
|
||||
".dot", ".dotx", ".dotm",
|
||||
".odt", ".fodt", ".ott", ".rtf", ".txt",
|
||||
".html", ".htm", ".mht", ".xml",
|
||||
".pdf", ".djvu", ".fb2", ".epub", ".xps", ".oxps", ".oform"
|
||||
);
|
||||
|
||||
// spreadsheet extensions
|
||||
public static List<String> ExtsSpreadsheet = Arrays.asList
|
||||
(
|
||||
".xls", ".xlsx", ".xlsm", ".xlsb",
|
||||
".xlt", ".xltx", ".xltm",
|
||||
".ods", ".fods", ".ots", ".csv"
|
||||
);
|
||||
private static List<String> extsSpreadsheet = Arrays.asList(
|
||||
".xls", ".xlsx", ".xlsm", ".xlsb",
|
||||
".xlt", ".xltx", ".xltm",
|
||||
".ods", ".fods", ".ots", ".csv"
|
||||
);
|
||||
|
||||
// presentation extensions
|
||||
public static List<String> ExtsPresentation = Arrays.asList
|
||||
(
|
||||
".pps", ".ppsx", ".ppsm",
|
||||
".ppt", ".pptx", ".pptm",
|
||||
".pot", ".potx", ".potm",
|
||||
".odp", ".fodp", ".otp"
|
||||
);
|
||||
private static List<String> extsPresentation = Arrays.asList(
|
||||
".pps", ".ppsx", ".ppsm",
|
||||
".ppt", ".pptx", ".pptm",
|
||||
".pot", ".potx", ".potm",
|
||||
".odp", ".fodp", ".otp"
|
||||
);
|
||||
|
||||
|
||||
// get file name from the url
|
||||
public static String GetFileName(String url)
|
||||
{
|
||||
if (url == null) return "";
|
||||
public static String getFileName(final String url) {
|
||||
if (url == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// get file name from the last part of url
|
||||
String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
|
||||
@ -90,41 +90,39 @@ public class FileUtility
|
||||
}
|
||||
|
||||
// get file name without extension
|
||||
public static String GetFileNameWithoutExtension(String url)
|
||||
{
|
||||
String fileName = GetFileName(url);
|
||||
if (fileName == null) return null;
|
||||
public static String getFileNameWithoutExtension(final String url) {
|
||||
String fileName = getFileName(url);
|
||||
if (fileName == null) {
|
||||
return null;
|
||||
}
|
||||
String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
|
||||
return fileNameWithoutExt;
|
||||
}
|
||||
|
||||
// get file extension from url
|
||||
public static String GetFileExtension(String url)
|
||||
{
|
||||
String fileName = GetFileName(url);
|
||||
if (fileName == null) return null;
|
||||
public static String getFileExtension(final String url) {
|
||||
String fileName = getFileName(url);
|
||||
if (fileName == null) {
|
||||
return null;
|
||||
}
|
||||
String fileExt = fileName.substring(fileName.lastIndexOf("."));
|
||||
return fileExt.toLowerCase();
|
||||
}
|
||||
|
||||
// get url parameters
|
||||
public static Map<String, String> GetUrlParams(String url)
|
||||
{
|
||||
try
|
||||
{
|
||||
String query = new URL(url).getQuery(); // take all the parameters which are placed after ? sign in the file url
|
||||
public static Map<String, String> getUrlParams(final String url) {
|
||||
try {
|
||||
// take all the parameters which are placed after ? sign in the file url
|
||||
String query = new URL(url).getQuery();
|
||||
String[] params = query.split("&"); // parameters are separated by & sign
|
||||
Map<String, String> map = new HashMap<>();
|
||||
for (String param : params) // write parameters and their values to the map dictionary
|
||||
{
|
||||
for (String param : params) { // write parameters and their values to the map dictionary
|
||||
String name = param.split("=")[0];
|
||||
String value = param.split("=")[1];
|
||||
map.put(name, value);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,7 +18,6 @@
|
||||
|
||||
package helpers;
|
||||
|
||||
import helpers.DocumentManager;
|
||||
import com.google.gson.Gson;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
@ -26,8 +25,6 @@ import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.text.MessageFormat;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@ -35,90 +32,162 @@ import java.nio.charset.StandardCharsets;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
import utils.ConvertErrorType;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import static utils.Constants.CONVERTATION_ERROR_MESSAGE_TEMPLATE;
|
||||
import static utils.Constants.CONVERT_TIMEOUT_MS;
|
||||
import static utils.Constants.FULL_LOADING_IN_PERCENT;
|
||||
import static utils.Constants.MAX_KEY_LENGTH;
|
||||
|
||||
|
||||
public class ServiceConverter
|
||||
{
|
||||
private static int ConvertTimeout = 120000;
|
||||
private static final String DocumentConverterUrl = ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.converter");
|
||||
private static final String DocumentJwtHeader = ConfigManager.GetProperty("files.docservice.header");
|
||||
public final class ServiceConverter {
|
||||
private static int convertTimeout;
|
||||
private static final String DOCUMENT_CONVERTER_URL = ConfigManager
|
||||
.getProperty("files.docservice.url.site") + ConfigManager.getProperty("files.docservice.url.converter");
|
||||
private static final String DOCUMENT_JWT_HEADER = ConfigManager.getProperty("files.docservice.header");
|
||||
|
||||
public static class ConvertBody
|
||||
{
|
||||
public String region;
|
||||
public String url;
|
||||
public String outputtype;
|
||||
public String filetype;
|
||||
public String title;
|
||||
public String key;
|
||||
public Boolean async;
|
||||
public String token;
|
||||
public String password;
|
||||
private ServiceConverter() { }
|
||||
|
||||
public static class ConvertBody {
|
||||
private String region;
|
||||
private String url;
|
||||
private String outputtype;
|
||||
private String filetype;
|
||||
private String title;
|
||||
private String key;
|
||||
private Boolean async;
|
||||
private String token;
|
||||
private String password;
|
||||
|
||||
public void setRegion(final String regionParam) {
|
||||
this.region = regionParam;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(final String urlParam) {
|
||||
this.url = urlParam;
|
||||
}
|
||||
|
||||
public String getOutputtype() {
|
||||
return outputtype;
|
||||
}
|
||||
|
||||
public void setOutputtype(final String outputtypeParam) {
|
||||
this.outputtype = outputtypeParam;
|
||||
}
|
||||
|
||||
public String getFiletype() {
|
||||
return filetype;
|
||||
}
|
||||
|
||||
public void setFiletype(final String filetypeParam) {
|
||||
this.filetype = filetypeParam;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(final String titleParam) {
|
||||
this.title = titleParam;
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public void setKey(final String keyParam) {
|
||||
this.key = keyParam;
|
||||
}
|
||||
|
||||
public Boolean getAsync() {
|
||||
return async;
|
||||
}
|
||||
|
||||
public void setAsync(final Boolean asyncParam) {
|
||||
this.async = asyncParam;
|
||||
}
|
||||
|
||||
public void setToken(final String tokenParam) {
|
||||
this.token = tokenParam;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(final String passwordParam) {
|
||||
this.password = passwordParam;
|
||||
}
|
||||
}
|
||||
|
||||
static
|
||||
{
|
||||
try
|
||||
{
|
||||
static {
|
||||
try {
|
||||
// get timeout value from the settings.properties
|
||||
int timeout = Integer.parseInt(ConfigManager.GetProperty("files.docservice.timeout"));
|
||||
if (timeout > 0) // if it's greater than 0
|
||||
{
|
||||
ConvertTimeout = timeout; // assign this value to a convert timeout
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
int timeout = Integer.parseInt(ConfigManager.getProperty("files.docservice.timeout"));
|
||||
// if it's greater than 0 then value to a convert timeout
|
||||
convertTimeout = timeout > 0 ? timeout : CONVERT_TIMEOUT_MS;
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
}
|
||||
|
||||
// get the url of the converted file
|
||||
public static String GetConvertedUri(String documentUri, String fromExtension, String toExtension, String documentRevisionId, String filePass, Boolean isAsync, String lang) throws Exception
|
||||
{
|
||||
public static String getConvertedUri(final String documentUri, final String fromExtension,
|
||||
final String toExtension, final String documentRevisionId,
|
||||
final String filePass, final Boolean isAsync,
|
||||
final String lang) throws Exception {
|
||||
// check if the fromExtension parameter is defined; if not, get it from the document url
|
||||
fromExtension = fromExtension == null || fromExtension.isEmpty() ? FileUtility.GetFileExtension(documentUri) : fromExtension;
|
||||
String fromExt = fromExtension == null || fromExtension.isEmpty()
|
||||
? FileUtility.getFileExtension(documentUri) : fromExtension;
|
||||
|
||||
// check if the file name parameter is defined; if not, get random uuid for this file
|
||||
String title = FileUtility.GetFileName(documentUri);
|
||||
String title = FileUtility.getFileName(documentUri);
|
||||
title = title == null || title.isEmpty() ? UUID.randomUUID().toString() : title;
|
||||
|
||||
documentRevisionId = documentRevisionId == null || documentRevisionId.isEmpty() ? documentUri : documentRevisionId;
|
||||
String documentRevId = documentRevisionId == null || documentRevisionId.isEmpty()
|
||||
? documentUri : documentRevisionId;
|
||||
|
||||
documentRevisionId = GenerateRevisionId(documentRevisionId); // create document token
|
||||
documentRevId = generateRevisionId(documentRevId); // create document token
|
||||
|
||||
// write all the necessary parameters to the body object
|
||||
ConvertBody body = new ConvertBody();
|
||||
body.region = lang;
|
||||
body.url = documentUri;
|
||||
body.outputtype = toExtension.replace(".", "");
|
||||
body.filetype = fromExtension.replace(".", "");
|
||||
body.title = title;
|
||||
body.key = documentRevisionId;
|
||||
body.password = filePass;
|
||||
if (isAsync)
|
||||
body.async = true;
|
||||
body.setRegion(lang);
|
||||
body.setUrl(documentUri);
|
||||
body.setOutputtype(toExtension.replace(".", ""));
|
||||
body.setFiletype(fromExt.replace(".", ""));
|
||||
body.setTitle(title);
|
||||
body.setKey(documentRevId);
|
||||
body.setPassword(filePass);
|
||||
if (isAsync) {
|
||||
body.setAsync(true);
|
||||
}
|
||||
|
||||
String headerToken = "";
|
||||
if (DocumentManager.TokenEnabled())
|
||||
{
|
||||
if (DocumentManager.tokenEnabled()) {
|
||||
HashMap<String, Object> map = new HashMap<String, Object>();
|
||||
map.put("region", lang);
|
||||
map.put("url", body.url);
|
||||
map.put("outputtype", body.outputtype);
|
||||
map.put("filetype", body.filetype);
|
||||
map.put("title", body.title);
|
||||
map.put("key", body.key);
|
||||
map.put("password", body.password);
|
||||
if (isAsync)
|
||||
map.put("async", body.async);
|
||||
map.put("url", body.getUrl());
|
||||
map.put("outputtype", body.getOutputtype());
|
||||
map.put("filetype", body.getFiletype());
|
||||
map.put("title", body.getTitle());
|
||||
map.put("key", body.getKey());
|
||||
map.put("password", body.getPassword());
|
||||
if (isAsync) {
|
||||
map.put("async", body.getAsync());
|
||||
}
|
||||
|
||||
// add token to the body if it is enabled
|
||||
String token = DocumentManager.CreateToken(map);
|
||||
body.token = token;
|
||||
String token = DocumentManager.createToken(map);
|
||||
body.setToken(token);
|
||||
|
||||
Map<String, Object> payloadMap = new HashMap<String, Object>();
|
||||
payloadMap.put("payload", map); // create payload object
|
||||
headerToken = DocumentManager.CreateToken(payloadMap); // create header token
|
||||
headerToken = DocumentManager.createToken(payloadMap); // create header token
|
||||
}
|
||||
|
||||
Gson gson = new Gson();
|
||||
@ -127,25 +196,25 @@ public class ServiceConverter
|
||||
byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
// specify request parameters
|
||||
URL url = new URL(DocumentConverterUrl);
|
||||
URL url = new URL(DOCUMENT_CONVERTER_URL);
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setDoOutput(true);
|
||||
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
|
||||
connection.setFixedLengthStreamingMode(bodyByte.length);
|
||||
connection.setRequestProperty("Accept", "application/json");
|
||||
connection.setConnectTimeout(ConvertTimeout);
|
||||
connection.setConnectTimeout(convertTimeout);
|
||||
|
||||
// write header token to the request
|
||||
if (DocumentManager.TokenEnabled())
|
||||
{
|
||||
connection.setRequestProperty(DocumentJwtHeader.equals("") ? "Authorization" : DocumentJwtHeader, "Bearer " + headerToken);
|
||||
if (DocumentManager.tokenEnabled()) {
|
||||
connection.setRequestProperty(DOCUMENT_JWT_HEADER.equals("")
|
||||
? "Authorization" : DOCUMENT_JWT_HEADER, "Bearer " + headerToken);
|
||||
}
|
||||
|
||||
connection.connect();
|
||||
|
||||
int statusCode = connection.getResponseCode();
|
||||
if (statusCode != 200) { // checking status code
|
||||
if (statusCode != HttpServletResponse.SC_OK) { // checking status code
|
||||
connection.disconnect();
|
||||
throw new Exception("Conversion service returned status: " + statusCode);
|
||||
}
|
||||
@ -155,110 +224,73 @@ public class ServiceConverter
|
||||
|
||||
InputStream stream = connection.getInputStream();
|
||||
|
||||
if (stream == null)
|
||||
if (stream == null) {
|
||||
throw new Exception("Could not get an answer");
|
||||
}
|
||||
|
||||
// convert string to json
|
||||
String jsonString = ConvertStreamToString(stream);
|
||||
String jsonString = convertStreamToString(stream);
|
||||
|
||||
connection.disconnect();
|
||||
|
||||
return GetResponseUri(jsonString);
|
||||
return getResponseUri(jsonString);
|
||||
}
|
||||
|
||||
// generate document key
|
||||
public static String GenerateRevisionId(String expectedKey)
|
||||
{
|
||||
if (expectedKey.length() > 20) // if the expected key length is greater than 20
|
||||
expectedKey = Integer.toString(expectedKey.hashCode()); // the expected key is hashed and a fixed length value is stored in the string format
|
||||
public static String generateRevisionId(final String expectedKey) {
|
||||
/* if the expected key length is greater than 20 then
|
||||
he expected key is hashed and a fixed length value is stored in the string format */
|
||||
String formatKey = expectedKey.length() > MAX_KEY_LENGTH
|
||||
? Integer.toString(expectedKey.hashCode()) : expectedKey;
|
||||
String key = formatKey.replace("[^0-9-.a-zA-Z_=]", "_");
|
||||
|
||||
String key = expectedKey.replace("[^0-9-.a-zA-Z_=]", "_");
|
||||
|
||||
return key.substring(0, Math.min(key.length(), 20)); // the resulting key length is 20 or less
|
||||
return key.substring(0, Math.min(key.length(), MAX_KEY_LENGTH)); // the resulting key length is 20 or less
|
||||
}
|
||||
|
||||
// create an error message for an error code
|
||||
private static void ProcessConvertServiceResponceError(int errorCode) throws Exception
|
||||
{
|
||||
String errorMessage = "";
|
||||
String errorMessageTemplate = "Error occurred in the ConvertService: ";
|
||||
|
||||
// add the error message to the error message template depending on the error code
|
||||
switch (errorCode)
|
||||
{
|
||||
case -8:
|
||||
errorMessage = errorMessageTemplate + "Error document VKey";
|
||||
break;
|
||||
case -7:
|
||||
errorMessage = errorMessageTemplate + "Error document request";
|
||||
break;
|
||||
case -6:
|
||||
errorMessage = errorMessageTemplate + "Error database";
|
||||
break;
|
||||
case -5:
|
||||
errorMessage = errorMessageTemplate + "Incorrect password";
|
||||
break;
|
||||
case -4:
|
||||
errorMessage = errorMessageTemplate + "Error download error";
|
||||
break;
|
||||
case -3:
|
||||
errorMessage = errorMessageTemplate + "Error convertation error";
|
||||
break;
|
||||
case -2:
|
||||
errorMessage = errorMessageTemplate + "Error convertation timeout";
|
||||
break;
|
||||
case -1:
|
||||
errorMessage = errorMessageTemplate + "Error convertation unknown";
|
||||
break;
|
||||
case 0: // if the error code is equal to 0, the error message is empty
|
||||
break;
|
||||
default:
|
||||
errorMessage = "ErrorCode = " + errorCode; // default value for the error message
|
||||
break;
|
||||
}
|
||||
private static void processConvertServiceResponceError(final int errorCode) throws Exception {
|
||||
String errorMessage = CONVERTATION_ERROR_MESSAGE_TEMPLATE + ConvertErrorType.labelOfCode(errorCode);
|
||||
|
||||
throw new Exception(errorMessage);
|
||||
}
|
||||
|
||||
// get the response url
|
||||
private static String GetResponseUri(String jsonString) throws Exception
|
||||
{
|
||||
JSONObject jsonObj = ConvertStringToJSON(jsonString);
|
||||
private static String getResponseUri(final String jsonString) throws Exception {
|
||||
JSONObject jsonObj = convertStringToJSON(jsonString);
|
||||
|
||||
Object error = jsonObj.get("error");
|
||||
if (error != null) // if an error occurs
|
||||
ProcessConvertServiceResponceError(Math.toIntExact((long)error)); // then get an error message
|
||||
if (error != null) { // if an error occurs
|
||||
processConvertServiceResponceError(Math.toIntExact((long) error)); // then get an error message
|
||||
}
|
||||
|
||||
// check if the conversion is completed and save the result to a variable
|
||||
Boolean isEndConvert = (Boolean) jsonObj.get("endConvert");
|
||||
|
||||
Long resultPercent = 0l;
|
||||
Long resultPercent = 0L;
|
||||
String responseUri = null;
|
||||
|
||||
if (isEndConvert) // if the conversion is completed
|
||||
{
|
||||
resultPercent = 100l;
|
||||
if (isEndConvert) { // if the conversion is completed
|
||||
resultPercent = FULL_LOADING_IN_PERCENT;
|
||||
responseUri = (String) jsonObj.get("fileUrl"); // get the file url
|
||||
}
|
||||
else // if the conversion isn't completed
|
||||
{
|
||||
} else { // if the conversion isn't completed
|
||||
resultPercent = (Long) jsonObj.get("percent");
|
||||
resultPercent = resultPercent >= 100l ? 99l : resultPercent; // get the percentage value
|
||||
resultPercent = resultPercent >= FULL_LOADING_IN_PERCENT
|
||||
? FULL_LOADING_IN_PERCENT - 1 : resultPercent; // get the percentage value
|
||||
}
|
||||
|
||||
return resultPercent >= 100l ? responseUri : "";
|
||||
return resultPercent >= FULL_LOADING_IN_PERCENT ? responseUri : "";
|
||||
}
|
||||
|
||||
// convert stream to string
|
||||
public static String ConvertStreamToString(InputStream stream) throws IOException
|
||||
{
|
||||
public static String convertStreamToString(final InputStream stream) throws IOException {
|
||||
InputStreamReader inputStreamReader = new InputStreamReader(stream); // create an object to get incoming stream
|
||||
StringBuilder stringBuilder = new StringBuilder(); // create a string builder object
|
||||
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // create an object to read incoming streams
|
||||
|
||||
// create an object to read incoming streams
|
||||
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
|
||||
String line = bufferedReader.readLine(); // get incoming streams by lines
|
||||
|
||||
while (line != null)
|
||||
{
|
||||
while (line != null) {
|
||||
stringBuilder.append(line); // concatenate strings using the string builder
|
||||
line = bufferedReader.readLine();
|
||||
}
|
||||
@ -269,12 +301,11 @@ public class ServiceConverter
|
||||
}
|
||||
|
||||
// convert string to json
|
||||
public static JSONObject ConvertStringToJSON(String jsonString) throws ParseException
|
||||
{
|
||||
public static JSONObject convertStringToJSON(final String jsonString) throws ParseException {
|
||||
JSONParser parser = new JSONParser();
|
||||
Object obj = parser.parse(jsonString); // parse json string
|
||||
JSONObject jsonObj = (JSONObject) obj; // and turn it into a json object
|
||||
|
||||
return jsonObj;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -25,19 +25,37 @@ import org.json.simple.parser.JSONParser;
|
||||
import org.primeframework.jwt.domain.JWT;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.*;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.InputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class TrackManager {
|
||||
private static final String DocumentJwtHeader = ConfigManager.GetProperty("files.docservice.header");
|
||||
import static utils.Constants.BUFFER_SIZE;
|
||||
import static utils.Constants.FILE_SAVE_TIMEOUT;
|
||||
import static utils.Constants.KILOBYTE_SIZE;
|
||||
|
||||
public final class TrackManager {
|
||||
private static final String DOCUMENT_JWT_HEADER = ConfigManager.getProperty("files.docservice.header");
|
||||
|
||||
private TrackManager() { }
|
||||
|
||||
// read request body
|
||||
public static JSONObject readBody(HttpServletRequest request, PrintWriter writer) throws Exception {
|
||||
public static JSONObject readBody(final HttpServletRequest request, final PrintWriter writer) throws Exception {
|
||||
String bodyString = "";
|
||||
|
||||
try {
|
||||
@ -46,8 +64,7 @@ public class TrackManager {
|
||||
scanner.useDelimiter("\\A");
|
||||
bodyString = scanner.hasNext() ? scanner.next() : "";
|
||||
scanner.close();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
} catch (Exception ex) {
|
||||
writer.write("get request.getInputStream error:" + ex.getMessage());
|
||||
throw ex;
|
||||
}
|
||||
@ -70,13 +87,17 @@ public class TrackManager {
|
||||
}
|
||||
|
||||
// if the secret key to generate token exists
|
||||
if (DocumentManager.TokenEnabled()) {
|
||||
if (DocumentManager.tokenEnabled()) {
|
||||
String token = (String) body.get("token"); // get the document token
|
||||
|
||||
if (token == null) { // if JSON web token is not received
|
||||
String header = (String) request.getHeader(DocumentJwtHeader == null || DocumentJwtHeader.isEmpty() ? "Authorization" : DocumentJwtHeader); // get it from the Authorization header
|
||||
String header = (String) request.getHeader(DOCUMENT_JWT_HEADER == null || DOCUMENT_JWT_HEADER.isEmpty()
|
||||
? "Authorization" : DOCUMENT_JWT_HEADER); // get it from the Authorization header
|
||||
if (header != null && !header.isEmpty()) {
|
||||
token = header.startsWith("Bearer ") ? header.substring(7) : header; // and save it without Authorization prefix
|
||||
String bearerPrefix = "Bearer ";
|
||||
|
||||
// and save it without Authorization prefix
|
||||
token = header.startsWith(bearerPrefix) ? header.substring(bearerPrefix.length()) : header;
|
||||
}
|
||||
}
|
||||
|
||||
@ -85,7 +106,7 @@ public class TrackManager {
|
||||
throw new Exception("{\"error\":1,\"message\":\"JWT expected\"}");
|
||||
}
|
||||
|
||||
JWT jwt = DocumentManager.ReadToken(token); // read token
|
||||
JWT jwt = DocumentManager.readToken(token); // read token
|
||||
if (jwt == null) {
|
||||
writer.write("{\"error\":1,\"message\":\"JWT validation failed\"}"); // an error occurs
|
||||
throw new Exception("{\"error\":1,\"message\":\"JWT validation failed\"}");
|
||||
@ -94,7 +115,7 @@ public class TrackManager {
|
||||
if (jwt.getObject("payload") != null) { // get the payload object from the request body
|
||||
try {
|
||||
@SuppressWarnings("unchecked") LinkedHashMap<String, Object> payload =
|
||||
(LinkedHashMap<String, Object>)jwt.getObject("payload");
|
||||
(LinkedHashMap<String, Object>) jwt.getObject("payload");
|
||||
|
||||
jwt.claims = payload;
|
||||
} catch (Exception ex) {
|
||||
@ -117,7 +138,9 @@ public class TrackManager {
|
||||
}
|
||||
|
||||
// file saving process
|
||||
public static void processSave(JSONObject body, String fileName, String userAddress) throws Exception {
|
||||
public static void processSave(final JSONObject body,
|
||||
final String fileName,
|
||||
final String userAddress) throws Exception {
|
||||
if (body.get("url") == null) {
|
||||
throw new Exception("DownloadUrl is null");
|
||||
}
|
||||
@ -126,57 +149,76 @@ public class TrackManager {
|
||||
String key = (String) body.get("key");
|
||||
String newFileName = fileName;
|
||||
|
||||
String curExt = FileUtility.GetFileExtension(fileName); // get current file extension
|
||||
String curExt = FileUtility.getFileExtension(fileName); // get current file extension
|
||||
String downloadExt = "." + (String) body.get("filetype"); // get the extension of the downloaded file
|
||||
|
||||
// Todo [Delete in version 7.0 or higher]
|
||||
if (downloadExt == "." + null) downloadExt = FileUtility.GetFileExtension(downloadUri); // Support for versions below 7.0
|
||||
|
||||
// convert downloaded file to the file with the current extension if these extensions aren't equal
|
||||
if (!curExt.equals(downloadExt)) {
|
||||
try {
|
||||
String newFileUri = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), null, false, null); // convert file and get url to a new file
|
||||
String newFileUri = ServiceConverter
|
||||
.getConvertedUri(downloadUri, downloadExt, curExt,
|
||||
ServiceConverter.generateRevisionId(downloadUri),
|
||||
null, false, null); // convert file and get url to a new file
|
||||
if (newFileUri.isEmpty()) {
|
||||
newFileName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress); // get the correct file name if it already exists
|
||||
|
||||
// get the correct file name if it already exists
|
||||
newFileName = DocumentManager
|
||||
.getCorrectName(FileUtility
|
||||
.getFileNameWithoutExtension(fileName) + downloadExt, userAddress);
|
||||
} else {
|
||||
downloadUri = newFileUri;
|
||||
}
|
||||
} catch (Exception e){
|
||||
newFileName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
|
||||
} catch (Exception e) {
|
||||
newFileName = DocumentManager.getCorrectName(FileUtility
|
||||
.getFileNameWithoutExtension(fileName) + downloadExt, userAddress);
|
||||
}
|
||||
}
|
||||
|
||||
String storagePath = DocumentManager.StoragePath(newFileName, userAddress); // get the file path
|
||||
File histDir = new File(DocumentManager.HistoryDir(storagePath)); // get the path to the history direction
|
||||
if (!histDir.exists()) histDir.mkdirs(); // if the path doesn't exist, create it
|
||||
byte[] byteArrayFile = getDownloadFile(downloadUri); // download document file
|
||||
|
||||
String versionDir = DocumentManager.VersionDir(histDir.getAbsolutePath(), DocumentManager.GetFileVersion(histDir.getAbsolutePath())); // get the path to the file version
|
||||
String storagePath = DocumentManager.storagePath(newFileName, userAddress); // get the file path
|
||||
File histDir = new File(DocumentManager.historyDir(storagePath)); // get the path to the history direction
|
||||
if (!histDir.exists()) {
|
||||
histDir.mkdirs(); // if the path doesn't exist, create it
|
||||
}
|
||||
|
||||
String versionDir = DocumentManager.versionDir(histDir.getAbsolutePath(), DocumentManager
|
||||
.getFileVersion(histDir.getAbsolutePath())); // get the path to the file version
|
||||
File ver = new File(versionDir);
|
||||
File lastVersion = new File(DocumentManager.StoragePath(fileName, userAddress));
|
||||
File toSave = new File(storagePath);
|
||||
File lastVersion = new File(DocumentManager.storagePath(fileName, userAddress));
|
||||
Path toSave = Paths.get(storagePath);
|
||||
|
||||
if (!ver.exists()) ver.mkdirs();
|
||||
if (!ver.exists()) {
|
||||
ver.mkdirs();
|
||||
}
|
||||
|
||||
lastVersion.renameTo(new File(versionDir + File.separator + "prev" + curExt)); // get the path to the previous file version and rename the last file version with it
|
||||
// get the path to the previous file version and rename the last file version with it
|
||||
lastVersion.renameTo(new File(versionDir + File.separator + "prev" + curExt));
|
||||
|
||||
downloadToFile(downloadUri, toSave); // save file to the storage path
|
||||
downloadToFile(changesUri, new File(versionDir + File.separator + "diff.zip")); // save file changes to the diff.zip archive
|
||||
saveFile(byteArrayFile, toSave); // save document file
|
||||
|
||||
byte[] byteArrayChanges = getDownloadFile(changesUri);
|
||||
saveFile(byteArrayChanges, Paths.get(versionDir + File.separator + "diff.zip"));
|
||||
|
||||
String history = (String) body.get("changeshistory");
|
||||
if (history == null && body.containsKey("history")) {
|
||||
history = ((JSONObject) body.get("history")).toJSONString();
|
||||
}
|
||||
if (history != null && !history.isEmpty()) {
|
||||
FileWriter fw = new FileWriter(new File(versionDir + File.separator + "changes.json")); // write the history changes to the changes.json file
|
||||
|
||||
// write the history changes to the changes.json file
|
||||
FileWriter fw = new FileWriter(new File(versionDir + File.separator + "changes.json"));
|
||||
fw.write(history);
|
||||
fw.close();
|
||||
}
|
||||
|
||||
FileWriter fw = new FileWriter(new File(versionDir + File.separator + "key.txt")); // write the key value to the key.txt file
|
||||
// write the key value to the key.txt file
|
||||
FileWriter fw = new FileWriter(new File(versionDir + File.separator + "key.txt"));
|
||||
fw.write(key);
|
||||
fw.close();
|
||||
|
||||
String forcesavePath = DocumentManager.ForcesavePath(newFileName, userAddress, false); // get the path to the forcesaved file version
|
||||
// get the path to the forcesaved file version
|
||||
String forcesavePath = DocumentManager.forcesavePath(newFileName, userAddress, false);
|
||||
if (!forcesavePath.equals("")) { // if the forcesaved file version exists
|
||||
File forceSaveFile = new File(forcesavePath);
|
||||
forceSaveFile.delete(); // remove it
|
||||
@ -184,111 +226,157 @@ public class TrackManager {
|
||||
}
|
||||
|
||||
// file force saving process
|
||||
public static void processForceSave(JSONObject body, String fileName, String userAddress) throws Exception {
|
||||
public static void processForceSave(final JSONObject body,
|
||||
final String fileNameParam,
|
||||
final String userAddress) throws Exception {
|
||||
if (body.get("url") == null) {
|
||||
throw new Exception("DownloadUrl is null");
|
||||
}
|
||||
String fileName = fileNameParam;
|
||||
String downloadUri = (String) body.get("url");
|
||||
|
||||
String curExt = FileUtility.GetFileExtension(fileName); // get current file extension
|
||||
String downloadExt = "."+(String) body.get("filetype"); // get the extension of the downloaded file
|
||||
|
||||
// Todo [Delete in version 7.0 or higher]
|
||||
if (downloadExt == "."+null) downloadExt = FileUtility.GetFileExtension(downloadUri); // Support for versions below 7.0
|
||||
String curExt = FileUtility.getFileExtension(fileName); // get current file extension
|
||||
String downloadExt = "." + (String) body.get("filetype"); // get the extension of the downloaded file
|
||||
|
||||
Boolean newFileName = false;
|
||||
|
||||
// convert downloaded file to the file with the current extension if these extensions aren't equal
|
||||
if (!curExt.equals(downloadExt)) {
|
||||
try {
|
||||
String newFileUri = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), null, false, null); // convert file and get url to a new file
|
||||
String newFileUri = ServiceConverter
|
||||
.getConvertedUri(downloadUri, downloadExt, curExt,
|
||||
ServiceConverter.generateRevisionId(downloadUri), null,
|
||||
false, null); // convert file and get url to a new file
|
||||
if (newFileUri.isEmpty()) {
|
||||
newFileName = true;
|
||||
} else {
|
||||
downloadUri = newFileUri;
|
||||
}
|
||||
} catch (Exception e){
|
||||
} catch (Exception e) {
|
||||
newFileName = true;
|
||||
}
|
||||
}
|
||||
|
||||
byte[] byteArrayFile = getDownloadFile(downloadUri); // download document file
|
||||
String forcesavePath = "";
|
||||
boolean isSubmitForm = body.get("forcesavetype").toString().equals("3"); // SubmitForm
|
||||
|
||||
if (isSubmitForm) { // if the form is submitted
|
||||
// new file
|
||||
if (newFileName){
|
||||
fileName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress); // get the correct file name if it already exists
|
||||
if (newFileName) {
|
||||
fileName = DocumentManager.getCorrectName(FileUtility.getFileNameWithoutExtension(fileName)
|
||||
+ "-form" + downloadExt, userAddress); // get the correct file name if it already exists
|
||||
} else {
|
||||
fileName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + "-form" + curExt, userAddress);
|
||||
fileName = DocumentManager.getCorrectName(FileUtility.getFileNameWithoutExtension(fileName)
|
||||
+ "-form" + curExt, userAddress);
|
||||
}
|
||||
forcesavePath = DocumentManager.StoragePath(fileName, userAddress);
|
||||
forcesavePath = DocumentManager.storagePath(fileName, userAddress);
|
||||
} else {
|
||||
if (newFileName){
|
||||
fileName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
|
||||
if (newFileName) {
|
||||
fileName = DocumentManager.getCorrectName(FileUtility
|
||||
.getFileNameWithoutExtension(fileName) + downloadExt, userAddress);
|
||||
}
|
||||
|
||||
// create forcesave path if it doesn't exist
|
||||
forcesavePath = DocumentManager.ForcesavePath(fileName, userAddress, false);
|
||||
forcesavePath = DocumentManager.forcesavePath(fileName, userAddress, false);
|
||||
if (forcesavePath == "") {
|
||||
forcesavePath = DocumentManager.ForcesavePath(fileName, userAddress, true);
|
||||
forcesavePath = DocumentManager.forcesavePath(fileName, userAddress, true);
|
||||
}
|
||||
}
|
||||
|
||||
File toSave = new File(forcesavePath);
|
||||
downloadToFile(downloadUri, toSave);
|
||||
saveFile(byteArrayFile, Paths.get(forcesavePath));
|
||||
|
||||
if (isSubmitForm) {
|
||||
JSONArray actions = (JSONArray) body.get("actions");
|
||||
JSONObject action = (JSONObject) actions.get(0);
|
||||
String user = (String) action.get("userid"); // get the user id
|
||||
DocumentManager.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for forcesaved file
|
||||
|
||||
// create meta data for forcesaved file
|
||||
DocumentManager.createMeta(fileName, user, "Filling Form", userAddress);
|
||||
}
|
||||
}
|
||||
|
||||
// save file information from the url to the file specified
|
||||
private static void downloadToFile(String url, File file) throws Exception {
|
||||
if (url == null || url.isEmpty()) throw new Exception("argument url"); // url isn't specified
|
||||
if (file == null) throw new Exception("argument path"); // file isn't specified
|
||||
// create a new file if it does not exist
|
||||
private static boolean createFile(final byte[] byteArray, final Path path) {
|
||||
if (Files.exists(path)) {
|
||||
return true;
|
||||
}
|
||||
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray)) {
|
||||
File file = Files.createFile(path).toFile(); // create a new file in the specified path
|
||||
try (FileOutputStream out = new FileOutputStream(file)) {
|
||||
int read;
|
||||
final byte[] bytes = new byte[KILOBYTE_SIZE];
|
||||
while ((read = byteArrayInputStream.read(bytes)) != -1) {
|
||||
out.write(bytes, 0, read); // write bytes to the output stream
|
||||
}
|
||||
out.flush(); // force write data to the output stream that can be cached in the current thread
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// get byte array from stream
|
||||
private static byte[] getAllBytes(final InputStream is) throws IOException {
|
||||
ByteArrayOutputStream os = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[BUFFER_SIZE];
|
||||
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
|
||||
os.write(buffer, 0, len);
|
||||
}
|
||||
return os.toByteArray();
|
||||
}
|
||||
|
||||
// save file
|
||||
private static boolean saveFile(final byte[] byteArray, final Path path) {
|
||||
if (path == null) {
|
||||
throw new RuntimeException("Path argument is not specified"); // file isn't specified
|
||||
}
|
||||
if (!Files.exists(path)) { // if the specified file does not exist
|
||||
return createFile(byteArray, path); // create it in the specified directory
|
||||
} else {
|
||||
try {
|
||||
Files.write(path, byteArray); // otherwise, write new information in the bytes format to the file
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// download file from url
|
||||
private static byte[] getDownloadFile(final String url) throws Exception {
|
||||
if (url == null || url.isEmpty()) {
|
||||
throw new RuntimeException("Url argument is not specified"); // URL isn't specified
|
||||
}
|
||||
|
||||
URL uri = new URL(url);
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) uri.openConnection();
|
||||
connection.setConnectTimeout(5000);
|
||||
connection.setConnectTimeout(FILE_SAVE_TIMEOUT);
|
||||
InputStream stream = connection.getInputStream(); // get input stream of the file information from the URL
|
||||
|
||||
int statusCode = connection.getResponseCode();
|
||||
if (statusCode != 200) { // checking status code
|
||||
|
||||
if (statusCode != HttpServletResponse.SC_OK) { // checking status code
|
||||
connection.disconnect();
|
||||
throw new RuntimeException("Document editing service returned status: " + statusCode);
|
||||
}
|
||||
|
||||
InputStream stream = connection.getInputStream(); // get input stream of the file information from the url
|
||||
|
||||
if (stream == null)
|
||||
{
|
||||
throw new Exception("Stream is null");
|
||||
if (stream == null) {
|
||||
connection.disconnect();
|
||||
throw new RuntimeException("Input stream is null");
|
||||
}
|
||||
|
||||
try (FileOutputStream out = new FileOutputStream(file))
|
||||
{
|
||||
int read;
|
||||
final byte[] bytes = new byte[1024];
|
||||
while ((read = stream.read(bytes)) != -1)
|
||||
{
|
||||
out.write(bytes, 0, read); // write bytes to the output stream
|
||||
}
|
||||
|
||||
// force write data to the output stream that can be cached in the current thread
|
||||
out.flush();
|
||||
}
|
||||
|
||||
connection.disconnect();
|
||||
return getAllBytes(stream);
|
||||
}
|
||||
|
||||
// create a command request
|
||||
public static void commandRequest(String method, String key, HashMap meta) throws Exception {
|
||||
String DocumentCommandUrl = ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.command");
|
||||
public static void commandRequest(final String method, final String key, final HashMap meta) throws Exception {
|
||||
String documentCommandUrl = ConfigManager.getProperty("files.docservice.url.site") + ConfigManager
|
||||
.getProperty("files.docservice.url.command");
|
||||
|
||||
URL url = new URL(DocumentCommandUrl);
|
||||
URL url = new URL(documentCommandUrl);
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
|
||||
|
||||
HashMap<String, Object> params = new HashMap<String, Object>();
|
||||
@ -300,16 +388,16 @@ public class TrackManager {
|
||||
}
|
||||
|
||||
String headerToken = "";
|
||||
if (DocumentManager.TokenEnabled()) // check if a secret key to generate token exists or not
|
||||
{
|
||||
if (DocumentManager.tokenEnabled()) { // check if a secret key to generate token exists or not
|
||||
Map<String, Object> payloadMap = new HashMap<String, Object>();
|
||||
payloadMap.put("payload", params);
|
||||
headerToken = DocumentManager.CreateToken(payloadMap); // encode a payload object into a header token
|
||||
headerToken = DocumentManager.createToken(payloadMap); // encode a payload object into a header token
|
||||
|
||||
// add a header Authorization with a header token and Authorization prefix in it
|
||||
connection.setRequestProperty(DocumentJwtHeader.equals("") ? "Authorization" : DocumentJwtHeader, "Bearer " + headerToken);
|
||||
connection.setRequestProperty(DOCUMENT_JWT_HEADER.equals("")
|
||||
? "Authorization" : DOCUMENT_JWT_HEADER, "Bearer " + headerToken);
|
||||
|
||||
String token = DocumentManager.CreateToken(params); // encode a payload object into a body token
|
||||
String token = DocumentManager.createToken(params); // encode a payload object into a body token
|
||||
params.put("token", token);
|
||||
}
|
||||
|
||||
@ -319,7 +407,9 @@ public class TrackManager {
|
||||
byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
connection.setRequestMethod("POST"); // set the request method
|
||||
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); // set the Content-Type header
|
||||
|
||||
// set the Content-Type header
|
||||
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
|
||||
connection.setDoOutput(true); // set the doOutput field to true
|
||||
|
||||
connection.connect();
|
||||
@ -328,14 +418,15 @@ public class TrackManager {
|
||||
}
|
||||
InputStream stream = connection.getInputStream(); // get input stream
|
||||
|
||||
if (stream == null)
|
||||
if (stream == null) {
|
||||
throw new Exception("Could not get an answer");
|
||||
}
|
||||
|
||||
String jsonString = ServiceConverter.ConvertStreamToString(stream); // convert stream to json string
|
||||
String jsonString = ServiceConverter.convertStreamToString(stream); // convert stream to json string
|
||||
connection.disconnect();
|
||||
|
||||
JSONObject response = ServiceConverter.ConvertStringToJSON(jsonString); // convert json string to json object
|
||||
if (!response.get("error").toString().equals("0")){
|
||||
JSONObject response = ServiceConverter.convertStringToJSON(jsonString); // convert json string to json object
|
||||
if (!response.get("error").toString().equals("0")) {
|
||||
throw new Exception(response.toJSONString());
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,13 +18,18 @@
|
||||
|
||||
package helpers;
|
||||
|
||||
import entities.*;
|
||||
import entities.CommentGroups;
|
||||
import entities.User;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class Users {
|
||||
public final class Users {
|
||||
|
||||
static List<String> descr_user_1 = new ArrayList<String>() {{
|
||||
private static List<String> descriptionUserFirst = new ArrayList<String>() {{
|
||||
add("File author by default");
|
||||
add("Doesn’t belong to any group");
|
||||
add("Can review all the changes");
|
||||
@ -34,16 +39,17 @@ public class Users {
|
||||
add("Can see the information about all users");
|
||||
}};
|
||||
|
||||
static List<String> descr_user_2 = new ArrayList<String>() {{
|
||||
private static List<String> descriptionUserSecond = new ArrayList<String>() {{
|
||||
add("Belongs to Group2");
|
||||
add("Can review only his own changes or changes made by users with no group");
|
||||
add("Can view comments, edit his own comments and comments left by users with no group. Can remove his own comments only");
|
||||
add("Can view comments, edit his own comments and comments left by users with no group."
|
||||
+ " Can remove his own comments only");
|
||||
add("This file is marked as favorite");
|
||||
add("Can create new files from the editor");
|
||||
add("Can see the information about users from Group2 and users who don’t belong to any group");
|
||||
}};
|
||||
|
||||
static List<String> descr_user_3 = new ArrayList<String>() {{
|
||||
private static List<String> descriptionUserThird = new ArrayList<String>() {{
|
||||
add("Belongs to Group3");
|
||||
add("Can review changes made by Group2 users");
|
||||
add("Can view comments left by Group2 and Group3 users. Can edit comments left by the Group2 users");
|
||||
@ -55,7 +61,7 @@ public class Users {
|
||||
add("Can see the information about Group2 users");
|
||||
}};
|
||||
|
||||
static List<String> descr_user_0 = new ArrayList<String>() {{
|
||||
private static List<String> descriptionUserZero = new ArrayList<String>() {{
|
||||
add("The name is requested when the editor is opened");
|
||||
add("Doesn’t belong to any group");
|
||||
add("Can review all the changes");
|
||||
@ -72,22 +78,27 @@ public class Users {
|
||||
private static List<User> users = new ArrayList<User>() {{
|
||||
add(new User("uid-1", "John Smith", "smith@example.com",
|
||||
"", null, new CommentGroups(), null,
|
||||
null, new ArrayList<String>(), descr_user_1, true));
|
||||
null, new ArrayList<String>(), descriptionUserFirst, true));
|
||||
add(new User("uid-2", "Mark Pottato", "pottato@example.com",
|
||||
"group-2", Arrays.asList("group-2", ""), new CommentGroups(null, Arrays.asList("group-2", ""), Arrays.asList("group-2")), Arrays.asList("group-2", ""),
|
||||
true, new ArrayList<String>(), descr_user_2, false));
|
||||
"group-2", Arrays.asList("group-2", ""), new CommentGroups(null,
|
||||
Arrays.asList("group-2", ""), Arrays.asList("group-2")), Arrays.asList("group-2", ""),
|
||||
true, new ArrayList<String>(), descriptionUserSecond, false));
|
||||
add(new User("uid-3", "Hamish Mitchell", "mitchell@example.com",
|
||||
"group-3", Arrays.asList("group-2"), new CommentGroups(Arrays.asList("group-3", "group-2"), Arrays.asList("group-2"), new ArrayList<String>()), Arrays.asList("group-2"),
|
||||
false, Arrays.asList("copy", "download", "print"), descr_user_3, false));
|
||||
"group-3", Arrays.asList("group-2"), new CommentGroups(Arrays.asList("group-3", "group-2"),
|
||||
Arrays.asList("group-2"), new ArrayList<String>()), Arrays.asList("group-2"),
|
||||
false, Arrays.asList("copy", "download", "print"),
|
||||
descriptionUserThird, false));
|
||||
add(new User("uid-0", null, null,
|
||||
"", null, new CommentGroups(), new ArrayList<String>(),
|
||||
null, new ArrayList<String>(), descr_user_0, false));
|
||||
null, new ArrayList<String>(), descriptionUserZero, false));
|
||||
}};
|
||||
|
||||
private Users() { }
|
||||
|
||||
// get a user by id specified
|
||||
public static User getUser (String id) {
|
||||
public static User getUser(final String id) {
|
||||
for (User user : users) {
|
||||
if (user.id.equals(id)) {
|
||||
if (user.getId().equals(id)) {
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@ -95,18 +106,18 @@ public class Users {
|
||||
}
|
||||
|
||||
// get a list of all the users
|
||||
public static List<User> getAllUsers () {
|
||||
public static List<User> getAllUsers() {
|
||||
return users;
|
||||
}
|
||||
|
||||
// get a list of users with their names and emails for mentions
|
||||
public static List<Map<String, Object>> getUsersForMentions (String id) {
|
||||
public static List<Map<String, Object>> getUsersForMentions(final String id) {
|
||||
List<Map<String, Object>> usersData = new ArrayList<>();
|
||||
for (User user : users) {
|
||||
if (!user.id.equals(id) && user.name != null && user.email != null) {
|
||||
if (!user.getId().equals(id) && user.getName() != null && user.getEmail() != null) {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("name", user.name);
|
||||
data.put("email", user.email);
|
||||
data.put("name", user.getName());
|
||||
data.put("email", user.getEmail());
|
||||
usersData.add(data);
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,32 @@
|
||||
/**
|
||||
*
|
||||
* (c) Copyright Ascensio System SIA 2023
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package utils;
|
||||
|
||||
public final class Constants {
|
||||
public static final Integer MAX_FILE_SIZE = 5 * 1024 * 1024;
|
||||
public static final Integer CONVERT_TIMEOUT_MS = 120000;
|
||||
public static final String CONVERTATION_ERROR_MESSAGE_TEMPLATE = "Error occurred in the ConvertService: ";
|
||||
public static final Long FULL_LOADING_IN_PERCENT = 100L;
|
||||
public static final Integer FILE_SAVE_TIMEOUT = 5000;
|
||||
public static final Integer MAX_KEY_LENGTH = 20;
|
||||
public static final Integer KILOBYTE_SIZE = 1024;
|
||||
public static final Integer BUFFER_SIZE = 0xFFFF;
|
||||
|
||||
private Constants() { }
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
/**
|
||||
*
|
||||
* (c) Copyright Ascensio System SIA 2023
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package utils;
|
||||
|
||||
public enum ConvertErrorType {
|
||||
EMPTY_ERROR(0, ""),
|
||||
CONVERTATION_UNKNOWN(-1, "Error convertation unknown"),
|
||||
CONVERTATION_TIMEOUT(-2, "Error convertation timeout"),
|
||||
CONVERTATION_ERROR(-3, "Error convertation error"),
|
||||
DOWNLOAD_ERROR(-4, "Error download error"),
|
||||
UNEXPECTED_GUID_ERROR(-5, "Error unexpected guid"),
|
||||
DATABASE_ERROR(-6, "Error database"),
|
||||
DOCUMENT_REQUEST_ERROR(-7, "Error document request"),
|
||||
DOCUMENT_VKEY_ERROR(-8, "Error document VKey");
|
||||
|
||||
private final int code;
|
||||
private final String label;
|
||||
|
||||
ConvertErrorType(final int codeParam, final String labelParam) {
|
||||
this.code = codeParam;
|
||||
this.label = labelParam;
|
||||
}
|
||||
|
||||
public static String labelOfCode(final int code) {
|
||||
for (ConvertErrorType convertErrorType : values()) {
|
||||
if (convertErrorType.code == code) {
|
||||
return convertErrorType.label;
|
||||
}
|
||||
}
|
||||
return "ErrorCode = " + code;
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,37 @@
|
||||
/**
|
||||
*
|
||||
* (c) Copyright Ascensio System SIA 2023
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package utils;
|
||||
|
||||
public enum StatusType {
|
||||
|
||||
EDITING(1),
|
||||
MUST_SAVE(2),
|
||||
CORRUPTED(3),
|
||||
MUST_FORCE_SAVE(6),
|
||||
CORRUPTED_FORCE_SAVE(7);
|
||||
private final int code;
|
||||
|
||||
StatusType(final int codeParam) {
|
||||
this.code = codeParam;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user