Browse Source

view pdf content

master
esoe 1 year ago
parent
commit
e54c9775b1
  1. 13
      README.md
  2. 28
      pom.xml
  3. 0
      src/main/docs/scripts/prepare.sql
  4. 128
      src/main/java/ru/molokoin/storage/api/RestStorageService.java
  5. 78
      src/main/java/ru/molokoin/storage/beans/HardDrive.java
  6. 23
      src/main/java/ru/molokoin/storage/beans/Storage.java
  7. 4
      src/main/java/ru/molokoin/storage/beans/StorageFace.java
  8. 12
      src/main/java/ru/molokoin/storage/entities/ContentEntity.java
  9. 2
      src/main/resources/META-INF/persistence.xml
  10. 2
      target/classes/META-INF/persistence.xml
  11. BIN
      target/classes/ru/molokoin/storage/api/RestConfig.class
  12. BIN
      target/classes/ru/molokoin/storage/api/RestStorageService.class
  13. BIN
      target/classes/ru/molokoin/storage/beans/HardDrive.class
  14. BIN
      target/classes/ru/molokoin/storage/beans/Storage.class
  15. BIN
      target/classes/ru/molokoin/storage/beans/StorageFace.class
  16. BIN
      target/classes/ru/molokoin/storage/entities/ContentEntity.class
  17. BIN
      target/classes/ru/molokoin/storage/services/Storage.class
  18. BIN
      target/classes/ru/molokoin/storage/services/StorageFace.class
  19. 4
      target/maven-archiver/pom.properties
  20. 6
      target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst
  21. 6
      target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst
  22. BIN
      target/storage.war
  23. 9
      target/storage/WEB-INF/classes/META-INF/persistence.xml
  24. BIN
      target/storage/WEB-INF/classes/ru/molokoin/storage/api/RestConfig.class
  25. BIN
      target/storage/WEB-INF/classes/ru/molokoin/storage/api/RestStorageService.class
  26. BIN
      target/storage/WEB-INF/classes/ru/molokoin/storage/beans/HardDrive.class
  27. BIN
      target/storage/WEB-INF/classes/ru/molokoin/storage/beans/Storage.class
  28. BIN
      target/storage/WEB-INF/classes/ru/molokoin/storage/beans/StorageFace.class
  29. BIN
      target/storage/WEB-INF/classes/ru/molokoin/storage/entities/ContentEntity.class
  30. BIN
      target/storage/WEB-INF/lib/jakarta.activation-api-2.1.0.jar
  31. BIN
      target/storage/WEB-INF/lib/jakarta.ws.rs-api-3.1.0.jar
  32. BIN
      target/storage/WEB-INF/lib/jakarta.xml.bind-api-4.0.0.jar
  33. 7
      target/storage/WEB-INF/web.xml
  34. 5
      target/storage/index.jsp

13
README.md

@ -1,8 +1,17 @@ @@ -1,8 +1,17 @@
# Storage-service
Сервис обмена файлами большого размера
## API
# Realization
Файлы хранятся не в базе данных, а в самостоятельном хранилице на сервере,
в базе хранятся адреса файлов, их описания,
# API
- getFile
- postFile
- deleteFile
- listFiles
- listFiles
# Servlets
- viewFile

28
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>
@ -88,6 +88,30 @@ @@ -88,6 +88,30 @@
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
<configuration>
<!-- отключаю плагин по умолчанию -->
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>4.1.0.Final</version>
<executions>
<execution>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
<configuration>
<hostname>molokoin.ru</hostname>
<port>9990</port>
<username>esoe</username>
<password>psalm6912</password>
<name>storage.war</name>
</configuration>
</plugin>
</plugins>
</pluginManagement>

0
src/main/scripts/prepare.sql → src/main/docs/scripts/prepare.sql

128
src/main/java/ru/molokoin/storage/api/RestStorageService.java

