esoe 1 year ago
parent
commit
e3f44aa8b4
  1. 4
      pom.xml
  2. 37
      src/main/java/ru/molokoin/home/servlets/Delete.java
  3. 48
      src/main/java/ru/molokoin/home/servlets/Download.java
  4. 209
      src/main/java/ru/molokoin/home/servlets/Storage.java
  5. 76
      src/main/java/ru/molokoin/home/util/HardDrive.java
  6. BIN
      target/classes/ru/molokoin/home/entities/Media.class
  7. BIN
      target/classes/ru/molokoin/home/servlets/Delete.class
  8. BIN
      target/classes/ru/molokoin/home/servlets/Download.class
  9. BIN
      target/classes/ru/molokoin/home/servlets/Main.class
  10. BIN
      target/classes/ru/molokoin/home/servlets/Storage.class
  11. BIN
      target/classes/ru/molokoin/home/util/HardDrive.class
  12. BIN
      target/home.war
  13. BIN
      target/home/WEB-INF/classes/ru/molokoin/home/entities/Media.class
  14. BIN
      target/home/WEB-INF/classes/ru/molokoin/home/servlets/Delete.class
  15. BIN
      target/home/WEB-INF/classes/ru/molokoin/home/servlets/Download.class
  16. BIN
      target/home/WEB-INF/classes/ru/molokoin/home/servlets/Main.class
  17. BIN
      target/home/WEB-INF/classes/ru/molokoin/home/servlets/Storage.class
  18. BIN
      target/home/WEB-INF/classes/ru/molokoin/home/util/HardDrive.class
  19. 3
      target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst
  20. 3
      target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst

4
pom.xml

@ -15,8 +15,8 @@ @@ -15,8 +15,8 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>

37
src/main/java/ru/molokoin/home/servlets/Delete.java

@ -0,0 +1,37 @@ @@ -0,0 +1,37 @@
package ru.molokoin.home.servlets;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Сервлет удаляющий файл из хранилища
*/
@WebServlet(name = "Delete", value = "/delete")
public class Delete extends HttpServlet{
private String STORAGE_PATH = "/srv/apps/home/exchange";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
//Узнать имя файла из запроса
String fileName = request.getParameter("filename");
//Удаление файла
File fileToDelete = new File(STORAGE_PATH + File.separator + fileName);
fileToDelete.delete();
//после скачивания возвращаем пользователя в хранилище
response.sendRedirect("storage");
}
}

48
src/main/java/ru/molokoin/home/servlets/Download.java

@ -0,0 +1,48 @@ @@ -0,0 +1,48 @@
package ru.molokoin.home.servlets;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import ru.molokoin.home.util.HardDrive;
@WebServlet(name = "Download", value = "/download")
public class Download extends HttpServlet{
private String STORAGE_PATH = HardDrive.root;
private final int ARBITARY_SIZE = 1048;//размер буфера при чтении файла
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
//response.setContentType("text/html; charset=UTF-8");
response.setContentType("text/plain; charset=UTF-8");
//Узнать имя файла из запроса
String fileName = request.getParameter("filename");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
//Отдаем файл с сервера
File file = new File(STORAGE_PATH + File.separator + fileName);
try(InputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream()) {
byte[] buffer = new byte[ARBITARY_SIZE];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numBytesRead);
}
}
//после скачивания возвращаем пользователя в хранилище
response.sendRedirect("storage");
}
}

209
src/main/java/ru/molokoin/home/servlets/Storage.java

