Skip to content

Commit

Permalink
java: search for fileName by path added + json-data fix
Browse files Browse the repository at this point in the history
  • Loading branch information
rivexe committed Feb 17, 2023
1 parent 63b7641 commit bc90d55
Showing 1 changed file with 93 additions and 59 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,11 @@

import static utils.Constants.KILOBYTE_SIZE;


@WebServlet(name = "IndexServlet", urlPatterns = {"/IndexServlet"})
@WebServlet(name = "IndexServlet", urlPatterns = { "/IndexServlet" })
@MultipartConfig
public class IndexServlet extends HttpServlet {
protected void processRequest(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException, IOException {
final HttpServletResponse response) throws ServletException, IOException {
// get the type parameter from the request
String action = request.getParameter("type");

Expand All @@ -81,7 +80,8 @@ protected void processRequest(final HttpServletRequest request,

DocumentManager.init(request, response);

// create a variable to display information about the application and error messages
// create a variable to display information about the application and error
// messages
PrintWriter writer = response.getWriter();

// define functions for each type of operation
Expand Down Expand Up @@ -128,8 +128,8 @@ protected void processRequest(final HttpServletRequest request,
}

private static void saveAs(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
final HttpServletResponse response,
final PrintWriter writer) {
response.setContentType("text/plain");
try {
Scanner scanner = new Scanner(request.getInputStream());
Expand Down Expand Up @@ -167,11 +167,10 @@ private static void saveAs(final HttpServletRequest request,
}
}


// upload a file
private static void upload(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
final HttpServletResponse response,
final PrintWriter writer) {
response.setContentType("text/plain");

try {
Expand All @@ -188,7 +187,7 @@ private static void upload(final HttpServletRequest request,
}
}

long curSize = httpPostedFile.getSize(); // get file size
long curSize = httpPostedFile.getSize(); // get file size

// check if the file size exceeds the maximum file size or is less than 0
if (DocumentManager.getMaxFileSize() < curSize || curSize <= 0) {
Expand All @@ -198,7 +197,7 @@ private static void upload(final HttpServletRequest request,
return;
}

String curExt = FileUtility.getFileExtension(fileName); // get current file extension
String curExt = FileUtility.getFileExtension(fileName); // get current file extension

// check if this extension is supported by the editor
if (!DocumentManager.getFileExts().contains(curExt)) {
Expand All @@ -224,10 +223,11 @@ private static void upload(final HttpServletRequest request,
int read;
final byte[] bytes = new byte[KILOBYTE_SIZE];
while ((read = fileStream.read(bytes)) != -1) {
out.write(bytes, 0, read); // write bytes to the output stream
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
// force write data to the output stream that can be cached in the current
// thread
out.flush();
}

Expand All @@ -246,8 +246,8 @@ private static void upload(final HttpServletRequest request,

// convert a file
private static void convert(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) throws UnsupportedEncodingException {
final HttpServletResponse response,
final PrintWriter writer) throws UnsupportedEncodingException {
CookieManager cm = new CookieManager(request);
response.setContentType("text/plain");

Expand Down Expand Up @@ -282,14 +282,16 @@ private static void convert(final HttpServletRequest request,
return;
}

/* 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 correctName = DocumentManager.getCorrectName(FileUtility
.getFileNameWithoutExtension(fileName) + internalFileExt, null);
.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
InputStream stream = connection.getInputStream(); // get input stream of the converted file

if (stream == null) {
throw new Exception("Stream is null");
Expand All @@ -300,10 +302,11 @@ private static void convert(final HttpServletRequest request,
int read;
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.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
// force write data to the output stream that can be cached in the current
// thread
out.flush();
}

Expand All @@ -315,7 +318,8 @@ private static void convert(final HttpServletRequest request,

fileName = correctName;

// create meta information about the converted file with the user id and name specified
// 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.getId(), user.getName(), null);
Expand All @@ -330,8 +334,8 @@ private static void convert(final HttpServletRequest request,

// track file changes
private static void track(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
final HttpServletResponse response,
final PrintWriter writer) {
JSONObject body = null;

// read request body
Expand All @@ -351,7 +355,7 @@ private static void track(final HttpServletRequest request,
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"); // the user who finished editing
String user = (String) action.get("userid"); // the user who finished editing
if (users.indexOf(user) == -1) {
String key = (String) body.get("key");
try {
Expand Down Expand Up @@ -394,8 +398,8 @@ private static void track(final HttpServletRequest request,

// remove a file
private static void remove(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
final HttpServletResponse response,
final PrintWriter writer) {
try {
String fileName = FileUtility.getFileName(request.getParameter("filename"));
String path = DocumentManager.storagePath(fileName, null);
Expand All @@ -416,19 +420,19 @@ private static void remove(final HttpServletRequest request,

// get files information
private static void files(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
final HttpServletResponse response,
final PrintWriter writer) {
ArrayList<Map<String, Object>> files = null;

try {
Gson gson = new Gson();
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 {
String fileId = request.getParameter("fileId"); // get file id from the request
String fileId = request.getParameter("fileId"); // get file id from the request
files = DocumentManager.getFilesInfo(fileId);
if (files.isEmpty()) {
writer.write("\"File not found\"");
Expand All @@ -443,8 +447,8 @@ private static void files(final HttpServletRequest request,

// download a csv file
private static void csv(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
final HttpServletResponse response,
final PrintWriter writer) {
String fileName = "assets/sample/csv.csv";
URL fileUrl = Thread.currentThread().getContextClassLoader().getResource(fileName);
Path filePath = null;
Expand All @@ -458,8 +462,8 @@ private static void csv(final HttpServletRequest request,

// get sample files from the assests
private static void assets(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
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;
Expand All @@ -473,15 +477,16 @@ private static void assets(final HttpServletRequest request,

// download a file from history
private static void downloadHistory(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
final HttpServletResponse response,
final PrintWriter writer) {
try {
if (DocumentManager.tokenEnabled()) {

String documentJwtHeader = ConfigManager.getProperty("files.docservice.header");

String header = (String) request.getHeader(documentJwtHeader == null || documentJwtHeader.isEmpty()
? "Authorization" : documentJwtHeader);
? "Authorization"
: documentJwtHeader);
if (header != null && !header.isEmpty()) {
String bearerPrefix = "Bearer ";
String token = header.startsWith(bearerPrefix) ? header.substring(bearerPrefix.length()) : header;
Expand All @@ -501,8 +506,8 @@ private static void downloadHistory(final HttpServletRequest request,
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 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);

Expand All @@ -514,8 +519,8 @@ private static void downloadHistory(final HttpServletRequest request,

// download a file
private static void download(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
final HttpServletResponse response,
final PrintWriter writer) {
try {
String fileName = FileUtility.getFileName(request.getParameter("fileName"));
String userAddress = request.getParameter("userAddress");
Expand All @@ -526,7 +531,8 @@ private static void download(final HttpServletRequest request,
String documentJwtHeader = ConfigManager.getProperty("files.docservice.header");

String header = (String) request.getHeader(documentJwtHeader == null || documentJwtHeader.isEmpty()
? "Authorization" : documentJwtHeader);
? "Authorization"
: documentJwtHeader);
String token = "";
if (header != null && !header.isEmpty()) {
String bearerPrefix = "Bearer ";
Expand All @@ -544,7 +550,7 @@ private static void download(final HttpServletRequest request,
// 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) {
Expand All @@ -555,8 +561,8 @@ private static void download(final HttpServletRequest request,
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()) {
Expand Down Expand Up @@ -585,7 +591,7 @@ private static void download(final String filePath, final HttpServletResponse re
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) {
Expand All @@ -601,8 +607,8 @@ private static void download(final String filePath, final HttpServletResponse re

// rename a file
private static void rename(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
final HttpServletResponse response,
final PrintWriter writer) {
try {
Scanner scanner = new Scanner(request.getInputStream());
scanner.useDelimiter("\\A");
Expand Down Expand Up @@ -639,8 +645,8 @@ private static void rename(final HttpServletRequest request,

// reference data
private static void reference(final HttpServletRequest request,
final HttpServletResponse response,
final PrintWriter writer) {
final HttpServletResponse response,
final PrintWriter writer) {
try {
Scanner scanner = new Scanner(request.getInputStream());
scanner.useDelimiter("\\A");
Expand All @@ -650,15 +656,43 @@ private static void reference(final HttpServletRequest request,

JSONParser parser = new JSONParser();
JSONObject body = (JSONObject) parser.parse(bodyString);
String instanceId = (String) body.get("instanceId");
JSONObject fileKey = (JSONObject) body.get("fileKey");
String fileKeyValue = gson.toJson(fileKey);
JSONObject referenceDataObj = (JSONObject) body.get("referenceData");
String instanceId = (String) referenceDataObj.get("instanceId");

String fileKeyValue = "";
String userAddress = "";
String fileName = "";

String fileName = (String) fileKey.get("fileName");
String userAddress = (String) fileKey.get("userAddress");
if (Objects.equals(instanceId, DocumentManager.getServerUrl(false))) {
JSONObject fileKey = (JSONObject) referenceDataObj.get("fileKey");
fileKeyValue = gson.toJson(fileKey);
userAddress = (String) fileKey.get("userAddress");
if (Objects.equals(userAddress, DocumentManager.curUserHostAddress(null))) {
fileName = (String) fileKey.get("fileName");
}
}

if (Objects.equals(fileName, "") && !Objects.equals(userAddress, "")) {
try {
String path = (String) body.get("path");
path = FileUtility.getFileName(path);
File f = new File(DocumentManager.storagePath(path, userAddress));
if (f.exists()) {
fileName = path;
}
} catch (Exception e) {
e.printStackTrace();
writer.write("{ \"error\" : 1, \"message\" : \"" + e.getMessage() + "\"}");
}
}

if (Objects.equals(fileName, "")) {
writer.write("{ \"error\": \"File not found\"}");
return;
}

HashMap<String, Object> referenceData = new HashMap<>();
referenceData.put("instanceId", DocumentManager.getServerUrl(true));
referenceData.put("instanceId", DocumentManager.getServerUrl(false));
referenceData.put("fileKey", fileKeyValue);

HashMap<String, Object> data = new HashMap<>();
Expand All @@ -682,14 +716,14 @@ private static void reference(final HttpServletRequest request,
// process get request
@Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException, IOException {
final HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

// process post request
@Override
protected void doPost(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException, IOException {
final HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

Expand Down

0 comments on commit bc90d55

Please sign in to comment.