@ -1,9 +1,20 @@ @@ -1,9 +1,20 @@
package ru.molokoin.storage.api;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import jakarta.ejb.EJB;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
@ -12,8 +23,9 @@ import jakarta.ws.rs.Produces; @@ -12,8 +23,9 @@ import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import ru.molokoin.storage.beans.HardDrive;
import ru.molokoin.storage.beans.StorageFace;
import ru.molokoin.storage.entities.ContentEntity;
import ru.molokoin.storage.services.StorageFace;
@Path("content")
public class RestStorageService {
@ -30,14 +42,72 @@ public class RestStorageService { @@ -30,14 +42,72 @@ public class RestStorageService {
*
* @return
*/
// @GET
// @Produces(MediaType.APPLICATION_XML)
// public Collection<ContentEntity> getInfo(){
// System.out.println("Передача данных обо всех файлах ...");
// Collection<ContentEntity> cce = storage.getInfo();
// return cce;
// }
/**
* Получение сведений о контенте из файловой системы
* @return
*/
@GET
@Produces(MediaType.APPLICATION_XML)
public Collection<ContentEntity> getInfo(){
System.out.println("Передача данных обо всех файлах ...");
Collection<ContentEntity> cce = storage.getInfo();
System.out.println("Передача данных о контенте из файловой системы ...");
Collection<ContentEntity> cce = new ArrayList<>();
try {
Set<String> list = HardDrive.listFiles(HardDrive.getRoot());
int i = 1;
for (String path : list) {
ContentEntity ce = new ContentEntity();
ce.setId((long)i);
i++;
ce.setFilename(Paths.get(path).toString());
ce.setLocation(HardDrive.getRoot());
cce.add(ce);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cce;
}
@GET
@Path("q/{id}")
@Produces(MediaType.APPLICATION_XML)
//@Produces(MediaType.MULTIPART_FORM_DATA)
public ContentEntity getInfoById(@PathParam("id") Integer id, @Context HttpServletResponse response){
Collection<ContentEntity> cce = new ArrayList<>();
ContentEntity ce = new ContentEntity();
try {
Set<String> list = HardDrive.listFiles(HardDrive.getRoot());
int i = 1;
for (String path : list) {
if (id == i) {
ce.setId((long)i);
ce.setFilename(Paths.get(path).toString());
ce.setLocation(HardDrive.getRoot());
cce.add(ce);
}
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ce;
}
// @GET
// @Path("{id}")
// @Produces(MediaType.APPLICATION_OCTET_STREAM)
@ -49,12 +119,54 @@ public class RestStorageService { @@ -49,12 +119,54 @@ public class RestStorageService {
// }
// @GET
// @Path("{id}")
// @Produces(MediaType.APPLICATION_OCTET_STREAM)
// public Response getFile() {
// File file = ... // Initialize this to the File path you want to serve.
// return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
// .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional
// .build();
// public File getFile(@PathParam("id") Integer id, @Context HttpServletResponse response) {
// ContentEntity ce = getInfoById(1, response);
// File file = new File(ce.getLocation()); // Initialize this to the File path you want to serve.
// // return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
// // .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional
// // .build();
// return file;
// }
/**
* Получение файла (*.pdf) на просмотр по id
* !!! добавить возможность открытия файлов других типов
* @param id
* @param response
* @return
* @throws IOException
*/
@GET
@Path("{id}")
public Response viewContent(@PathParam("id") Integer id,
@Context HttpServletResponse response) throws IOException {
try {
System.out.println(">>>>>>>>>>>>>>>> SHOW the FILE <<<<<<<<<<<<<<<");
ContentEntity ce = getInfoById(id, response);
java.nio.file.Path path = Paths.get(ce.getLocation() + File.separator + ce.getFilename());
System.out.println("------- PATH: " + path.toString());
long size = Files.size(path);
response.setContentLength((int) size);
// response.setContentType("text/markdown");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/pdf");
response.setHeader("Content-disposition","inline; filename=\"" + ce.getFilename() + "\"");
ServletOutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(path.toFile());
// HardDrive.getBais(id);
int length = 0;
while ((fis != null) && ((length = fis.read(buffer)) != -1)) {
outStream.write(buffer, 0, length);
}
fis.close();
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
return Response.ok().build();
}
}

78
src/main/java/ru/molokoin/storage/beans/HardDrive.java

@ -0,0 +1,78 @@ @@ -0,0 +1,78 @@
package ru.molokoin.storage.beans;
import java.io.ByteArrayInputStream;
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;
import ru.molokoin.storage.entities.ContentEntity;
/**
* Методы работы с данными на жестком диске
*/
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
*/
public 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());
}
}
}
public static Path getFileById(int id) throws IOException{
Path path = null;
Set<String> set = listFiles(root);
int i = 0;
for (String s : set) {
i++;
System.out.println("CURRENT FILE >> " + s);
if (i == id){
path = Paths.get(s);
System.out.println("SUCCESS >> " + path.toString());
}
}
return path;
}
}

23
src/main/java/ru/molokoin/storage/services/Storage.java → src/main/java/ru/molokoin/storage/beans/Storage.java

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
package ru.molokoin.storage.services;
package ru.molokoin.storage.beans;
import java.util.ArrayList;
import java.util.List;
@ -6,21 +6,34 @@ import java.util.List; @@ -6,21 +6,34 @@ import java.util.List;
import jakarta.ejb.Singleton;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import jakarta.ws.rs.core.Response;
import ru.molokoin.storage.entities.ContentEntity;
@Singleton
public class Storage implements StorageFace{
@PersistenceContext (unitName="Storage")
@PersistenceContext (unitName="default")
private EntityManager em;
@Override
public <T> List<T> findAll(Class<T> clazz) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(clazz);
//Metamodel m = em.getMetamodel();
Root<T> obj = cq.from(clazz);
return em.createQuery(cq.select(obj)).getResultList();
}
@Override
public List<ContentEntity> getInfo() {
List<ContentEntity> list = new ArrayList<>();
System.out.println("getInfo()");
//Обращаемся к базе и запрашиваем сведения
String sql = "SELECT id, filename, location FROM Storage";
Query query = em.createNativeQuery(sql, ContentEntity.class);
List<ContentEntity> list = query.getResultList();
return list;
}

4
src/main/java/ru/molokoin/storage/services/StorageFace.java → src/main/java/ru/molokoin/storage/beans/StorageFace.java

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
package ru.molokoin.storage.services;
package ru.molokoin.storage.beans;
import java.util.List;
@ -12,6 +12,8 @@ import ru.molokoin.storage.entities.ContentEntity; @@ -12,6 +12,8 @@ import ru.molokoin.storage.entities.ContentEntity;
*/
@Local
public interface StorageFace {
<T> List<T> findAll(Class<T> clazz);
/**
* Коллекция сведений о файлах, доступных в хранилице
* полученная из базы данных

12
src/main/java/ru/molokoin/storage/entities/ContentEntity.java

@ -17,7 +17,7 @@ import jakarta.xml.bind.annotation.XmlRootElement; @@ -17,7 +17,7 @@ import jakarta.xml.bind.annotation.XmlRootElement;
*/
@Entity
@XmlRootElement(name = "storage")
@Table(name = "Storage", schema = "home", catalog = "")//поправить схему
@Table(name = "Storage", schema = "home", catalog = "")//поправить схему?
public class ContentEntity implements Serializable{
@Id //уникальный идентификатор строки
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ -33,8 +33,6 @@ public class ContentEntity implements Serializable{ @@ -33,8 +33,6 @@ public class ContentEntity implements Serializable{
@Column(name = "location", length = 1000)
String location; //Путь к файлу на локальной машине
byte[] content; //массив байткода - содержимое файла
public Long getId() {
return id;
}
@ -59,14 +57,6 @@ public class ContentEntity implements Serializable{ @@ -59,14 +57,6 @@ public class ContentEntity implements Serializable{
this.location = location;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
@Override
public int hashCode() {
final int prime = 31;

2
src/main/resources/META-INF/persistance.xml → src/main/resources/META-INF/persistence.xml

@ -1,6 +1,6 @@ @@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0" xsi:schemalocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
<persistence-unit name="Storage" transaction-type="JTA">
<persistence-unit name="default" transaction-type="JTA">
<description>Подключение к базе molokoin.ru:3306/home</description>
<jta-data-source>java:/home</jta-data-source>
<class>ru.molokoin.storage.entities.ContentEntity</class>

2
target/classes/META-INF/persistance.xml → target/classes/META-INF/persistence.xml

@ -1,6 +1,6 @@ @@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0" xsi:schemalocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
<persistence-unit name="Storage" transaction-type="JTA">
<persistence-unit name="default" transaction-type="JTA">
<description>Подключение к базе molokoin.ru:3306/home</description>
<jta-data-source>java:/home</jta-data-source>
<class>ru.molokoin.storage.entities.ContentEntity</class>

BIN
target/classes/ru/molokoin/storage/api/RestConfig.class

Binary file not shown.

BIN
target/classes/ru/molokoin/storage/api/RestStorageService.class

Binary file not shown.

BIN
target/classes/ru/molokoin/storage/beans/HardDrive.class

Binary file not shown.

BIN
target/classes/ru/molokoin/storage/beans/Storage.class

Binary file not shown.

BIN
target/classes/ru/molokoin/storage/beans/StorageFace.class

Binary file not shown.

BIN
target/classes/ru/molokoin/storage/entities/ContentEntity.class

Binary file not shown.

BIN
target/classes/ru/molokoin/storage/services/Storage.class

Binary file not shown.

BIN
target/classes/ru/molokoin/storage/services/StorageFace.class

Binary file not shown.

4
target/maven-archiver/pom.properties

@ -0,0 +1,4 @@ @@ -0,0 +1,4 @@
#Created by Apache Maven 3.8.5
groupId=ru.molokoin
artifactId=storage
version=1.0

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

@ -0,0 +1,6 @@ @@ -0,0 +1,6 @@
ru\molokoin\storage\entities\ContentEntity.class
ru\molokoin\storage\beans\StorageFace.class
ru\molokoin\storage\api\RestStorageService.class
ru\molokoin\storage\api\RestConfig.class
ru\molokoin\storage\beans\HardDrive.class
ru\molokoin\storage\beans\Storage.class

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

@ -0,0 +1,6 @@ @@ -0,0 +1,6 @@
C:\Users\Strannik\Documents\esoe\code\storage\src\main\java\ru\molokoin\storage\beans\Storage.java
C:\Users\Strannik\Documents\esoe\code\storage\src\main\java\ru\molokoin\storage\beans\StorageFace.java
C:\Users\Strannik\Documents\esoe\code\storage\src\main\java\ru\molokoin\storage\entities\ContentEntity.java
C:\Users\Strannik\Documents\esoe\code\storage\src\main\java\ru\molokoin\storage\api\RestConfig.java
C:\Users\Strannik\Documents\esoe\code\storage\src\main\java\ru\molokoin\storage\beans\HardDrive.java
C:\Users\Strannik\Documents\esoe\code\storage\src\main\java\ru\molokoin\storage\api\RestStorageService.java

BIN
target/storage.war

Binary file not shown.

9
target/storage/WEB-INF/classes/META-INF/persistence.xml

@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0" xsi:schemalocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
<persistence-unit name="default" transaction-type="JTA">
<description>Подключение к базе molokoin.ru:3306/home</description>
<jta-data-source>java:/home</jta-data-source>
<class>ru.molokoin.storage.entities.ContentEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
</persistence>

BIN
target/storage/WEB-INF/classes/ru/molokoin/storage/api/RestConfig.class

Binary file not shown.

BIN
target/storage/WEB-INF/classes/ru/molokoin/storage/api/RestStorageService.class

Binary file not shown.

BIN
target/storage/WEB-INF/classes/ru/molokoin/storage/beans/HardDrive.class

Binary file not shown.

BIN
target/storage/WEB-INF/classes/ru/molokoin/storage/beans/Storage.class

Binary file not shown.

BIN
target/storage/WEB-INF/classes/ru/molokoin/storage/beans/StorageFace.class

Binary file not shown.

BIN
target/storage/WEB-INF/classes/ru/molokoin/storage/entities/ContentEntity.class

Binary file not shown.

BIN
target/storage/WEB-INF/lib/jakarta.activation-api-2.1.0.jar

Binary file not shown.

BIN
target/storage/WEB-INF/lib/jakarta.ws.rs-api-3.1.0.jar

Binary file not shown.

BIN
target/storage/WEB-INF/lib/jakarta.xml.bind-api-4.0.0.jar

Binary file not shown.

7
target/storage/WEB-INF/web.xml

@ -0,0 +1,7 @@ @@ -0,0 +1,7 @@
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>

5
target/storage/index.jsp

@ -0,0 +1,5 @@ @@ -0,0 +1,5 @@
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
Loading…
Cancel
Save