@ -8,7 +8,14 @@ import java.io.InputStreamReader; @@ -8,7 +8,14 @@ import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
@ -20,11 +27,13 @@ import jakarta.servlet.http.Part; @@ -20,11 +27,13 @@ import jakarta.servlet.http.Part;
/**
* Сервлет файлообменника
*/
@MultipartConfig(fileSizeThreshold = 2024 * 2024,
maxFileSize = 2024 * 2024 * 5,
maxRequestSize = 2024 * 2024 * 5 * 5)
@MultipartConfig
// (fileSizeThreshold = 2024 * 2024,
// maxFileSize = 2024 * 2024 * 5,
// maxRequestSize = 2024 * 2024 * 5 * 5)
@WebServlet(name = "Storage", value = "/storage")
public class Storage extends HttpServlet{
private String STORAGE_PATH = "/srv/apps/home/exchange";//TODO Путь разместить в файле настроек приложения *.property
/**
* Возвращает пользователю страницу, содержащую:
* - перечень доступных для скачивания файлов
@ -32,11 +41,10 @@ public class Storage extends HttpServlet{ @@ -32,11 +41,10 @@ public class Storage extends HttpServlet{
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//page(request, response);
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html lang=\"en\">");
out.println("<head>");
@ -52,16 +60,31 @@ public class Storage extends HttpServlet{ @@ -52,16 +60,31 @@ public class Storage extends HttpServlet{
out.println(" <h1 >molokoin.ru : storage</h1>");
out.println("</header>");
out.println("<aside>");
out.println(" <p>controls</p>");
out.println(" <h1>upload file</h1>");
//форма upload
out.println(" <form action=\"storage\" method=\"post\" enctype=\"multipart/form-data\">");
out.println(" <input type=\"text\" name=\"description\" />");
//out.println(" <input type=\"text\" name=\"description\" />");
out.println(" <input type=\"file\" name=\"file\" />");
//out.println(" <input type=\"file\" name=\"file\" multiple=\"multiple\"/>");
out.println(" <input type=\"submit\" />");
out.println("</form>");
out.println(listSide());
out.println("</aside>");
out.println("<main>");
out.println(" <p>tables of content</p>");
// Отображение содержимого файла
// System.out.println("Проверка filename ...");
// if (request.getParameter("filename") != null){
// System.out.println(STORAGE_PATH + "/" + request.getParameter("filename"));
// out.println("<embed src=\"" + STORAGE_PATH + "/" + request.getParameter("filename") + "\" width=\"800px\" height=\"2100px\" />");
// }
// Отображение списка файлов
out.println(listMain());
out.println("</main>");
out.println("<footer>");
out.println("</footer>");
@ -70,84 +93,116 @@ public class Storage extends HttpServlet{ @@ -70,84 +93,116 @@ public class Storage extends HttpServlet{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
page(request, response);
//page(request, response);
//скачивание файла
try {
upload(request);
} catch (ServletException e) {
//переслать на страницу ошибки
}
response.sendRedirect("storage");
}
private void page(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html lang=\"en\">");
out.println("<head>");
out.println(" <meta charset=\"UTF-8\">");
out.println(" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">");
out.println(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
out.println(" <title>home:storage</title>");
// Подключение стилей
out.println(" <link href=\"layout/styles.css\" rel=\"stylesheet\">");
out.println("</head>");
out.println("<html><body >");
out.println("<header>");
out.println(" <h1 >molokoin.ru : storage</h1>");
out.println("</header>");
out.println("<aside>");
out.println(" <p>controls</p>");
out.println("</aside>");
out.println("<main>");
out.println(" <p>tables of content</p>");
// обработка данных
String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
out.println(" <p>"+description+"</p>");
String uploadPath = "/srv/apps/home/exchange";
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
out.println(" <p>"+"Директория для записи файла: " + uploadPath + " не доступна!!!" + "</p>");
} else {
try {
/**
* Метод загружает на сервер файл выбранный пользователем,
* возвращает строку, содержащую отчет по результатам загрузки
* @param request
* @return
* @throws IOException
* @throws ServletException
*/
private Boolean upload(HttpServletRequest request) throws IOException, ServletException{
String fileName = "";
Part filePart = request.getPart("file");
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
out.println(" <p>"+fileName+"</p>");
fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
for (Part part : request.getParts()) {
part.write(uploadPath + File.separator + fileName);
//out.println(" <p>"+fileName + "содержит: " + part.getSize()+"</p>");
}
} catch (ServletException e) {
//e.printStackTrace();
part.write(STORAGE_PATH + File.separator + fileName);
}
return true;
}
/**
* Метод, возвращающий список файлов на сервере
* @return
* @throws IOException
*/
private Set<String> list() throws IOException{
Stream<Path> stream = Files.list(Paths.get(STORAGE_PATH));
Set<String> list = stream
.filter(file -> !Files.isDirectory(file))
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toSet());
stream.close();
return list;
}
/**
* Метод формирует список файлов и директорий,
* для отображения на боковой панели страницы
* Инструменты управления файлами:
* - просмотр списка файлов и директорий
* - просмотр файла
* - просмотр содержимого директории
* -
*
* @return
* @throws IOException
*/
private String listSide() throws IOException{
StringBuilder report = new StringBuilder();
Set<String> list = list();
for (String filename : list) {
report.append("<a href=\"storage?filename=" + filename + "\">");
report.append(filename);
report.append("</a>");
}
return report.toString();
}
// Part filePart;
// try {
// filePart = request.getPart("file");// Retrieves <input type="file" name="file">
// String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
// out.println(" <p>" + fileName + " contains: " + "</p>");
// InputStream fileContent = filePart.getInputStream();
// //читаем из файла
// StringBuilder textBuilder = new StringBuilder();
// try (Reader reader = new BufferedReader(new InputStreamReader
// (fileContent, StandardCharsets.UTF_8))) {
// int c = 0;
// while ((c = reader.read()) != -1) {
// textBuilder.append((char) c);
// }
// out.println(" <p>" + fileName + " contains: " + textBuilder.toString() + "</p>");
// }
// } catch (ServletException e) {
// // TODO Auto-generated catch block
// //e.printStackTrace();
// out.println(" <p>" + "Файл вызвал ошибку: " + "</p>");
// }
out.println("</main>");
out.println("<footer>");
out.println("</footer>");
out.println("</body></html>");
/**
* Метод возвращает перечень доступных файлов на сервере
* - в виде таблицы
* @return
* @throws IOException
*/
private String listMain() throws IOException{
StringBuilder report = new StringBuilder();
Set<String> list = list();
//таблица - перечень файлов
report.append("<h1>" + "Файлы на сервере: " + "</h1>");
report.append("<table>");
report.append("<tr>");
report.append("<td>ID</td>");
report.append("<td>Наименование</td>");
report.append("<td>Описание</td>");
report.append("<td>Дата добавления</td>");
report.append("<td>controls</td>");//скачать : удалить
report.append("</tr>");
for(String path : list) {
report.append("<tr>");
report.append("<td>" + "no id" +"</td>");
report.append("<td>" + path + "</td>");
report.append("<td>" + "no description" + "</td>");
report.append("<td>" + "no date" + "</td>");
//добавляем кнопку скачивания
report.append("<td>");
//кнопка скачивания
report.append(" <form action=\"download\" method=\"post\">");
report.append(" <input type=\"hidden\" name=\"filename\" value=\"" + path + "\">");
report.append(" <button type=\"submit\" formmethod=\"post\">download</button>");
report.append(" </form>");
report.append(" <br>");
//кнопка удаления
report.append(" <form action=\"delete\" method=\"post\">");
report.append(" <input type=\"hidden\" name=\"filename\" value=\"" + path + "\">");
report.append(" <button type=\"submit\" formmethod=\"post\">delete</button>");
report.append(" </form>");
report.append("</td>");
report.append("</tr>");
}
report.append("</table>");
return report.toString();
}

