mirror of
https://github.com/ONLYOFFICE/document-server-integration.git
synced 2026-04-07 14:06:11 +08:00
java: added comments
This commit is contained in:
@ -39,6 +39,7 @@ import helpers.FileUtility;
|
||||
@WebServlet(name = "EditorServlet", urlPatterns = {"/EditorServlet"})
|
||||
public class EditorServlet extends HttpServlet
|
||||
{
|
||||
// process request
|
||||
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
DocumentManager.Init(request, response);
|
||||
@ -47,6 +48,7 @@ public class EditorServlet extends HttpServlet
|
||||
String fileExt = request.getParameter("fileExt");
|
||||
String sample = request.getParameter("sample");
|
||||
|
||||
// check if there is sample data in the request
|
||||
Boolean sampleData = (sample == null || sample.isEmpty()) ? false : sample.toLowerCase().equals("true");
|
||||
|
||||
CookieManager cm = new CookieManager(request);
|
||||
@ -55,8 +57,9 @@ public class EditorServlet extends HttpServlet
|
||||
{
|
||||
try
|
||||
{
|
||||
// create demo document
|
||||
fileName = DocumentManager.CreateDemo(fileExt, sampleData, cm.getCookie("uid"), cm.getCookie("uname"));
|
||||
response.sendRedirect("EditorServlet?fileName=" + URLEncoder.encode(fileName, "UTF-8"));
|
||||
response.sendRedirect("EditorServlet?fileName=" + URLEncoder.encode(fileName, "UTF-8")); // redirect the request
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
@ -65,27 +68,33 @@ public class EditorServlet extends HttpServlet
|
||||
}
|
||||
}
|
||||
|
||||
// create file model (get all the necessary parameters from cookies)
|
||||
FileModel file = new FileModel(fileName, cm.getCookie("ulang"), cm.getCookie("uid"), cm.getCookie("uname"), request.getParameter("actionLink"));
|
||||
// change type parameter if needed
|
||||
file.changeType(request.getParameter("mode"), request.getParameter("type"));
|
||||
|
||||
// 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");
|
||||
|
||||
// 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");
|
||||
|
||||
// recipients data for mail merging
|
||||
Map<String, Object> dataMailMergeRecipients = new HashMap<>();
|
||||
dataMailMergeRecipients.put("fileType", "csv");
|
||||
dataMailMergeRecipients.put("url", DocumentManager.GetServerUrl(true) + "/IndexServlet?type=csv");
|
||||
|
||||
// check if the document token is enabled
|
||||
if (DocumentManager.TokenEnabled())
|
||||
{
|
||||
file.BuildToken();
|
||||
dataInsertImage.put("token", DocumentManager.CreateToken(dataInsertImage));
|
||||
dataCompareFile.put("token", DocumentManager.CreateToken(dataCompareFile));
|
||||
dataMailMergeRecipients.put("token", DocumentManager.CreateToken(dataMailMergeRecipients));
|
||||
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
|
||||
}
|
||||
|
||||
Gson gson = new Gson();
|
||||
@ -97,18 +106,21 @@ public class EditorServlet extends HttpServlet
|
||||
request.getRequestDispatcher("editor.jsp").forward(request, response);
|
||||
}
|
||||
|
||||
// create get request
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
processRequest(request, response);
|
||||
}
|
||||
|
||||
// create post request
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
processRequest(request, response);
|
||||
}
|
||||
|
||||
// get servlet information
|
||||
@Override
|
||||
public String getServletInfo()
|
||||
{
|
||||
|
||||
@ -32,12 +32,14 @@ import javax.servlet.ServletContextListener;
|
||||
|
||||
public class GlobalServletContextListener implements ServletContextListener
|
||||
{
|
||||
// destroy ServletContextListener interface
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent arg0)
|
||||
{
|
||||
System.out.println("ServletContextListener destroyed");
|
||||
}
|
||||
|
||||
// start ServletContextListener interface
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent arg0)
|
||||
{
|
||||
@ -45,17 +47,20 @@ public class GlobalServletContextListener implements ServletContextListener
|
||||
{
|
||||
new X509TrustManager()
|
||||
{
|
||||
// return an array of certificates which are trusted
|
||||
@Override
|
||||
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)
|
||||
{
|
||||
}
|
||||
|
||||
// check whether the X509 certificate chain can be validated and is trusted for server authentication
|
||||
@Override
|
||||
public void checkServerTrusted(X509Certificate[] certs, String authType)
|
||||
{
|
||||
@ -67,6 +72,7 @@ public class GlobalServletContextListener implements ServletContextListener
|
||||
|
||||
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());
|
||||
@ -75,6 +81,7 @@ public class GlobalServletContextListener implements ServletContextListener
|
||||
{
|
||||
}
|
||||
|
||||
// create all-trusting host name verifier
|
||||
HostnameVerifier allHostsValid = new HostnameVerifier()
|
||||
{
|
||||
@Override
|
||||
@ -84,6 +91,7 @@ public class GlobalServletContextListener implements ServletContextListener
|
||||
}
|
||||
};
|
||||
|
||||
// install the all-trusting host verifier
|
||||
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
|
||||
|
||||
System.out.println("ServletContextListener started");
|
||||
|
||||
@ -46,17 +46,20 @@ public class IndexServlet extends HttpServlet
|
||||
{
|
||||
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
// get the type parameter from the request
|
||||
String action = request.getParameter("type");
|
||||
|
||||
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();
|
||||
PrintWriter writer = response.getWriter(); // create a variable to display information about the application and error messages
|
||||
|
||||
// define functions for each type of operation
|
||||
switch (action.toLowerCase())
|
||||
{
|
||||
case "upload":
|
||||
@ -86,6 +89,7 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
|
||||
|
||||
// upload a file
|
||||
private static void Upload(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
response.setContentType("text/plain");
|
||||
@ -94,6 +98,7 @@ public class IndexServlet extends HttpServlet
|
||||
{
|
||||
Part httpPostedFile = request.getPart("file");
|
||||
|
||||
// get file name from the content-disposition response header
|
||||
String fileName = "";
|
||||
for (String content : httpPostedFile.getHeader("content-disposition").split(";"))
|
||||
{
|
||||
@ -103,24 +108,24 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
}
|
||||
|
||||
long curSize = httpPostedFile.getSize();
|
||||
if (DocumentManager.GetMaxFileSize() < curSize || curSize <= 0)
|
||||
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\"}");
|
||||
writer.write("{ \"error\": \"File size is incorrect\"}"); // if so, write the error status and message to the response
|
||||
return;
|
||||
}
|
||||
|
||||
String curExt = FileUtility.GetFileExtension(fileName);
|
||||
if (!DocumentManager.GetFileExts().contains(curExt))
|
||||
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\"}");
|
||||
writer.write("{ \"error\": \"File type is not supported\"}"); // if not, write the error status and message to the response
|
||||
return;
|
||||
}
|
||||
|
||||
InputStream fileStream = httpPostedFile.getInputStream();
|
||||
InputStream fileStream = httpPostedFile.getInputStream(); // get input file stream
|
||||
|
||||
fileName = DocumentManager.GetCorrectName(fileName, null);
|
||||
String fileStoragePath = DocumentManager.StoragePath(fileName, null);
|
||||
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();
|
||||
|
||||
File file = new File(fileStoragePath);
|
||||
@ -131,12 +136,14 @@ public class IndexServlet extends HttpServlet
|
||||
final byte[] bytes = new byte[1024];
|
||||
while ((read = fileStream.read(bytes)) != -1)
|
||||
{
|
||||
out.write(bytes, 0, read);
|
||||
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();
|
||||
}
|
||||
|
||||
// create meta information with the user id and name specified
|
||||
CookieManager cm = new CookieManager(request);
|
||||
DocumentManager.CreateMeta(fileName, cm.getCookie("uid"), cm.getCookie("uname"), null);
|
||||
|
||||
@ -149,6 +156,7 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
}
|
||||
|
||||
// convert a file
|
||||
private static void Convert(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
response.setContentType("text/plain");
|
||||
@ -170,10 +178,13 @@ public class IndexServlet extends HttpServlet
|
||||
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))
|
||||
{
|
||||
// generate document key
|
||||
String key = ServiceConverter.GenerateRevisionId(fileUri);
|
||||
|
||||
// get the url to the converted file
|
||||
String newFileUri = ServiceConverter.GetConvertedUri(fileUri, fileExt, internalFileExt, key, filePass, true);
|
||||
|
||||
if (newFileUri.isEmpty())
|
||||
@ -182,11 +193,12 @@ public class IndexServlet extends HttpServlet
|
||||
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);
|
||||
|
||||
URL url = new URL(newFileUri);
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
|
||||
InputStream stream = connection.getInputStream();
|
||||
InputStream stream = connection.getInputStream(); // get input stream of the converted file
|
||||
|
||||
if (stream == null)
|
||||
{
|
||||
@ -200,20 +212,22 @@ public class IndexServlet extends HttpServlet
|
||||
final byte[] bytes = new byte[1024];
|
||||
while ((read = stream.read(bytes)) != -1)
|
||||
{
|
||||
out.write(bytes, 0, read);
|
||||
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();
|
||||
|
||||
//remove source file ?
|
||||
//File sourceFile = new File(DocumentManager.StoragePath(fileName, null));
|
||||
//sourceFile.delete();
|
||||
// remove source file ?
|
||||
// File sourceFile = new File(DocumentManager.StoragePath(fileName, null));
|
||||
// sourceFile.delete();
|
||||
|
||||
fileName = correctName;
|
||||
|
||||
// create meta information about the converted file with the user id and name specified
|
||||
CookieManager cm = new CookieManager(request);
|
||||
DocumentManager.CreateMeta(fileName, cm.getCookie("uid"), cm.getCookie("uname"), null);
|
||||
}
|
||||
@ -227,10 +241,12 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
}
|
||||
|
||||
// track file changes
|
||||
private static void Track(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
JSONObject body = null;
|
||||
|
||||
// read request body
|
||||
try {
|
||||
body = TrackManager.readBody(request, writer);
|
||||
} catch (Exception e) {
|
||||
@ -238,19 +254,20 @@ public class IndexServlet extends HttpServlet
|
||||
return;
|
||||
}
|
||||
|
||||
// get status from the request body
|
||||
int status = Math.toIntExact((long) body.get("status"));
|
||||
int saved = 0;
|
||||
|
||||
if (status == 1) { //Editing
|
||||
if (status == 1) { // editing
|
||||
JSONArray actions = (JSONArray) body.get("actions");
|
||||
JSONArray users = (JSONArray) body.get("users");
|
||||
JSONObject action = (JSONObject) actions.get(0);
|
||||
if (actions != null && action.get("type").toString().equals("0")) { //finished edit
|
||||
String user = (String) action.get("userid");
|
||||
if (actions != null && action.get("type").toString().equals("0")) { // finished edit
|
||||
String user = (String) action.get("userid"); // the user who finished editing
|
||||
if (users.indexOf(user) == -1) {
|
||||
String key = (String) body.get("key");
|
||||
try {
|
||||
TrackManager.commandRequest("forcesave", key);
|
||||
TrackManager.commandRequest("forcesave", key); // create a command request with the forcesave method
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@ -261,7 +278,7 @@ public class IndexServlet extends HttpServlet
|
||||
String userAddress = request.getParameter("userAddress");
|
||||
String fileName = FileUtility.GetFileName(request.getParameter("fileName"));
|
||||
|
||||
if (status == 2 || status == 3) { //MustSave, Corrupted
|
||||
if (status == 2 || status == 3) { // MustSave, Corrupted
|
||||
try {
|
||||
TrackManager.processSave(body, fileName, userAddress);
|
||||
} catch (Exception ex) {
|
||||
@ -271,7 +288,7 @@ public class IndexServlet extends HttpServlet
|
||||
|
||||
}
|
||||
|
||||
if (status == 6 || status == 7) { //MustForceSave, CorruptedForceSave
|
||||
if (status == 6 || status == 7) { // MustForceSave, CorruptedForceSave
|
||||
try {
|
||||
TrackManager.processForceSave(body, fileName, userAddress);
|
||||
} catch (Exception ex) {
|
||||
@ -283,6 +300,7 @@ public class IndexServlet extends HttpServlet
|
||||
writer.write("{\"error\":" + saved + "}");
|
||||
}
|
||||
|
||||
// remove a file
|
||||
private static void Remove(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
try
|
||||
@ -290,9 +308,11 @@ public class IndexServlet extends HttpServlet
|
||||
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));
|
||||
delete(hist);
|
||||
|
||||
@ -304,6 +324,7 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
}
|
||||
|
||||
// get files information
|
||||
private static void Files(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
ArrayList<Map<String, Object>> files = null;
|
||||
@ -313,10 +334,10 @@ public class IndexServlet extends HttpServlet
|
||||
response.setContentType("application/json");
|
||||
|
||||
if (request.getParameter("fileId") == null) {
|
||||
files = DocumentManager.GetFilesInfo();
|
||||
files = DocumentManager.GetFilesInfo(); // get the information about the files from the storage path
|
||||
writer.write(gson.toJson(files));
|
||||
}else {
|
||||
String fileId = request.getParameter("fileId");
|
||||
String fileId = request.getParameter("fileId"); // get file id from the request
|
||||
files = DocumentManager.GetFilesInfo(fileId);
|
||||
if(files.isEmpty()) {
|
||||
writer.write("\"File not found\"");
|
||||
@ -331,6 +352,7 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
}
|
||||
|
||||
// download a csv file
|
||||
private static void CSV(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
String fileName = "assets/sample/csv.csv";
|
||||
@ -344,6 +366,7 @@ public class IndexServlet extends HttpServlet
|
||||
download(filePath.toString(), response, writer);
|
||||
}
|
||||
|
||||
// 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"));
|
||||
@ -357,13 +380,14 @@ public class IndexServlet extends HttpServlet
|
||||
download(filePath.toString(), response, writer);
|
||||
}
|
||||
|
||||
// download a file
|
||||
private static void Download(HttpServletRequest request, HttpServletResponse response, PrintWriter writer)
|
||||
{
|
||||
try {
|
||||
String fileName = FileUtility.GetFileName(request.getParameter("name"));
|
||||
String filePath = DocumentManager.ForcesavePath(fileName, null, false);
|
||||
String filePath = DocumentManager.ForcesavePath(fileName, null, false); // get the path to the force saved document version
|
||||
if (filePath.equals("")) {
|
||||
filePath = DocumentManager.StoragePath(fileName, null);
|
||||
filePath = DocumentManager.StoragePath(fileName, null); // or to the original document
|
||||
}
|
||||
download(filePath, response, writer);
|
||||
} catch (Exception e) {
|
||||
@ -372,14 +396,16 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
|
||||
private static void delete(File f) throws Exception {
|
||||
// to delete a directory
|
||||
if (f.isDirectory()) {
|
||||
for (File c : f.listFiles())
|
||||
delete(c);
|
||||
for (File c : f.listFiles()) // run through all the files in it
|
||||
delete(c); // and delete them
|
||||
}
|
||||
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) {
|
||||
String fileType = null;
|
||||
try {
|
||||
@ -390,6 +416,7 @@ public class IndexServlet extends HttpServlet
|
||||
|
||||
File file = new File(filePath);
|
||||
|
||||
// set headers to the response
|
||||
response.setHeader("Content-Length", String.valueOf(file.length()));
|
||||
response.setHeader("Content-Type", fileType);
|
||||
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8\'\'" + file.getName());
|
||||
@ -399,7 +426,7 @@ public class IndexServlet extends HttpServlet
|
||||
FileInputStream fileInputStream = new FileInputStream(file);
|
||||
inputStream = new BufferedInputStream(fileInputStream);
|
||||
int readBytes = 0;
|
||||
while ((readBytes = inputStream.read()) != -1)
|
||||
while ((readBytes = inputStream.read()) != -1) // write bytes to the output stream
|
||||
writer.write(readBytes);
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
@ -412,18 +439,21 @@ public class IndexServlet extends HttpServlet
|
||||
}
|
||||
}
|
||||
|
||||
// process get request
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
processRequest(request, response);
|
||||
}
|
||||
|
||||
// process post request
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
|
||||
{
|
||||
processRequest(request, response);
|
||||
}
|
||||
|
||||
// get servlet information
|
||||
@Override
|
||||
public String getServletInfo()
|
||||
{
|
||||
|
||||
@ -41,49 +41,61 @@ public class FileModel
|
||||
public EditorConfig editorConfig;
|
||||
public String token;
|
||||
|
||||
// create file model
|
||||
public FileModel(String fileName, String lang, String uid, String uname, String actionData)
|
||||
{
|
||||
if (fileName == null) fileName = "";
|
||||
fileName = fileName.trim();
|
||||
fileName = fileName.trim(); // remove extra spaces in the file name
|
||||
|
||||
// get file type from the file name (word, cell or slide)
|
||||
documentType = FileUtility.GetFileType(fileName).toString().toLowerCase();
|
||||
|
||||
// set the document parameters
|
||||
document = new Document();
|
||||
document.title = fileName;
|
||||
document.url = DocumentManager.GetFileUri(fileName, true);
|
||||
document.url = DocumentManager.GetFileUri(fileName, true); // get file url
|
||||
document.urlUser = DocumentManager.GetFileUri(fileName, false);
|
||||
document.fileType = FileUtility.GetFileExtension(fileName).replace(".", "");
|
||||
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 = uid != null && !uid.isEmpty() ? uid.equals("uid-2") : null;
|
||||
|
||||
// set the editor config parameters
|
||||
editorConfig = new EditorConfig(actionData);
|
||||
editorConfig.callbackUrl = DocumentManager.GetCallback(fileName);
|
||||
editorConfig.callbackUrl = DocumentManager.GetCallback(fileName); // get callback url
|
||||
editorConfig.createUrl = DocumentManager.GetCreateUrl(FileUtility.GetFileType(fileName));
|
||||
if (lang != null) editorConfig.lang = lang;
|
||||
if (lang != null) editorConfig.lang = lang; // write language parameter to the config
|
||||
|
||||
// write user information to the config (id, name and group)
|
||||
if (uid != null) editorConfig.user.id = uid;
|
||||
if (uname != null) editorConfig.user.name = uid.equals("uid-0") ? null : uname;
|
||||
if (editorConfig.user.id.equals("uid-2")) editorConfig.user.group = "group-2";
|
||||
if (editorConfig.user.id.equals("uid-3")) editorConfig.user.group = "group-3";
|
||||
|
||||
// write the absolute URL to the file location
|
||||
editorConfig.customization.goback.url = DocumentManager.GetServerUrl(false) + "/IndexServlet";
|
||||
|
||||
changeType(mode, type);
|
||||
}
|
||||
|
||||
// change the document type
|
||||
public void changeType(String _mode, String _type)
|
||||
{
|
||||
if (_mode != null) mode = _mode;
|
||||
if (_type != null) type = _type;
|
||||
|
||||
// check if the file with such an extension can be edited
|
||||
Boolean canEdit = DocumentManager.GetEditedExts().contains(FileUtility.GetFileExtension(document.title));
|
||||
// check if the Submit form button is displayed or not
|
||||
editorConfig.customization.submitForm = canEdit && (mode.equals("edit") || mode.equals("fillForms"));
|
||||
// set the mode parameter: change it to view if the document can't be edited
|
||||
editorConfig.mode = canEdit && !mode.equals("view") ? "edit" : "view";
|
||||
|
||||
// set document permissions
|
||||
document.permissions = new Permissions(mode, type, canEdit);
|
||||
|
||||
if (type.equals("embedded")) InitDesktop();
|
||||
if (type.equals("embedded")) InitDesktop(); // set parameters for the embedded document
|
||||
}
|
||||
|
||||
public void InitDesktop()
|
||||
@ -91,44 +103,50 @@ public class FileModel
|
||||
editorConfig.InitDesktop(document.urlUser);
|
||||
}
|
||||
|
||||
// generate document token
|
||||
public void BuildToken()
|
||||
{
|
||||
// write all the necessary document parameters to the map
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("type", type);
|
||||
map.put("documentType", documentType);
|
||||
map.put("document", document);
|
||||
map.put("editorConfig", editorConfig);
|
||||
|
||||
// and create token from them
|
||||
token = DocumentManager.CreateToken(map);
|
||||
}
|
||||
|
||||
// get document history
|
||||
public String[] GetHistory()
|
||||
{
|
||||
JSONParser parser = new JSONParser();
|
||||
String histDir = DocumentManager.HistoryDir(DocumentManager.StoragePath(document.title, null));
|
||||
String histDir = DocumentManager.HistoryDir(DocumentManager.StoragePath(document.title, null)); // get history directory
|
||||
if (DocumentManager.GetFileVersion(histDir) > 0) {
|
||||
Integer curVer = DocumentManager.GetFileVersion(histDir);
|
||||
Integer curVer = DocumentManager.GetFileVersion(histDir); // get current file version if it is greater than 0
|
||||
|
||||
List<Object> hist = new ArrayList<>();
|
||||
Map<String, Object> histData = new HashMap<String, Object>();
|
||||
|
||||
for (Integer i = 1; i <= curVer; i++) {
|
||||
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);
|
||||
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"));
|
||||
|
||||
obj.put("key", key);
|
||||
obj.put("version", i);
|
||||
|
||||
if (i == 1) {
|
||||
String createdInfo = readFileToEnd(new File(histDir + File.separator + "createdInfo.json"));
|
||||
JSONObject json = (JSONObject) parser.parse(createdInfo);
|
||||
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
|
||||
JSONObject json = (JSONObject) parser.parse(createdInfo); // and turn it into json object
|
||||
|
||||
// write meta information to the object (user information and creation date)
|
||||
obj.put("created", json.get("created"));
|
||||
Map<String, Object> user = new HashMap<String, Object>();
|
||||
user.put("id", json.get("id"));
|
||||
@ -140,20 +158,23 @@ public class FileModel
|
||||
dataObj.put("url", i == curVer ? document.url : DocumentManager.GetPathUri(verDir + File.separator + "prev" + FileUtility.GetFileExtension(document.title)));
|
||||
dataObj.put("version", i);
|
||||
|
||||
if (i > 1) {
|
||||
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 change = (JSONObject) ((JSONArray) changes.get("changes")).get(0);
|
||||
|
||||
// write information about changes to the object
|
||||
obj.put("changes", changes.get("changes"));
|
||||
obj.put("serverVersion", changes.get("serverVersion"));
|
||||
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));
|
||||
Map<String, Object> prev = (Map<String, Object>) histData.get(Integer.toString(i - 2)); // get the history data from the previous file version
|
||||
Map<String, Object> prevInfo = new HashMap<String, Object>();
|
||||
prevInfo.put("key", prev.get("key"));
|
||||
prevInfo.put("key", prev.get("key")); // write key and url information about previous file version
|
||||
prevInfo.put("url", prev.get("url"));
|
||||
dataObj.put("previous", prevInfo);
|
||||
dataObj.put("previous", prevInfo); // write information about previous file version to the data object
|
||||
// write the path to the diff.zip archive with differences in this file version
|
||||
dataObj.put("changesUrl", DocumentManager.GetPathUri(DocumentManager.VersionDir(histDir, i - 1) + File.separator + "diff.zip"));
|
||||
}
|
||||
|
||||
@ -168,6 +189,7 @@ public class FileModel
|
||||
} catch (Exception ex) { }
|
||||
}
|
||||
|
||||
// write history information about the current file version to the history object
|
||||
Map<String, Object> histObj = new HashMap<String, Object>();
|
||||
histObj.put("currentVersion", curVer);
|
||||
histObj.put("history", hist);
|
||||
@ -178,12 +200,13 @@ public class FileModel
|
||||
return new String[] { "", "" };
|
||||
}
|
||||
|
||||
// read a file
|
||||
private String readFileToEnd(File file) {
|
||||
String output = "";
|
||||
try {
|
||||
try(FileInputStream is = new FileInputStream(file))
|
||||
{
|
||||
Scanner scanner = new Scanner(is);
|
||||
Scanner scanner = new Scanner(is); // read data from the source
|
||||
scanner.useDelimiter("\\A");
|
||||
while (scanner.hasNext()) {
|
||||
output += scanner.next();
|
||||
@ -194,6 +217,7 @@ public class FileModel
|
||||
return output;
|
||||
}
|
||||
|
||||
// the document parameters
|
||||
public class Document
|
||||
{
|
||||
public String title;
|
||||
@ -205,6 +229,7 @@ public class FileModel
|
||||
public Permissions permissions;
|
||||
}
|
||||
|
||||
// the permissions parameters
|
||||
public class Permissions
|
||||
{
|
||||
public Boolean comment;
|
||||
@ -216,6 +241,7 @@ public class FileModel
|
||||
public Boolean review;
|
||||
public List<String> reviewGroups;
|
||||
|
||||
// defines what can be done with a document
|
||||
public Permissions(String mode, String type, Boolean canEdit)
|
||||
{
|
||||
comment = !mode.equals("view") && !mode.equals("fillForms") && !mode.equals("embedded") && !mode.equals("blockcontent");
|
||||
@ -228,6 +254,7 @@ public class FileModel
|
||||
reviewGroups = editorConfig.user.group != null ? GetReviewGroups(editorConfig.user.group) : null;
|
||||
}
|
||||
|
||||
// defines the list of groups whose documents the user can review
|
||||
private List<String> GetReviewGroups(String group){
|
||||
Map<String, List<String>> reviewGroups = new HashMap<>();
|
||||
|
||||
@ -238,11 +265,13 @@ public class FileModel
|
||||
}
|
||||
}
|
||||
|
||||
// the Favorite icon state
|
||||
public class Info
|
||||
{
|
||||
Boolean favorite;
|
||||
}
|
||||
|
||||
// the editor config parameters
|
||||
public class EditorConfig
|
||||
{
|
||||
public HashMap<String, Object> actionLink = null;
|
||||
@ -256,6 +285,7 @@ public class FileModel
|
||||
|
||||
public EditorConfig(String actionData)
|
||||
{
|
||||
// get the action in the document that will be scrolled to (bookmark or comment)
|
||||
if (actionData != null) {
|
||||
Gson gson = new Gson();
|
||||
actionLink = gson.fromJson(actionData, new TypeToken<HashMap<String, Object>>() { }.getType());
|
||||
@ -264,15 +294,17 @@ public class FileModel
|
||||
customization = new Customization();
|
||||
}
|
||||
|
||||
// set parameters for the embedded document
|
||||
public void InitDesktop(String url)
|
||||
{
|
||||
embedded = new Embedded();
|
||||
embedded.saveUrl = url;
|
||||
embedded.embedUrl = url;
|
||||
embedded.shareUrl = url;
|
||||
embedded.toolbarDocked = "top";
|
||||
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
|
||||
}
|
||||
|
||||
// default user parameters (id, name and group)
|
||||
public class User
|
||||
{
|
||||
public String id = "uid-1";
|
||||
@ -280,6 +312,7 @@ public class FileModel
|
||||
public String group = null;
|
||||
}
|
||||
|
||||
// customization parameters
|
||||
public class Customization
|
||||
{
|
||||
public Goback goback;
|
||||
@ -298,6 +331,7 @@ public class FileModel
|
||||
}
|
||||
}
|
||||
|
||||
// parameters for embedded document
|
||||
public class Embedded
|
||||
{
|
||||
public String saveUrl;
|
||||
@ -308,6 +342,7 @@ public class FileModel
|
||||
}
|
||||
|
||||
|
||||
// turn java objects into json strings
|
||||
public static String Serialize(FileModel model)
|
||||
{
|
||||
Gson gson = new Gson();
|
||||
|
||||
@ -34,6 +34,7 @@ public class ConfigManager
|
||||
{
|
||||
try
|
||||
{
|
||||
// get stream from the settings.properties resource and load it
|
||||
properties = new Properties();
|
||||
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("settings.properties");
|
||||
properties.load(stream);
|
||||
@ -44,6 +45,7 @@ public class ConfigManager
|
||||
}
|
||||
}
|
||||
|
||||
// get name from the settings.properties file
|
||||
public static String GetProperty(String name)
|
||||
{
|
||||
if (properties == null)
|
||||
@ -51,6 +53,7 @@ public class ConfigManager
|
||||
return "";
|
||||
}
|
||||
|
||||
// get property by its name
|
||||
String property = properties.getProperty(name);
|
||||
|
||||
return property == null ? "" : property;
|
||||
|
||||
@ -31,14 +31,15 @@ public class CookieManager {
|
||||
public CookieManager(HttpServletRequest request) throws UnsupportedEncodingException {
|
||||
cookiesMap = new HashMap<String, String>();
|
||||
|
||||
Cookie[] cookies = request.getCookies();
|
||||
Cookie[] cookies = request.getCookies(); // get all the cookies from the request
|
||||
if (cookies != null) {
|
||||
for (Cookie cookie : cookies) {
|
||||
cookiesMap.putIfAbsent(cookie.getName(), URLDecoder.decode(cookie.getValue(), "UTF-8"));
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// get cookie by its name
|
||||
public String getCookie(String name) {
|
||||
return cookiesMap.get(name);
|
||||
}
|
||||
|
||||
@ -50,6 +50,7 @@ public class DocumentManager
|
||||
request = req;
|
||||
}
|
||||
|
||||
// get max file size
|
||||
public static long GetMaxFileSize()
|
||||
{
|
||||
long size;
|
||||
@ -66,6 +67,7 @@ public class DocumentManager
|
||||
return size > 0 ? size : 5 * 1024 * 1024;
|
||||
}
|
||||
|
||||
// get all the supported file extensions
|
||||
public static List<String> GetFileExts()
|
||||
{
|
||||
List<String> res = new ArrayList<>();
|
||||
@ -77,30 +79,35 @@ public class DocumentManager
|
||||
return res;
|
||||
}
|
||||
|
||||
// get file extensions that can be viewed
|
||||
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");
|
||||
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");
|
||||
return Arrays.asList(exts.split("\\|"));
|
||||
}
|
||||
|
||||
// get current user host address
|
||||
public static String CurUserHostAddress(String userAddress)
|
||||
{
|
||||
if(userAddress == 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)
|
||||
@ -112,40 +119,47 @@ public class DocumentManager
|
||||
return userAddress.replaceAll("[^0-9a-zA-Z.=]", "_");
|
||||
}
|
||||
|
||||
// get the root directory of the user host
|
||||
public static String FilesRootPath(String userAddress)
|
||||
{
|
||||
String hostAddress = CurUserHostAddress(userAddress);
|
||||
String serverPath = request.getSession().getServletContext().getRealPath("");
|
||||
String storagePath = ConfigManager.GetProperty("storage-folder");
|
||||
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 directory = serverPath + storagePath + File.separator + hostAddress + File.separator;
|
||||
|
||||
File file = new File(directory);
|
||||
|
||||
// if the root directory doesn't exist
|
||||
if (!file.exists())
|
||||
{
|
||||
// create it
|
||||
file.mkdirs();
|
||||
}
|
||||
|
||||
return directory;
|
||||
}
|
||||
|
||||
// get the storage path of the file
|
||||
public static String StoragePath(String fileName, String userAddress)
|
||||
{
|
||||
String directory = FilesRootPath(userAddress);
|
||||
return directory + FileUtility.GetFileName(fileName);
|
||||
}
|
||||
|
||||
// get the path to the forcesaved file version
|
||||
public static String ForcesavePath(String fileName, String userAddress, Boolean create)
|
||||
{
|
||||
String hostAddress = CurUserHostAddress(userAddress);
|
||||
String serverPath = request.getSession().getServletContext().getRealPath("");
|
||||
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 "";
|
||||
|
||||
// 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 "";
|
||||
@ -161,42 +175,48 @@ public class DocumentManager
|
||||
return directory;
|
||||
}
|
||||
|
||||
// get the history directory
|
||||
public static String HistoryDir(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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
// get the file version by the history path
|
||||
public static Integer GetFileVersion(String historyPath)
|
||||
{
|
||||
File dir = new File(historyPath);
|
||||
|
||||
if (!dir.exists()) return 0;
|
||||
if (!dir.exists()) return 0; // if the history path doesn't exist, then the file version is 0
|
||||
|
||||
File[] dirs = dir.listFiles(new FileFilter() {
|
||||
File[] dirs = dir.listFiles(new FileFilter() { // take only directories from the history folder
|
||||
@Override
|
||||
public boolean accept(File pathname) {
|
||||
return pathname.isDirectory();
|
||||
}
|
||||
});
|
||||
|
||||
return dirs.length + 1;
|
||||
return dirs.length + 1; // count the directories
|
||||
}
|
||||
|
||||
// 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)));
|
||||
}
|
||||
|
||||
// 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);
|
||||
@ -205,22 +225,24 @@ public class DocumentManager
|
||||
|
||||
File file = new File(StoragePath(name, userAddress));
|
||||
|
||||
for (int i = 1; file.exists(); i++)
|
||||
for (int i = 1; file.exists(); i++) // run through all the files with such a name in the storage directory
|
||||
{
|
||||
name = baseName + " (" + i + ")" + ext;
|
||||
name = baseName + " (" + i + ")" + ext; // and add an index to the base name
|
||||
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));
|
||||
|
||||
File dir = new File(histDir);
|
||||
File dir = new File(histDir); // create history directory
|
||||
dir.mkdir();
|
||||
|
||||
// create json object and put there file information (creation time, user id and name)
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("created", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
|
||||
json.put("id", (uid == null || uid.isEmpty()) ? "uid-1" : uid);
|
||||
@ -230,18 +252,20 @@ public class DocumentManager
|
||||
json.put("name", (uname == null || uname.isEmpty()) ? "John Smith" : uname);
|
||||
}
|
||||
|
||||
// create createdInfo.json file with meta information in the history directory
|
||||
File meta = new File(histDir + File.separator + "createdInfo.json");
|
||||
try (FileWriter writer = new FileWriter(meta)) {
|
||||
json.writeJSONString(writer);
|
||||
json.writeJSONString(writer); // write information from the json object into this file
|
||||
}
|
||||
}
|
||||
|
||||
// get all the stored files from the user host address
|
||||
public static File[] GetStoredFiles(String userAddress)
|
||||
{
|
||||
String directory = FilesRootPath(userAddress);
|
||||
|
||||
File file = new File(directory);
|
||||
return file.listFiles(new FileFilter() {
|
||||
return file.listFiles(new FileFilter() { // take only files from the root directory
|
||||
@Override
|
||||
public boolean accept(File pathname) {
|
||||
return pathname.isFile();
|
||||
@ -249,13 +273,14 @@ public class DocumentManager
|
||||
});
|
||||
}
|
||||
|
||||
// create demo document
|
||||
public static String CreateDemo(String fileExt, Boolean sample, String uid, String uname) throws Exception
|
||||
{
|
||||
String demoName = (sample ? "sample." : "new.") + fileExt;
|
||||
String demoPath = "assets" + File.separator + (sample ? "sample" : "new") + File.separator;
|
||||
String fileName = GetCorrectName(demoName, null);
|
||||
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
|
||||
|
||||
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(demoPath + demoName);
|
||||
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(demoPath + demoName); // get the input file stream
|
||||
|
||||
File file = new File(StoragePath(fileName, null));
|
||||
|
||||
@ -265,16 +290,19 @@ public class DocumentManager
|
||||
final byte[] bytes = new byte[1024];
|
||||
while ((read = stream.read(bytes)) != -1)
|
||||
{
|
||||
out.write(bytes, 0, read);
|
||||
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();
|
||||
}
|
||||
|
||||
// create meta information of the demo file
|
||||
CreateMeta(fileName, uid, uname, null);
|
||||
|
||||
return fileName;
|
||||
}
|
||||
|
||||
// get file url
|
||||
public static String GetFileUri(String fileName, Boolean forDocumentServer)
|
||||
{
|
||||
try
|
||||
@ -293,11 +321,13 @@ public class DocumentManager
|
||||
}
|
||||
}
|
||||
|
||||
// get file information
|
||||
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)){
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
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");
|
||||
@ -310,6 +340,7 @@ public class DocumentManager
|
||||
return files;
|
||||
}
|
||||
|
||||
// get file information by its id
|
||||
public static ArrayList<Map<String, Object>> GetFilesInfo(String fileId){
|
||||
ArrayList<Map<String, Object>> file = new ArrayList<>();
|
||||
|
||||
@ -323,6 +354,7 @@ public class DocumentManager
|
||||
return file;
|
||||
}
|
||||
|
||||
// get the path url
|
||||
public static String GetPathUri(String path)
|
||||
{
|
||||
String serverPath = GetServerUrl(true);
|
||||
@ -335,6 +367,7 @@ public class DocumentManager
|
||||
}
|
||||
|
||||
|
||||
// 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");
|
||||
@ -343,6 +376,7 @@ public class DocumentManager
|
||||
}
|
||||
}
|
||||
|
||||
// get the callback url
|
||||
public static String GetCallback(String fileName)
|
||||
{
|
||||
String serverPath = GetServerUrl(true);
|
||||
@ -367,31 +401,38 @@ public class DocumentManager
|
||||
return serverPath + "/EditorServlet" + query;
|
||||
}
|
||||
|
||||
// get an editor internal extension
|
||||
public static String GetInternalExtension(FileType fileType)
|
||||
{
|
||||
// .docx for word file type
|
||||
if (fileType.equals(FileType.Word))
|
||||
return ".docx";
|
||||
|
||||
// .xlsx for cell file type
|
||||
if (fileType.equals(FileType.Cell))
|
||||
return ".xlsx";
|
||||
|
||||
// .pptx for slide file type
|
||||
if (fileType.equals(FileType.Slide))
|
||||
return ".pptx";
|
||||
|
||||
// the default file type is .docx
|
||||
return ".docx";
|
||||
}
|
||||
|
||||
// create document token
|
||||
public static String CreateToken(Map<String, Object> payloadClaims)
|
||||
{
|
||||
try
|
||||
{
|
||||
// build a HMAC signer using a SHA-256 hash
|
||||
Signer signer = HMACSigner.newSHA256Signer(GetTokenSecret());
|
||||
JWT jwt = new JWT();
|
||||
for (String key : payloadClaims.keySet())
|
||||
for (String key : payloadClaims.keySet()) // run through all the keys from the payload
|
||||
{
|
||||
jwt.addClaim(key, payloadClaims.get(key));
|
||||
jwt.addClaim(key, payloadClaims.get(key)); // and write each claim to the jwt
|
||||
}
|
||||
return JWT.getEncoder().encode(jwt, signer);
|
||||
return JWT.getEncoder().encode(jwt, signer); // sign and encode the JWT to a JSON string representation
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@ -399,12 +440,14 @@ public class DocumentManager
|
||||
}
|
||||
}
|
||||
|
||||
// read document token
|
||||
public static JWT ReadToken(String token)
|
||||
{
|
||||
try
|
||||
{
|
||||
// build a HMAC verifier using the token secret
|
||||
Verifier verifier = HMACVerifier.newVerifier(GetTokenSecret());
|
||||
return JWT.getDecoder().decode(token, verifier);
|
||||
return JWT.getDecoder().decode(token, verifier); // verify and decode the encoded string JWT to a rich object
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
@ -412,12 +455,14 @@ public class DocumentManager
|
||||
}
|
||||
}
|
||||
|
||||
// check if the token is enabled
|
||||
public static Boolean TokenEnabled()
|
||||
{
|
||||
String secret = GetTokenSecret();
|
||||
return secret != null && !secret.isEmpty();
|
||||
}
|
||||
|
||||
// get token secret from the config parameters
|
||||
private static String GetTokenSecret()
|
||||
{
|
||||
return ConfigManager.GetProperty("files.docservice.secret");
|
||||
|
||||
@ -29,22 +29,28 @@ public class FileUtility
|
||||
{
|
||||
static {}
|
||||
|
||||
// get file type
|
||||
public static FileType GetFileType(String fileName)
|
||||
{
|
||||
String ext = GetFileExtension(fileName).toLowerCase();
|
||||
|
||||
// word type for document extensions
|
||||
if (ExtsDocument.contains(ext))
|
||||
return FileType.Word;
|
||||
|
||||
// cell type for spreadsheet extensions
|
||||
if (ExtsSpreadsheet.contains(ext))
|
||||
return FileType.Cell;
|
||||
|
||||
// slide type for presentation extensions
|
||||
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",
|
||||
@ -54,6 +60,7 @@ public class FileUtility
|
||||
".pdf", ".djvu", ".fb2", ".epub", ".xps"
|
||||
);
|
||||
|
||||
// spreadsheet extensions
|
||||
public static List<String> ExtsSpreadsheet = Arrays.asList
|
||||
(
|
||||
".xls", ".xlsx", ".xlsm",
|
||||
@ -61,6 +68,7 @@ public class FileUtility
|
||||
".ods", ".fods", ".ots", ".csv"
|
||||
);
|
||||
|
||||
// presentation extensions
|
||||
public static List<String> ExtsPresentation = Arrays.asList
|
||||
(
|
||||
".pps", ".ppsx", ".ppsm",
|
||||
@ -70,15 +78,18 @@ public class FileUtility
|
||||
);
|
||||
|
||||
|
||||
// get file name from the url
|
||||
public static String GetFileName(String url)
|
||||
{
|
||||
if (url == null) return "";
|
||||
|
||||
// get file name from the last part of url
|
||||
String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
|
||||
fileName = fileName.split("\\?")[0];
|
||||
return fileName;
|
||||
}
|
||||
|
||||
// get file name without extension
|
||||
public static String GetFileNameWithoutExtension(String url)
|
||||
{
|
||||
String fileName = GetFileName(url);
|
||||
@ -87,6 +98,7 @@ public class FileUtility
|
||||
return fileNameWithoutExt;
|
||||
}
|
||||
|
||||
// get file extension from url
|
||||
public static String GetFileExtension(String url)
|
||||
{
|
||||
String fileName = GetFileName(url);
|
||||
@ -95,14 +107,15 @@ public class FileUtility
|
||||
return fileExt.toLowerCase();
|
||||
}
|
||||
|
||||
// get url parameters
|
||||
public static Map<String, String> GetUrlParams(String url)
|
||||
{
|
||||
try
|
||||
{
|
||||
String query = new URL(url).getQuery();
|
||||
String[] params = query.split("&");
|
||||
String query = new URL(url).getQuery(); // take all the parameters which are placed after ? sign in the file url
|
||||
String[] params = query.split("&"); // parameters are separated by & sign
|
||||
Map<String, String> map = new HashMap<>();
|
||||
for (String param : params)
|
||||
for (String param : params) // write parameters and their values to the map dictionary
|
||||
{
|
||||
String name = param.split("=")[0];
|
||||
String value = param.split("=")[1];
|
||||
|
||||
@ -59,10 +59,11 @@ public class ServiceConverter
|
||||
{
|
||||
try
|
||||
{
|
||||
// get timeout value from the settings.properties
|
||||
int timeout = Integer.parseInt(ConfigManager.GetProperty("files.docservice.timeout"));
|
||||
if (timeout > 0)
|
||||
if (timeout > 0) // if it's greater than 0
|
||||
{
|
||||
ConvertTimeout = timeout;
|
||||
ConvertTimeout = timeout; // assign this value to a convert timeout
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@ -70,17 +71,21 @@ public class ServiceConverter
|
||||
}
|
||||
}
|
||||
|
||||
// get the url of the converted file
|
||||
public static String GetConvertedUri(String documentUri, String fromExtension, String toExtension, String documentRevisionId, String filePass, Boolean isAsync) 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;
|
||||
|
||||
// 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;
|
||||
|
||||
documentRevisionId = GenerateRevisionId(documentRevisionId);
|
||||
documentRevisionId = GenerateRevisionId(documentRevisionId); // create document token
|
||||
|
||||
// write all the necessary parameters to the body object
|
||||
ConvertBody body = new ConvertBody();
|
||||
body.url = documentUri;
|
||||
body.outputtype = toExtension.replace(".", "");
|
||||
@ -104,12 +109,13 @@ public class ServiceConverter
|
||||
if (isAsync)
|
||||
map.put("async", body.async);
|
||||
|
||||
// add token to the body if it is enabled
|
||||
String token = DocumentManager.CreateToken(map);
|
||||
body.token = token;
|
||||
|
||||
Map<String, Object> payloadMap = new HashMap<String, Object>();
|
||||
payloadMap.put("payload", map);
|
||||
headerToken = DocumentManager.CreateToken(payloadMap);
|
||||
payloadMap.put("payload", map); // create payload object
|
||||
headerToken = DocumentManager.CreateToken(payloadMap); // create header token
|
||||
}
|
||||
|
||||
Gson gson = new Gson();
|
||||
@ -117,6 +123,7 @@ public class ServiceConverter
|
||||
|
||||
byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
// specify request parameters
|
||||
URL url = new URL(DocumentConverterUrl);
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
@ -126,6 +133,7 @@ public class ServiceConverter
|
||||
connection.setRequestProperty("Accept", "application/json");
|
||||
connection.setConnectTimeout(ConvertTimeout);
|
||||
|
||||
// write header token to the request
|
||||
if (DocumentManager.TokenEnabled())
|
||||
{
|
||||
connection.setRequestProperty(DocumentJwtHeader.equals("") ? "Authorization" : DocumentJwtHeader, "Bearer " + headerToken);
|
||||
@ -141,6 +149,7 @@ public class ServiceConverter
|
||||
if (stream == null)
|
||||
throw new Exception("Could not get an answer");
|
||||
|
||||
// convert string to json
|
||||
String jsonString = ConvertStreamToString(stream);
|
||||
|
||||
connection.disconnect();
|
||||
@ -148,21 +157,24 @@ public class ServiceConverter
|
||||
return GetResponseUri(jsonString);
|
||||
}
|
||||
|
||||
// generate document key
|
||||
public static String GenerateRevisionId(String expectedKey)
|
||||
{
|
||||
if (expectedKey.length() > 20)
|
||||
expectedKey = Integer.toString(expectedKey.hashCode());
|
||||
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
|
||||
|
||||
String key = expectedKey.replace("[^0-9-.a-zA-Z_=]", "_");
|
||||
|
||||
return key.substring(0, Math.min(key.length(), 20));
|
||||
return key.substring(0, Math.min(key.length(), 20)); // 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:
|
||||
@ -189,53 +201,56 @@ public class ServiceConverter
|
||||
case -1:
|
||||
errorMessage = errorMessageTemplate + "Error convertation unknown";
|
||||
break;
|
||||
case 0:
|
||||
case 0: // if the error code is equal to 0, the error message is empty
|
||||
break;
|
||||
default:
|
||||
errorMessage = "ErrorCode = " + errorCode;
|
||||
errorMessage = "ErrorCode = " + errorCode; // default value for the error message
|
||||
break;
|
||||
}
|
||||
|
||||
throw new Exception(errorMessage);
|
||||
}
|
||||
|
||||
// get the response url
|
||||
private static String GetResponseUri(String jsonString) throws Exception
|
||||
{
|
||||
JSONObject jsonObj = ConvertStringToJSON(jsonString);
|
||||
|
||||
Object error = jsonObj.get("error");
|
||||
if (error != null)
|
||||
ProcessConvertServiceResponceError(Math.toIntExact((long)error));
|
||||
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;
|
||||
String responseUri = null;
|
||||
|
||||
if (isEndConvert)
|
||||
if (isEndConvert) // if the conversion is completed
|
||||
{
|
||||
resultPercent = 100l;
|
||||
responseUri = (String) jsonObj.get("fileUrl");
|
||||
responseUri = (String) jsonObj.get("fileUrl"); // get the file url
|
||||
}
|
||||
else
|
||||
else // if the conversion isn't completed
|
||||
{
|
||||
resultPercent = (Long) jsonObj.get("percent");
|
||||
resultPercent = resultPercent >= 100l ? 99l : resultPercent;
|
||||
resultPercent = resultPercent >= 100l ? 99l : resultPercent; // get the percentage value
|
||||
}
|
||||
|
||||
return resultPercent >= 100l ? responseUri : "";
|
||||
}
|
||||
|
||||
// convert stream to string
|
||||
public static String ConvertStreamToString(InputStream stream) throws IOException
|
||||
{
|
||||
InputStreamReader inputStreamReader = new InputStreamReader(stream);
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
|
||||
String line = bufferedReader.readLine();
|
||||
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
|
||||
String line = bufferedReader.readLine(); // get incoming streams by lines
|
||||
|
||||
while (line != null)
|
||||
{
|
||||
stringBuilder.append(line);
|
||||
stringBuilder.append(line); // concatenate strings using the string builder
|
||||
line = bufferedReader.readLine();
|
||||
}
|
||||
|
||||
@ -244,11 +259,12 @@ public class ServiceConverter
|
||||
return result;
|
||||
}
|
||||
|
||||
// convert string to json
|
||||
public static JSONObject ConvertStringToJSON(String jsonString) throws ParseException
|
||||
{
|
||||
JSONParser parser = new JSONParser();
|
||||
Object obj = parser.parse(jsonString);
|
||||
JSONObject jsonObj = (JSONObject) obj;
|
||||
Object obj = parser.parse(jsonString); // parse json string
|
||||
JSONObject jsonObj = (JSONObject) obj; // and turn it into a json object
|
||||
|
||||
return jsonObj;
|
||||
}
|
||||
|
||||
@ -36,10 +36,12 @@ import java.util.Scanner;
|
||||
public class TrackManager {
|
||||
private static final String DocumentJwtHeader = ConfigManager.GetProperty("files.docservice.header");
|
||||
|
||||
// read request body
|
||||
public static JSONObject readBody(HttpServletRequest request, PrintWriter writer) throws Exception {
|
||||
String bodyString = "";
|
||||
|
||||
try {
|
||||
// read request body by streams
|
||||
Scanner scanner = new Scanner(request.getInputStream());
|
||||
scanner.useDelimiter("\\A");
|
||||
bodyString = scanner.hasNext() ? scanner.next() : "";
|
||||
@ -50,6 +52,7 @@ public class TrackManager {
|
||||
throw ex;
|
||||
}
|
||||
|
||||
// error when the bodyString object is empty
|
||||
if (bodyString.isEmpty()) {
|
||||
writer.write("empty request.getInputStream");
|
||||
throw new Exception("empty request.getInputStream");
|
||||
@ -59,35 +62,36 @@ public class TrackManager {
|
||||
JSONObject body;
|
||||
|
||||
try {
|
||||
Object obj = parser.parse(bodyString);
|
||||
Object obj = parser.parse(bodyString); // parse bodyString object
|
||||
body = (JSONObject) obj;
|
||||
} catch (Exception ex) {
|
||||
writer.write("JSONParser.parse error:" + ex.getMessage());
|
||||
throw ex;
|
||||
}
|
||||
|
||||
// if the secret key to generate token exists
|
||||
if (DocumentManager.TokenEnabled()) {
|
||||
String token = (String) body.get("token");
|
||||
String token = (String) body.get("token"); // get the document token
|
||||
|
||||
if (token == null) {
|
||||
String header = (String) request.getHeader(DocumentJwtHeader == null || DocumentJwtHeader.isEmpty() ? "Authorization" : DocumentJwtHeader);
|
||||
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
|
||||
if (header != null && !header.isEmpty()) {
|
||||
token = header.startsWith("Bearer ") ? header.substring(7) : header;
|
||||
token = header.startsWith("Bearer ") ? header.substring(7) : header; // and save it without Authorization prefix
|
||||
}
|
||||
}
|
||||
|
||||
if (token == null || token.isEmpty()) {
|
||||
writer.write("{\"error\":1,\"message\":\"JWT expected\"}");
|
||||
if (token == null || token.isEmpty()) { // if the token is not received
|
||||
writer.write("{\"error\":1,\"message\":\"JWT expected\"}"); // an error occurs
|
||||
throw new Exception("{\"error\":1,\"message\":\"JWT expected\"}");
|
||||
}
|
||||
|
||||
JWT jwt = DocumentManager.ReadToken(token);
|
||||
JWT jwt = DocumentManager.ReadToken(token); // read token
|
||||
if (jwt == null) {
|
||||
writer.write("{\"error\":1,\"message\":\"JWT validation failed\"}");
|
||||
writer.write("{\"error\":1,\"message\":\"JWT validation failed\"}"); // an error occurs
|
||||
throw new Exception("{\"error\":1,\"message\":\"JWT validation failed\"}");
|
||||
}
|
||||
|
||||
if (jwt.getObject("payload") != null) {
|
||||
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");
|
||||
@ -112,20 +116,22 @@ public class TrackManager {
|
||||
return body;
|
||||
}
|
||||
|
||||
// file saving process
|
||||
public static void processSave(JSONObject body, String fileName, String userAddress) throws Exception {
|
||||
String downloadUri = (String) body.get("url");
|
||||
String changesUri = (String) body.get("changesurl");
|
||||
String key = (String) body.get("key");
|
||||
String newFileName = fileName;
|
||||
|
||||
String curExt = FileUtility.GetFileExtension(fileName);
|
||||
String downloadExt = FileUtility.GetFileExtension(downloadUri);
|
||||
String curExt = FileUtility.GetFileExtension(fileName); // get current file extension
|
||||
String downloadExt = FileUtility.GetFileExtension(downloadUri); // get the extension of the downloaded file
|
||||
|
||||
// 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);
|
||||
String newFileUri = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), null, false); // convert file and get url to a new file
|
||||
if (newFileUri.isEmpty()) {
|
||||
newFileName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
|
||||
newFileName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress); // get the correct file name if it already exists
|
||||
} else {
|
||||
downloadUri = newFileUri;
|
||||
}
|
||||
@ -134,54 +140,56 @@ public class TrackManager {
|
||||
}
|
||||
}
|
||||
|
||||
String storagePath = DocumentManager.StoragePath(newFileName, userAddress);
|
||||
File histDir = new File(DocumentManager.HistoryDir(storagePath));
|
||||
if (!histDir.exists()) histDir.mkdirs();
|
||||
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()));
|
||||
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);
|
||||
|
||||
if (!ver.exists()) ver.mkdirs();
|
||||
|
||||
lastVersion.renameTo(new File(versionDir + File.separator + "prev" + curExt));
|
||||
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
|
||||
|
||||
downloadToFile(downloadUri, toSave);
|
||||
downloadToFile(changesUri, new File(versionDir + File.separator + "diff.zip"));
|
||||
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
|
||||
|
||||
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"));
|
||||
FileWriter fw = new FileWriter(new File(versionDir + File.separator + "changes.json")); // write the history changes to the changes.json file
|
||||
fw.write(history);
|
||||
fw.close();
|
||||
}
|
||||
|
||||
FileWriter fw = new FileWriter(new File(versionDir + File.separator + "key.txt"));
|
||||
FileWriter fw = new FileWriter(new File(versionDir + File.separator + "key.txt")); // write the key value to the key.txt file
|
||||
fw.write(key);
|
||||
fw.close();
|
||||
|
||||
String forcesavePath = DocumentManager.ForcesavePath(newFileName, userAddress, false);
|
||||
if (!forcesavePath.equals("")) {
|
||||
String forcesavePath = DocumentManager.ForcesavePath(newFileName, userAddress, false); // get the path to the forcesaved file version
|
||||
if (!forcesavePath.equals("")) { // if the forcesaved file version exists
|
||||
File forceSaveFile = new File(forcesavePath);
|
||||
forceSaveFile.delete();
|
||||
forceSaveFile.delete(); // remove it
|
||||
}
|
||||
}
|
||||
|
||||
// file force saving process
|
||||
public static void processForceSave(JSONObject body, String fileName, String userAddress) throws Exception {
|
||||
|
||||
String downloadUri = (String) body.get("url");
|
||||
|
||||
String curExt = FileUtility.GetFileExtension(fileName);
|
||||
String downloadExt = FileUtility.GetFileExtension(downloadUri);
|
||||
String curExt = FileUtility.GetFileExtension(fileName); // get current file extension
|
||||
String downloadExt = FileUtility.GetFileExtension(downloadUri); // 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);
|
||||
String newFileUri = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), null, false); // convert file and get url to a new file
|
||||
if (newFileUri.isEmpty()) {
|
||||
newFileName = true;
|
||||
} else {
|
||||
@ -193,12 +201,12 @@ public class TrackManager {
|
||||
}
|
||||
|
||||
String forcesavePath = "";
|
||||
boolean isSubmitForm = body.get("forcesavetype").toString().equals("3");
|
||||
boolean isSubmitForm = body.get("forcesavetype").toString().equals("3"); // SubmitForm
|
||||
|
||||
if (isSubmitForm) {
|
||||
//new file
|
||||
if (isSubmitForm) { // if the form is submitted
|
||||
// new file
|
||||
if (newFileName){
|
||||
fileName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress);
|
||||
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);
|
||||
}
|
||||
@ -208,7 +216,8 @@ public class TrackManager {
|
||||
fileName = DocumentManager.GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
|
||||
}
|
||||
|
||||
forcesavePath = DocumentManager.ForcesavePath(fileName, userAddress, false);
|
||||
// create forcesave path if it doesn't exist
|
||||
forcesavePath = DocumentManager.ForcesavePath(newFileName, userAddress, false);
|
||||
if (forcesavePath == "") {
|
||||
forcesavePath = DocumentManager.ForcesavePath(fileName, userAddress, true);
|
||||
}
|
||||
@ -220,18 +229,19 @@ public class TrackManager {
|
||||
if (isSubmitForm) {
|
||||
JSONArray actions = (JSONArray) body.get("actions");
|
||||
JSONObject action = (JSONObject) actions.get(0);
|
||||
String user = (String) action.get("userid");
|
||||
DocumentManager.CreateMeta(fileName, user, "Filling Form", userAddress);
|
||||
String user = (String) action.get("userid"); // get the user id
|
||||
DocumentManager.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for forcesaved file
|
||||
}
|
||||
}
|
||||
|
||||
// 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");
|
||||
if (file == null) throw new Exception("argument path");
|
||||
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
|
||||
|
||||
URL uri = new URL(url);
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) uri.openConnection();
|
||||
InputStream stream = connection.getInputStream();
|
||||
InputStream stream = connection.getInputStream(); // get input stream of the file information from the url
|
||||
|
||||
if (stream == null)
|
||||
{
|
||||
@ -244,15 +254,17 @@ public class TrackManager {
|
||||
final byte[] bytes = new byte[1024];
|
||||
while ((read = stream.read(bytes)) != -1)
|
||||
{
|
||||
out.write(bytes, 0, read);
|
||||
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();
|
||||
}
|
||||
|
||||
// create a command request
|
||||
public static void commandRequest(String method, String key) throws Exception {
|
||||
String DocumentCommandUrl = ConfigManager.GetProperty("files.docservice.url.site") + ConfigManager.GetProperty("files.docservice.url.command");
|
||||
|
||||
@ -264,15 +276,16 @@ public class TrackManager {
|
||||
params.put("key", key);
|
||||
|
||||
String headerToken = "";
|
||||
if (DocumentManager.TokenEnabled())
|
||||
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);
|
||||
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);
|
||||
|
||||
String token = DocumentManager.CreateToken(params);
|
||||
String token = DocumentManager.CreateToken(params); // encode a payload object into a body token
|
||||
params.put("token", token);
|
||||
}
|
||||
|
||||
@ -281,23 +294,23 @@ public class TrackManager {
|
||||
|
||||
byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
|
||||
connection.setDoOutput(true);
|
||||
connection.setRequestMethod("POST"); // set the request method
|
||||
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();
|
||||
try (OutputStream os = connection.getOutputStream()) {
|
||||
os.write(bodyByte);
|
||||
os.write(bodyByte); // write bytes to the output stream
|
||||
}
|
||||
InputStream stream = connection.getInputStream();;
|
||||
InputStream stream = connection.getInputStream();; // get input stream
|
||||
|
||||
if (stream == null)
|
||||
throw new Exception("Could not get an answer");
|
||||
|
||||
String jsonString = ServiceConverter.ConvertStreamToString(stream);
|
||||
String jsonString = ServiceConverter.ConvertStreamToString(stream); // convert stream to json string
|
||||
connection.disconnect();
|
||||
|
||||
JSONObject response = ServiceConverter.ConvertStringToJSON(jsonString);
|
||||
JSONObject response = ServiceConverter.ConvertStringToJSON(jsonString); // convert json string to json object
|
||||
if (!response.get("error").toString().equals("0")){
|
||||
throw new Exception(response.toJSONString());
|
||||
}
|
||||
|
||||
@ -42,28 +42,34 @@
|
||||
console.log(message);
|
||||
};
|
||||
|
||||
// the application is loaded into the browser
|
||||
var onAppReady = function () {
|
||||
innerAlert("Document editor ready");
|
||||
};
|
||||
|
||||
// the document is modified
|
||||
var onDocumentStateChange = function (event) {
|
||||
var title = document.title.replace(/\*$/g, "");
|
||||
document.title = title + (event.data ? "*" : "");
|
||||
};
|
||||
|
||||
// the user is trying to switch the document from the viewing into the editing mode
|
||||
var onRequestEditRights = function () {
|
||||
location.href = location.href.replace(RegExp("mode=view\&?", "i"), "");
|
||||
};
|
||||
|
||||
// an error or some other specific event occurs
|
||||
var onError = function (event) {
|
||||
if (event)
|
||||
innerAlert(event.data);
|
||||
};
|
||||
|
||||
// the document is opened for editing with the old document.key value
|
||||
var onOutdatedVersion = function (event) {
|
||||
location.reload(true);
|
||||
};
|
||||
|
||||
// replace the link to the document which contains a bookmark
|
||||
var replaceActionLink = function(href, linkParam) {
|
||||
var link;
|
||||
var actionIndex = href.indexOf("&actionLink=");
|
||||
@ -80,32 +86,37 @@
|
||||
return link;
|
||||
}
|
||||
|
||||
// the user is trying to get link for opening the document which contains a bookmark, scrolling to the bookmark position
|
||||
var onMakeActionLink = function (event) {
|
||||
var actionData = event.data;
|
||||
var linkParam = JSON.stringify(actionData);
|
||||
docEditor.setActionLink(replaceActionLink(location.href, linkParam));
|
||||
docEditor.setActionLink(replaceActionLink(location.href, linkParam)); // set the link to the document which contains a bookmark
|
||||
};
|
||||
|
||||
// the meta information of the document is changed via the meta command
|
||||
var onMetaChange = function (event) {
|
||||
var favorite = !!event.data.favorite;
|
||||
var title = document.title.replace(/^\☆/g, "");
|
||||
document.title = (favorite ? "☆" : "") + title;
|
||||
docEditor.setFavorite(favorite);
|
||||
docEditor.setFavorite(favorite); // change the Favorite icon state
|
||||
};
|
||||
|
||||
// the user is trying to insert an image by clicking the Image from Storage button
|
||||
var onRequestInsertImage = function(event) {
|
||||
docEditor.insertImage({
|
||||
docEditor.insertImage({ // insert an image into the file
|
||||
"c": event.data.c,
|
||||
${dataInsertImage}
|
||||
})
|
||||
};
|
||||
|
||||
// the user is trying to select document for comparing by clicking the Document from Storage button
|
||||
var onRequestCompareFile = function() {
|
||||
docEditor.setRevisedFile(${dataCompareFile});
|
||||
docEditor.setRevisedFile(${dataCompareFile}); // select a document for comparing
|
||||
};
|
||||
|
||||
// the user is trying to select recipients data by clicking the Mail merge button
|
||||
var onRequestMailMergeRecipients = function (event) {
|
||||
docEditor.setMailMergeRecipients(${dataMailMergeRecipients});
|
||||
docEditor.setMailMergeRecipients(${dataMailMergeRecipients}); // insert recipient data for mail merge into the file
|
||||
};
|
||||
|
||||
var config = JSON.parse('<%= FileModel.Serialize(Model) %>');
|
||||
@ -131,14 +142,17 @@
|
||||
%>
|
||||
|
||||
<% if (!history.isEmpty() && !historyData.isEmpty()) { %>
|
||||
// the user is trying to show the document version history
|
||||
config.events['onRequestHistory'] = function () {
|
||||
docEditor.refreshHistory(<%= history %>);
|
||||
docEditor.refreshHistory(<%= history %>); // show the document version history
|
||||
};
|
||||
// the user is trying to click the specific document version in the document version history
|
||||
config.events['onRequestHistoryData'] = function (event) {
|
||||
var ver = event.data;
|
||||
var histData = <%= historyData %>;
|
||||
docEditor.setHistoryData(histData[ver - 1]);
|
||||
docEditor.setHistoryData(histData[ver - 1]); // send the link to the document for viewing the version history
|
||||
};
|
||||
// the user is trying to go back to the document from viewing the document version history
|
||||
config.events['onRequestHistoryClose'] = function () {
|
||||
document.location.reload();
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user