76
src/main/java/ru/molokoin/home/util/HardDrive.java

@ -0,0 +1,76 @@ @@ -0,0 +1,76 @@
package ru.molokoin.home.util;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Методы работы с данными на жестком диске
*/
public class HardDrive {
public static String root = "/srv/apps/home/exchange";
public static String getRoot() {
return root;
}
public static void setRoot(String root) {
HardDrive.root = root;
}
/**
* Метод, возвращающий список файлов в корне хранилища приложения
* @return
* @throws IOException
*/
private static Set<String> listFiles(String path) throws IOException{
Stream<Path> stream = Files.list(Paths.get(path));
Set<String> list = stream
.filter(file -> !Files.isDirectory(file))
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toSet());
stream.close();
return list;
}
private static HashMap<String, Boolean> getMap(String path) throws IOException{
Stream<Path> stream = Files.list(Paths.get(path));
HashMap<String, Boolean> map = new HashMap<>();
return map;
}
public static void showFiles(File[] files) {
for (File file : files) {
if (file.isDirectory()) {
System.out.println("Directory: " + file.getAbsolutePath());
showFiles(file.listFiles()); // Calls same method again.
} else {
System.out.println("File: " + file.getAbsolutePath());
}
}
}
/**
* тестируем работу методов HardDrive
* @param args
*/
public static void main(String[] args) {
File dir = new File("C:\\Users\\Strannik\\Documents\\esoe\\code\\home\\src\\main\\webapp\\content");
new File(dir + File.separator + "inner").mkdirs();
//showFiles(dir.listFiles());
System.out.println(Arrays.toString(dir.listFiles()));
for (File file : dir.listFiles()) {
System.out.println(file.getName());
}
}
}

BIN
target/classes/ru/molokoin/home/entities/Media.class

Binary file not shown.

BIN
target/classes/ru/molokoin/home/servlets/Delete.class

Binary file not shown.

BIN
target/classes/ru/molokoin/home/servlets/Download.class

Binary file not shown.

BIN
target/classes/ru/molokoin/home/servlets/Main.class

Binary file not shown.

BIN
target/classes/ru/molokoin/home/servlets/Storage.class

Binary file not shown.

BIN
target/classes/ru/molokoin/home/util/HardDrive.class

Binary file not shown.

BIN
target/home.war

Binary file not shown.

BIN
target/home/WEB-INF/classes/ru/molokoin/home/entities/Media.class

Binary file not shown.

BIN
target/home/WEB-INF/classes/ru/molokoin/home/servlets/Delete.class

Binary file not shown.

BIN
target/home/WEB-INF/classes/ru/molokoin/home/servlets/Download.class

Binary file not shown.

BIN
target/home/WEB-INF/classes/ru/molokoin/home/servlets/Main.class

Binary file not shown.

BIN
target/home/WEB-INF/classes/ru/molokoin/home/servlets/Storage.class

Binary file not shown.

BIN
target/home/WEB-INF/classes/ru/molokoin/home/util/HardDrive.class

Binary file not shown.

3
target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst

@ -1,3 +1,6 @@ @@ -1,3 +1,6 @@
ru\molokoin\home\servlets\Storage.class
ru\molokoin\home\entities\Media.class
ru\molokoin\home\servlets\Delete.class
ru\molokoin\home\servlets\Main.class
ru\molokoin\home\util\HardDrive.class
ru\molokoin\home\servlets\Download.class

3
target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst

@ -1,3 +1,6 @@ @@ -1,3 +1,6 @@
C:\Users\Strannik\Documents\esoe\code\home\src\main\java\ru\molokoin\home\servlets\Storage.java
C:\Users\Strannik\Documents\esoe\code\home\src\main\java\ru\molokoin\home\entities\Media.java
C:\Users\Strannik\Documents\esoe\code\home\src\main\java\ru\molokoin\home\servlets\Download.java
C:\Users\Strannik\Documents\esoe\code\home\src\main\java\ru\molokoin\home\servlets\Delete.java
C:\Users\Strannik\Documents\esoe\code\home\src\main\java\ru\molokoin\home\servlets\Main.java
C:\Users\Strannik\Documents\esoe\code\home\src\main\java\ru\molokoin\home\util\HardDrive.java

Loading…
Cancel
Save