.gitignore
.. .. @@ -0,0 +1,73 @@ 1 +2 +# Created by https://www.gitignore.io/api/eclipse3 +4 +### Eclipse ###5 +6 +.metadata7 +bin/8 +tmp/9 +*.tmp10 +*.bak11 +*.swp12 +*~.nib13 +local.properties14 +.settings/15 +.loadpath16 +.recommenders17 +18 +# External tool builders19 +.externalToolBuilders/20 +21 +# Locally stored "Eclipse launch configurations"22 +*.launch23 +24 +# PyDev specific (Python IDE for Eclipse)25 +*.pydevproject26 +27 +# CDT-specific (C/C++ Development Tooling)28 +.cproject29 +30 +# CDT- autotools31 +.autotools32 +33 +# Java annotation processor (APT)34 +.factorypath35 +36 +# PDT-specific (PHP Development Tools)37 +.buildpath38 +39 +# sbteclipse plugin40 +.target41 +42 +# Tern plugin43 +.tern-project44 +45 +# TeXlipse plugin46 +.texlipse47 +48 +# STS (Spring Tool Suite)49 +.springBeans50 +51 +# Code Recommenders52 +.recommenders/53 +54 +# Annotation Processing55 +.apt_generated/56 +57 +# Scala IDE specific (Scala & Java development for Eclipse)58 +.cache-main59 +.scala_dependencies60 +.worksheet61 +62 +### Eclipse Patch ###63 +# Eclipse Core64 +.project65 +66 +# JDT-specific (Eclipse Java Development Tools)67 +.classpath68 +69 +# Annotation Processing70 +.apt_generated71 +72 +73 +# End of https://www.gitignore.io/api/eclipsedg1cloud-core/.mvn/wrapper/maven-wrapper.jarBinary files differ
dg1cloud-core/.mvn/wrapper/maven-wrapper.properties
.. .. @@ -0,0 +1 @@ 1 +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zipdg1cloud-core/WebContent/META-INF/MANIFEST.MF
.. .. @@ -0,0 +1,3 @@ 1 +Manifest-Version: 1.02 +Class-Path:3 +dg1cloud-core/WebContent/WEB-INF/web.xml
.. .. @@ -0,0 +1,12 @@ 1 +<?xml version="1.0" encoding="UTF-8"?>2 +<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">3 + <display-name>dg1cloud-core</display-name>4 + <welcome-file-list>5 + <welcome-file>index.html</welcome-file>6 + <welcome-file>index.htm</welcome-file>7 + <welcome-file>index.jsp</welcome-file>8 + <welcome-file>default.html</welcome-file>9 + <welcome-file>default.htm</welcome-file>10 + <welcome-file>default.jsp</welcome-file>11 + </welcome-file-list>12 +</web-app>dg1cloud-core/mvnw
.. .. @@ -0,0 +1,225 @@ 1 +#!/bin/sh2 +# ----------------------------------------------------------------------------3 +# Licensed to the Apache Software Foundation (ASF) under one4 +# or more contributor license agreements. See the NOTICE file5 +# distributed with this work for additional information6 +# regarding copyright ownership. The ASF licenses this file7 +# to you under the Apache License, Version 2.0 (the8 +# "License"); you may not use this file except in compliance9 +# with the License. You may obtain a copy of the License at10 +#11 +# http://www.apache.org/licenses/LICENSE-2.012 +#13 +# Unless required by applicable law or agreed to in writing,14 +# software distributed under the License is distributed on an15 +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY16 +# KIND, either express or implied. See the License for the17 +# specific language governing permissions and limitations18 +# under the License.19 +# ----------------------------------------------------------------------------20 +21 +# ----------------------------------------------------------------------------22 +# Maven2 Start Up Batch script23 +#24 +# Required ENV vars:25 +# ------------------26 +# JAVA_HOME - location of a JDK home dir27 +#28 +# Optional ENV vars29 +# -----------------30 +# M2_HOME - location of maven2's installed home dir31 +# MAVEN_OPTS - parameters passed to the Java VM when running Maven32 +# e.g. to debug Maven itself, use33 +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=800034 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files35 +# ----------------------------------------------------------------------------36 +37 +if [ -z "$MAVEN_SKIP_RC" ] ; then38 +39 + if [ -f /etc/mavenrc ] ; then40 + . /etc/mavenrc41 + fi42 +43 + if [ -f "$HOME/.mavenrc" ] ; then44 + . "$HOME/.mavenrc"45 + fi46 +47 +fi48 +49 +# OS specific support. $var _must_ be set to either true or false.50 +cygwin=false;51 +darwin=false;52 +mingw=false53 +case "`uname`" in54 + CYGWIN*) cygwin=true ;;55 + MINGW*) mingw=true;;56 + Darwin*) darwin=true57 + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home58 + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html59 + if [ -z "$JAVA_HOME" ]; then60 + if [ -x "/usr/libexec/java_home" ]; then61 + export JAVA_HOME="`/usr/libexec/java_home`"62 + else63 + export JAVA_HOME="/Library/Java/Home"64 + fi65 + fi66 + ;;67 +esac68 +69 +if [ -z "$JAVA_HOME" ] ; then70 + if [ -r /etc/gentoo-release ] ; then71 + JAVA_HOME=`java-config --jre-home`72 + fi73 +fi74 +75 +if [ -z "$M2_HOME" ] ; then76 + ## resolve links - $0 may be a link to maven's home77 + PRG="$0"78 +79 + # need this for relative symlinks80 + while [ -h "$PRG" ] ; do81 + ls=`ls -ld "$PRG"`82 + link=`expr "$ls" : '.*-> \(.*\)$'`83 + if expr "$link" : '/.*' > /dev/null; then84 + PRG="$link"85 + else86 + PRG="`dirname "$PRG"`/$link"87 + fi88 + done89 +90 + saveddir=`pwd`91 +92 + M2_HOME=`dirname "$PRG"`/..93 +94 + # make it fully qualified95 + M2_HOME=`cd "$M2_HOME" && pwd`96 +97 + cd "$saveddir"98 + # echo Using m2 at $M2_HOME99 +fi100 +101 +# For Cygwin, ensure paths are in UNIX format before anything is touched102 +if $cygwin ; then103 + [ -n "$M2_HOME" ] &&104 + M2_HOME=`cygpath --unix "$M2_HOME"`105 + [ -n "$JAVA_HOME" ] &&106 + JAVA_HOME=`cygpath --unix "$JAVA_HOME"`107 + [ -n "$CLASSPATH" ] &&108 + CLASSPATH=`cygpath --path --unix "$CLASSPATH"`109 +fi110 +111 +# For Migwn, ensure paths are in UNIX format before anything is touched112 +if $mingw ; then113 + [ -n "$M2_HOME" ] &&114 + M2_HOME="`(cd "$M2_HOME"; pwd)`"115 + [ -n "$JAVA_HOME" ] &&116 + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"117 + # TODO classpath?118 +fi119 +120 +if [ -z "$JAVA_HOME" ]; then121 + javaExecutable="`which javac`"122 + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then123 + # readlink(1) is not available as standard on Solaris 10.124 + readLink=`which readlink`125 + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then126 + if $darwin ; then127 + javaHome="`dirname \"$javaExecutable\"`"128 + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"129 + else130 + javaExecutable="`readlink -f \"$javaExecutable\"`"131 + fi132 + javaHome="`dirname \"$javaExecutable\"`"133 + javaHome=`expr "$javaHome" : '\(.*\)/bin'`134 + JAVA_HOME="$javaHome"135 + export JAVA_HOME136 + fi137 + fi138 +fi139 +140 +if [ -z "$JAVACMD" ] ; then141 + if [ -n "$JAVA_HOME" ] ; then142 + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then143 + # IBM's JDK on AIX uses strange locations for the executables144 + JAVACMD="$JAVA_HOME/jre/sh/java"145 + else146 + JAVACMD="$JAVA_HOME/bin/java"147 + fi148 + else149 + JAVACMD="`which java`"150 + fi151 +fi152 +153 +if [ ! -x "$JAVACMD" ] ; then154 + echo "Error: JAVA_HOME is not defined correctly." >&2155 + echo " We cannot execute $JAVACMD" >&2156 + exit 1157 +fi158 +159 +if [ -z "$JAVA_HOME" ] ; then160 + echo "Warning: JAVA_HOME environment variable is not set."161 +fi162 +163 +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher164 +165 +# traverses directory structure from process work directory to filesystem root166 +# first directory with .mvn subdirectory is considered project base directory167 +find_maven_basedir() {168 +169 + if [ -z "$1" ]170 + then171 + echo "Path not specified to find_maven_basedir"172 + return 1173 + fi174 +175 + basedir="$1"176 + wdir="$1"177 + while [ "$wdir" != '/' ] ; do178 + if [ -d "$wdir"/.mvn ] ; then179 + basedir=$wdir180 + break181 + fi182 + # workaround for JBEAP-8937 (on Solaris 10/Sparc)183 + if [ -d "${wdir}" ]; then184 + wdir=`cd "$wdir/.."; pwd`185 + fi186 + # end of workaround187 + done188 + echo "${basedir}"189 +}190 +191 +# concatenates all lines of a file192 +concat_lines() {193 + if [ -f "$1" ]; then194 + echo "$(tr -s '\n' ' ' < "$1")"195 + fi196 +}197 +198 +BASE_DIR=`find_maven_basedir "$(pwd)"`199 +if [ -z "$BASE_DIR" ]; then200 + exit 1;201 +fi202 +203 +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}204 +echo $MAVEN_PROJECTBASEDIR205 +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"206 +207 +# For Cygwin, switch paths to Windows format before running java208 +if $cygwin; then209 + [ -n "$M2_HOME" ] &&210 + M2_HOME=`cygpath --path --windows "$M2_HOME"`211 + [ -n "$JAVA_HOME" ] &&212 + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`213 + [ -n "$CLASSPATH" ] &&214 + CLASSPATH=`cygpath --path --windows "$CLASSPATH"`215 + [ -n "$MAVEN_PROJECTBASEDIR" ] &&216 + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`217 +fi218 +219 +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain220 +221 +exec "$JAVACMD" \222 + $MAVEN_OPTS \223 + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \224 + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \225 + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"dg1cloud-core/mvnw.cmd
.. .. @@ -0,0 +1,143 @@ 1 +@REM ----------------------------------------------------------------------------2 +@REM Licensed to the Apache Software Foundation (ASF) under one3 +@REM or more contributor license agreements. See the NOTICE file4 +@REM distributed with this work for additional information5 +@REM regarding copyright ownership. The ASF licenses this file6 +@REM to you under the Apache License, Version 2.0 (the7 +@REM "License"); you may not use this file except in compliance8 +@REM with the License. You may obtain a copy of the License at9 +@REM10 +@REM http://www.apache.org/licenses/LICENSE-2.011 +@REM12 +@REM Unless required by applicable law or agreed to in writing,13 +@REM software distributed under the License is distributed on an14 +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15 +@REM KIND, either express or implied. See the License for the16 +@REM specific language governing permissions and limitations17 +@REM under the License.18 +@REM ----------------------------------------------------------------------------19 +20 +@REM ----------------------------------------------------------------------------21 +@REM Maven2 Start Up Batch script22 +@REM23 +@REM Required ENV vars:24 +@REM JAVA_HOME - location of a JDK home dir25 +@REM26 +@REM Optional ENV vars27 +@REM M2_HOME - location of maven2's installed home dir28 +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands29 +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending30 +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven31 +@REM e.g. to debug Maven itself, use32 +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=800033 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files34 +@REM ----------------------------------------------------------------------------35 +36 +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'37 +@echo off38 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'39 +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%40 +41 +@REM set %HOME% to equivalent of $HOME42 +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")43 +44 +@REM Execute a user defined script before this one45 +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre46 +@REM check for pre script, once with legacy .bat ending and once with .cmd ending47 +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"48 +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"49 +:skipRcPre50 +51 +@setlocal52 +53 +set ERROR_CODE=054 +55 +@REM To isolate internal variables from possible post scripts, we use another setlocal56 +@setlocal57 +58 +@REM ==== START VALIDATION ====59 +if not "%JAVA_HOME%" == "" goto OkJHome60 +61 +echo.62 +echo Error: JAVA_HOME not found in your environment. >&263 +echo Please set the JAVA_HOME variable in your environment to match the >&264 +echo location of your Java installation. >&265 +echo.66 +goto error67 +68 +:OkJHome69 +if exist "%JAVA_HOME%\bin\java.exe" goto init70 +71 +echo.72 +echo Error: JAVA_HOME is set to an invalid directory. >&273 +echo JAVA_HOME = "%JAVA_HOME%" >&274 +echo Please set the JAVA_HOME variable in your environment to match the >&275 +echo location of your Java installation. >&276 +echo.77 +goto error78 +79 +@REM ==== END VALIDATION ====80 +81 +:init82 +83 +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".84 +@REM Fallback to current working directory if not found.85 +86 +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%87 +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir88 +89 +set EXEC_DIR=%CD%90 +set WDIR=%EXEC_DIR%91 +:findBaseDir92 +IF EXIST "%WDIR%"\.mvn goto baseDirFound93 +cd ..94 +IF "%WDIR%"=="%CD%" goto baseDirNotFound95 +set WDIR=%CD%96 +goto findBaseDir97 +98 +:baseDirFound99 +set MAVEN_PROJECTBASEDIR=%WDIR%100 +cd "%EXEC_DIR%"101 +goto endDetectBaseDir102 +103 +:baseDirNotFound104 +set MAVEN_PROJECTBASEDIR=%EXEC_DIR%105 +cd "%EXEC_DIR%"106 +107 +:endDetectBaseDir108 +109 +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig110 +111 +@setlocal EnableExtensions EnableDelayedExpansion112 +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a113 +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%114 +115 +:endReadAdditionalConfig116 +117 +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"118 +119 +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"120 +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain121 +122 +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*123 +if ERRORLEVEL 1 goto error124 +goto end125 +126 +:error127 +set ERROR_CODE=1128 +129 +:end130 +@endlocal & set ERROR_CODE=%ERROR_CODE%131 +132 +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost133 +@REM check for post script, once with legacy .bat ending and once with .cmd ending134 +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"135 +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"136 +:skipRcPost137 +138 +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'139 +if "%MAVEN_BATCH_PAUSE%" == "on" pause140 +141 +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%142 +143 +exit /B %ERROR_CODE%dg1cloud-core/pom.xml
.. .. @@ -0,0 +1,94 @@ 1 +<?xml version="1.0" encoding="UTF-8"?>2 +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"3 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">4 + <modelVersion>4.0.0</modelVersion>5 +6 + <groupId>it.digione.cloud</groupId>7 + <artifactId>dg1cloud-core</artifactId>8 + <version>0.0.1-SNAPSHOT</version>9 + <packaging>jar</packaging>10 +11 + <name>dg1cloud-core</name>12 + <description>Servizio cloud per ricezione file</description>13 +14 + <parent>15 + <groupId>org.springframework.boot</groupId>16 + <artifactId>spring-boot-starter-parent</artifactId>17 + <version>2.0.3.RELEASE</version>18 + <relativePath/> <!-- lookup parent from repository -->19 + </parent>20 +21 + <properties>22 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>23 + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>24 + <java.version>1.8</java.version>25 + </properties>26 +27 + <dependencies>28 + <dependency>29 + <groupId>org.springframework.boot</groupId>30 + <artifactId>spring-boot-starter-data-jpa</artifactId>31 + </dependency>32 +33 + <dependency>34 + <groupId>org.flywaydb</groupId>35 + <artifactId>flyway-core</artifactId>36 + </dependency>37 +38 + <dependency>39 + <groupId>org.springframework.boot</groupId>40 + <artifactId>spring-boot-starter-test</artifactId>41 + <scope>test</scope>42 + </dependency>43 +44 + <dependency>45 + <groupId>org.springframework.boot</groupId>46 + <artifactId>spring-boot-starter-web</artifactId>47 + </dependency>48 +49 + <dependency>50 + <groupId>org.springframework.boot</groupId>51 + <artifactId>spring-boot-starter-tomcat</artifactId>52 + <scope>provided</scope>53 + </dependency>54 +55 + <dependency>56 + <groupId>org.postgresql</groupId>57 + <artifactId>postgresql</artifactId>58 + </dependency>59 +60 + <dependency>61 + <groupId>org.eclipse.persistence</groupId>62 + <artifactId>eclipselink</artifactId>63 + <version>2.5.0</version>64 + </dependency>65 +66 + <dependency>67 + <groupId>com.fasterxml.jackson.core</groupId>68 + <artifactId>jackson-databind</artifactId>69 + </dependency>70 +71 + <dependency>72 + <groupId>commons-io</groupId>73 + <artifactId>commons-io</artifactId>74 + <version>2.6</version>75 + </dependency>76 +77 + <dependency>78 + <groupId>commons-codec</groupId>79 + <artifactId>commons-codec</artifactId>80 + </dependency>81 +82 + </dependencies>83 +84 + <build>85 + <plugins>86 + <plugin>87 + <groupId>org.springframework.boot</groupId>88 + <artifactId>spring-boot-maven-plugin</artifactId>89 + </plugin>90 + </plugins>91 + </build>92 +93 +94 +</project>dg1cloud-core/src/main/java/META-INF/persistence.xml
.. .. @@ -0,0 +1,9 @@ 1 +<?xml version="1.0" encoding="UTF-8"?>2 +<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">3 + <persistence-unit name="dg1cloud-core">4 + <class>it.digione.dg1cloud.model.RegDocument</class>5 + <properties>6 + <property name="eclipselink.jdbc.batch-writing" value="JDBC"/>7 + </properties>8 + </persistence-unit>9 +</persistence>dg1cloud-core/src/main/java/db/migration/V0.1__DG1CLOUD.sql
.. .. @@ -0,0 +1,27 @@ 1 +-- Table: public.reg_document2 +CREATE TABLE public.reg_document3 +(4 + document_id bigint NOT NULL,5 + created timestamp without time zone NOT NULL DEFAULT now(),6 + createdby character varying(255) NOT NULL,7 + modified timestamp without time zone NOT NULL DEFAULT now(),8 + modifiedby character varying(255) NOT NULL,9 + file_hash character varying(255),10 + file_name text NOT NULL,11 + file_path text NOT NULL,12 + file_size bigint,13 + due_date date,14 + CONSTRAINT reg_document_pkey PRIMARY KEY (document_id)15 +)16 +WITH (17 + OIDS = FALSE18 +);19 +20 +CREATE SEQUENCE public.reg_document_seq21 + INCREMENT 122 + START 123 + MINVALUE 124 + MAXVALUE 922337203685477580725 + CACHE 1;26 +27 +dg1cloud-core/src/main/java/it/digione/dg1cloud/app/Dg1cloudCoreApplication.java
.. .. @@ -0,0 +1,21 @@ 1 +package it.digione.dg1cloud.app;2 +3 +import org.springframework.boot.SpringApplication;4 +import org.springframework.boot.autoconfigure.SpringBootApplication;5 +import org.springframework.boot.builder.SpringApplicationBuilder;6 +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;7 +import org.springframework.context.annotation.ComponentScan;8 +9 +@ComponentScan(basePackages="it.digione.dg1cloud")10 +@SpringBootApplication11 +public class Dg1cloudCoreApplication extends SpringBootServletInitializer {12 +13 + public static void main(String[] args) {14 + SpringApplication.run(Dg1cloudCoreApplication.class, args);15 + }16 +17 + @Override18 + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {19 + return application.sources(Dg1cloudCoreApplication.class);20 + }21 +}dg1cloud-core/src/main/java/it/digione/dg1cloud/config/AppConfig.java
.. .. @@ -0,0 +1,104 @@ 1 +package it.digione.dg1cloud.config;2 +3 +import java.io.Serializable;4 +import java.util.HashMap;5 +import java.util.Map;6 +7 +import javax.persistence.EntityManagerFactory;8 +import javax.sql.DataSource;9 +10 +import org.eclipse.persistence.config.BatchWriting;11 +import org.eclipse.persistence.config.PersistenceUnitProperties;12 +import org.eclipse.persistence.config.TargetServer;13 +import org.springframework.beans.factory.ObjectProvider;14 +import org.springframework.beans.factory.annotation.Value;15 +import org.springframework.boot.autoconfigure.EnableAutoConfiguration;16 +import org.springframework.boot.autoconfigure.domain.EntityScan;17 +import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;18 +import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;19 +import org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers;20 +import org.springframework.boot.context.properties.EnableConfigurationProperties;21 +import org.springframework.context.annotation.Bean;22 +import org.springframework.context.annotation.ComponentScan;23 +import org.springframework.context.annotation.Configuration;24 +import org.springframework.context.annotation.PropertySource;25 +import org.springframework.context.annotation.PropertySources;26 +import org.springframework.data.jpa.repository.config.EnableJpaRepositories;27 +import org.springframework.orm.jpa.JpaTransactionManager;28 +import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter;29 +import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;30 +import org.springframework.transaction.PlatformTransactionManager;31 +import org.springframework.transaction.annotation.EnableTransactionManagement;32 +import org.springframework.transaction.jta.JtaTransactionManager;33 +34 +@ComponentScan35 +@Configuration36 +@PropertySources({37 + @PropertySource(value = "classpath:/it/digione/dg1cloud/config/dg1cloud.properties", ignoreResourceNotFound=false),38 + @PropertySource(value = "file:/etc/digione/dg1cloud/application.properties", ignoreResourceNotFound=true)39 + })40 +@EnableAutoConfiguration41 +@EnableConfigurationProperties42 +@EnableJpaRepositories("it.digione.dg1cloud.repository")43 +@EntityScan("it.digione.dg1cloud.model")44 +@EnableTransactionManagement45 +public class AppConfig extends JpaBaseConfiguration implements Serializable{46 +47 + protected AppConfig(DataSource dataSource, JpaProperties properties,48 + ObjectProvider<JtaTransactionManager> jtaTransactionManager,49 + ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {50 + super(dataSource, properties, jtaTransactionManager, transactionManagerCustomizers);51 + }52 +53 + /**54 + *55 + */56 + private static final long serialVersionUID = -662074265587285778L;57 +58 + @Value("${application.version}")59 + private String applicationVersion;60 + public String getApplicationVersion() {61 + return applicationVersion;62 + }63 +64 + @Value("${repository.base.upload.path}")65 + private String repositoryBaseUploadPath;66 + public String getRepositoryBaseUploadPath() {67 + return repositoryBaseUploadPath;68 + }69 +70 + @Value("${repository.base.storage.path}")71 + private String repositoryBaseStoragePath;72 + public String getRepositoryBaseStoragePath() {73 + return repositoryBaseStoragePath;74 + }75 +76 + @Value("${external.server.address.base.url}")77 + private String externalBaseUrl;78 + public String getExternalBaseUrl() {79 + return externalBaseUrl;80 + }81 +82 + @Bean83 + public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {84 + final JpaTransactionManager transactionManager = new JpaTransactionManager();85 + transactionManager.setEntityManagerFactory(emf);86 + return transactionManager;87 + }88 +89 + @Override90 + protected AbstractJpaVendorAdapter createJpaVendorAdapter() {91 + return new EclipseLinkJpaVendorAdapter();92 + }93 +94 + @Override95 + protected Map<String, Object> getVendorProperties() {96 + final Map<String, Object> map = new HashMap<>();97 + map.put(PersistenceUnitProperties.BATCH_WRITING, BatchWriting.JDBC);98 + map.put(PersistenceUnitProperties.WEAVING, "static");99 + map.put(PersistenceUnitProperties.DEPLOY_ON_STARTUP, "true");100 + map.put(PersistenceUnitProperties.TARGET_SERVER, TargetServer.DEFAULT);101 + return map;102 + }103 +104 +}dg1cloud-core/src/main/java/it/digione/dg1cloud/config/dg1cloud.properties
.. .. @@ -0,0 +1,16 @@ 1 +application.version=v0.0.1beta2 +3 +repository.base.upload.path=/etc/dg1cloud/repository/upload4 +repository.base.storage.path=/etc/dg1cloud/repository/storage5 +6 +repository.scanner.job.fixed.delay=600007 +repository.scanner.job.initial.delay=10008 +9 +repository.cleaner.job.fixed.delay=6000010 +repository.cleaner.job.initial.delay=100011 +12 +repository.dircleaner.job.cron=0 0 5 * * *13 +14 +server.servlet.context-path=/dg1cloud15 +16 +external.server.address.base.url=http://vannux.grupposistematica.it:8080/dg1clouddg1cloud-core/src/main/java/it/digione/dg1cloud/controller/DownloadFileController.java
.. .. @@ -0,0 +1,63 @@ 1 +package it.digione.dg1cloud.controller;2 +3 +import java.io.File;4 +import java.io.FileInputStream;5 +import java.io.IOException;6 +7 +import javax.servlet.ServletContext;8 +9 +import org.slf4j.Logger;10 +import org.slf4j.LoggerFactory;11 +import org.springframework.beans.factory.annotation.Autowired;12 +import org.springframework.core.io.InputStreamResource;13 +import org.springframework.http.HttpHeaders;14 +import org.springframework.http.MediaType;15 +import org.springframework.http.ResponseEntity;16 +import org.springframework.stereotype.Controller;17 +import org.springframework.web.bind.annotation.RequestMapping;18 +import org.springframework.web.bind.annotation.RequestParam;19 +20 +import it.digione.dg1cloud.model.RegDocument;21 +import it.digione.dg1cloud.repository.RegDocumentRepository;22 +import it.digione.dg1cloud.service.CloudService;23 +24 +@Controller25 +public class DownloadFileController {26 +27 + private static final Logger logger = LoggerFactory.getLogger(CloudService.class);28 +29 + @Autowired private ServletContext servletContext;30 + @Autowired private RegDocumentRepository regDocumentRepository;31 +32 + @RequestMapping("/downloadFile")33 + public ResponseEntity<InputStreamResource> downloadFile(@RequestParam String fileName, @RequestParam long id) throws IOException {34 +35 + logger.debug("Avvio download file {} con id {}, fileName, id");36 +37 + MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;38 + try {39 + mediaType = MediaType.parseMediaType(servletContext.getMimeType(fileName));40 + } catch (Exception e) {41 + logger.warn("Errore nello stabilire il mime type del file. Verrà usato " + mediaType.toString(), e);42 + }43 +44 + RegDocument regDocument = regDocumentRepository.getOne(id);45 +46 + if (regDocument.getFileName().equalsIgnoreCase(fileName) == false ) {47 + logger.error("Il nome del file richiesto non corrisponde con quello referenziato dall'id");48 + throw new RuntimeException("Il nome del file richiesto non corrisponde con quello referenziato dall'id");49 + }50 +51 + File file = new File(regDocument.getFilePath());52 + FileInputStream fis = new FileInputStream(file);53 + InputStreamResource isr = new InputStreamResource(fis);54 + return ResponseEntity.ok()55 + // Content-Disposition56 + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())57 + // Content-Type58 + .contentType(mediaType)59 + // Contet-Length60 + .contentLength(file.length()) //61 + .body(isr);62 + }63 +}dg1cloud-core/src/main/java/it/digione/dg1cloud/model/RegDocument.java
.. .. @@ -0,0 +1,152 @@ 1 +package it.digione.dg1cloud.model;2 +3 +import java.io.Serializable;4 +import java.util.Date;5 +6 +import javax.persistence.*;7 +8 +/**9 + * The persistent class for the reg_classification database table.10 + *11 + */12 +@Entity13 +@Table(name="reg_document")14 +@Cacheable(false)15 +@SequenceGenerator(name="reg_document_seq", sequenceName="reg_document_seq", allocationSize=1 )16 +public class RegDocument implements Serializable {17 +18 + private static final long serialVersionUID = -3682129109212204091L;19 +20 + @Id21 + @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="reg_document_seq")22 + @Column(name="document_id")23 + private Long documentId;24 +25 + @Temporal(TemporalType.TIMESTAMP)26 + private Date created;27 +28 + @Column(name="createdby")29 + private String createdBy;30 +31 + @Temporal(TemporalType.TIMESTAMP)32 + private Date modified;33 +34 + @Column(name="modifiedby")35 + private String modifiedBy;36 +37 + @Column(name="file_hash")38 + private String fileHash;39 +40 + @Column(name="file_name")41 + private String fileName;42 +43 + @Column(name="file_path")44 + private String filePath;45 +46 + @Column(name="file_size")47 + private Long fileSize;48 +49 + @Temporal(TemporalType.TIMESTAMP)50 + @Column(name="due_date")51 + private Date dueDate;52 +53 + public RegDocument() {54 + }55 +56 + @PrePersist57 + public void prePersist() {58 + Date now = new Date();59 + if(created == null) //We set default value in case if the value is not set yet.60 + created = now;61 + if(modified == null) //We set default value in case if the value is not set yet.62 + modified = now;63 + }64 +65 + public Long getDocumentId() {66 + return documentId;67 + }68 +69 + public void setDocumentId(Long documentId) {70 + this.documentId = documentId;71 + }72 +73 + public Date getCreated() {74 + return created;75 + }76 +77 + public void setCreated(Date created) {78 + this.created = created;79 + }80 +81 + public String getCreatedBy() {82 + return createdBy;83 + }84 +85 + public void setCreatedBy(String createdBy) {86 + this.createdBy = createdBy;87 + }88 +89 + public Date getModified() {90 + return modified;91 + }92 +93 + public void setModified(Date modified) {94 + this.modified = modified;95 + }96 +97 + public String getModifiedBy() {98 + return modifiedBy;99 + }100 +101 + public void setModifiedBy(String modifiedBy) {102 + this.modifiedBy = modifiedBy;103 + }104 +105 + public String getFileHash() {106 + return fileHash;107 + }108 +109 + public void setFileHash(String fileHash) {110 + this.fileHash = fileHash;111 + }112 +113 + public String getFileName() {114 + return fileName;115 + }116 +117 + public void setFileName(String fileName) {118 + this.fileName = fileName;119 + }120 +121 + public String getFilePath() {122 + return filePath;123 + }124 +125 + public void setFilePath(String filePath) {126 + this.filePath = filePath;127 + }128 +129 + public Long getFileSize() {130 + return fileSize;131 + }132 +133 + public void setFileSize(Long fileSize) {134 + this.fileSize = fileSize;135 + }136 +137 + public Date getDueDate() {138 + return dueDate;139 + }140 +141 + public void setDueDate(Date dueDate) {142 + this.dueDate = dueDate;143 + }144 +145 + @Override146 + public String toString() {147 + return "RegDocument [documentId=" + documentId + ", created=" + created + ", createdBy=" + createdBy148 + + ", modified=" + modified + ", modifiedBy=" + modifiedBy + ", fileHash=" + fileHash + ", filePath="149 + + filePath + ", fileSize=" + fileSize + ", dueDate=" + dueDate + "]";150 + }151 +152 +}dg1cloud-core/src/main/java/it/digione/dg1cloud/pojo/UploadedFileDescriptor.java
.. .. @@ -0,0 +1,29 @@ 1 +package it.digione.dg1cloud.pojo;2 +3 +import java.util.Date;4 +5 +public class UploadedFileDescriptor {6 +7 + private String fileName;8 + private String sha256;9 + private Date dueDate; //Data nel formato ISO-8601 - es: 2018-07-27T18:25:43.511Z10 +11 + public String getFileName() {12 + return fileName;13 + }14 + public void setFileName(String fileName) {15 + this.fileName = fileName;16 + }17 + public String getSha256() {18 + return sha256;19 + }20 + public void setSha256(String sha256) {21 + this.sha256 = sha256;22 + }23 + public Date getDueDate() {24 + return dueDate;25 + }26 + public void setDueDate(Date dueDate) {27 + this.dueDate = dueDate;28 + }29 +}dg1cloud-core/src/main/java/it/digione/dg1cloud/pojo/UploadedFileDescriptorOk.java
.. .. @@ -0,0 +1,20 @@ 1 +package it.digione.dg1cloud.pojo;2 +3 +public class UploadedFileDescriptorOk {4 +5 + private String fileName;6 + private String url;7 +8 + public String getFileName() {9 + return fileName;10 + }11 + public void setFileName(String fileName) {12 + this.fileName = fileName;13 + }14 + public String getUrl() {15 + return url;16 + }17 + public void setUrl(String url) {18 + this.url = url;19 + }20 +}dg1cloud-core/src/main/java/it/digione/dg1cloud/repository/RegDocumentRepository.java
.. .. @@ -0,0 +1,23 @@ 1 +package it.digione.dg1cloud.repository;2 +3 +import java.util.List;4 +5 +import org.springframework.data.jpa.repository.JpaRepository;6 +import org.springframework.data.jpa.repository.Query;7 +import org.springframework.data.repository.query.Param;8 +import org.springframework.stereotype.Repository;9 +import org.springframework.transaction.annotation.Propagation;10 +import org.springframework.transaction.annotation.Transactional;11 +12 +import it.digione.dg1cloud.model.RegDocument;13 +14 +@Repository15 +@Transactional( propagation = Propagation.REQUIRED )16 +public interface RegDocumentRepository extends JpaRepository<RegDocument, Long> {17 +18 + @Query("SELECT d FROM RegDocument d WHERE d.fileHash = :fileHash and d.fileName = :fileName")19 + RegDocument findOneByHashAndName(@Param("fileHash") String fileHash, @Param("fileName") String fileName);20 +21 + @Query("SELECT d FROM RegDocument d WHERE CURRENT_DATE > d.dueDate")22 + List<RegDocument> findAllRegDocumentExpired();23 +}dg1cloud-core/src/main/java/it/digione/dg1cloud/scheduler/RepositoryJob.java
.. .. @@ -0,0 +1,56 @@ 1 +package it.digione.dg1cloud.scheduler;2 +3 +import java.io.IOException;4 +import java.security.NoSuchAlgorithmException;5 +6 +import org.slf4j.Logger;7 +import org.slf4j.LoggerFactory;8 +import org.springframework.beans.factory.annotation.Autowired;9 +import org.springframework.context.annotation.Configuration;10 +import org.springframework.scheduling.annotation.EnableScheduling;11 +import org.springframework.scheduling.annotation.Scheduled;12 +13 +import com.fasterxml.jackson.core.JsonParseException;14 +import com.fasterxml.jackson.databind.JsonMappingException;15 +16 +import it.digione.dg1cloud.service.CleanerService;17 +import it.digione.dg1cloud.service.CloudService;18 +19 +@Configuration20 +@EnableScheduling21 +public class RepositoryJob {22 +23 + private static final Logger logger = LoggerFactory.getLogger(RepositoryJob.class);24 +25 + @Autowired private CloudService cloudService;26 + @Autowired private CleanerService cleanerService;27 +28 + @Scheduled(29 + fixedDelayString = "${repository.scanner.job.fixed.delay}",30 + initialDelayString = "${repository.scanner.job.initial.delay}"31 + )32 + public void scannerJob() throws JsonParseException, JsonMappingException, NoSuchAlgorithmException, IOException {33 + logger.debug("Avvio servizio controllo home directory");34 + cloudService.scannAccountHomeDirs();35 + logger.debug("Fine");36 + }37 +38 + @Scheduled(39 + fixedDelayString = "${repository.cleaner.job.fixed.delay}",40 + initialDelayString = "${repository.cleaner.job.initial.delay}"41 + )42 + public void cleanerJob() {43 + logger.debug("Avvio servizio rimozione file scaduti");44 + cleanerService.cleanExpiredStoredFiles();45 + logger.debug("Fine");46 + }47 +48 + @Scheduled(49 + cron = "${repository.dircleaner.job.cron}"50 + )51 + public void dirCleanerJob() {52 + logger.debug("Avvio servizio rimozione directory vuote");53 + cleanerService.cleanEmptyStorageFolder();54 + logger.debug("Fine");55 + }56 +}dg1cloud-core/src/main/java/it/digione/dg1cloud/service/CleanerService.java
.. .. @@ -0,0 +1,60 @@ 1 +package it.digione.dg1cloud.service;2 +3 +import java.io.File;4 +import java.io.IOException;5 +import java.util.List;6 +7 +import org.apache.commons.io.FileUtils;8 +import org.slf4j.Logger;9 +import org.slf4j.LoggerFactory;10 +import org.springframework.beans.factory.annotation.Autowired;11 +import org.springframework.stereotype.Service;12 +13 +import it.digione.dg1cloud.config.AppConfig;14 +import it.digione.dg1cloud.model.RegDocument;15 +import it.digione.dg1cloud.repository.RegDocumentRepository;16 +17 +@Service("cleanerService")18 +public class CleanerService {19 +20 + private static final Logger logger = LoggerFactory.getLogger(CleanerService.class);21 +22 + @Autowired private Utils utils;23 + @Autowired private AppConfig appConfig;24 + @Autowired private RegDocumentRepository regDocumentRepository;25 +26 + public void cleanExpiredStoredFiles() {27 +28 + List<RegDocument> regDocuments = regDocumentRepository.findAllRegDocumentExpired();29 + logger.debug("Trovati {} documenti da cancellare", regDocuments.size());30 +31 + for ( RegDocument regDocument : regDocuments ) {32 + logger.debug("Rimozione file {}", regDocument.getFilePath());33 + File cloudFile = new File( regDocument.getFilePath() );34 + if (cloudFile.exists() == true ) {35 + FileUtils.deleteQuietly(cloudFile);36 + } else {37 + logger.debug("File gia' rimosso. Procedo alla rimozione del record");38 + }39 + logger.debug("Rimozione record");40 + regDocumentRepository.delete(regDocument);41 + logger.debug("Record rimosso");42 +43 + try {44 + utils.deleteDir(cloudFile.getParentFile());45 + } catch (Exception e) {46 + logger.warn("ERRORE: Problemi nella rimozione della directory", e);47 + }48 + }49 + }50 +51 + public void cleanEmptyStorageFolder() {52 + String baseStoragePath = appConfig.getRepositoryBaseStoragePath();53 + logger.debug("Avvio esplorazione ricorsiva directory vuote da eliminare partendo da {}", baseStoragePath);54 + try {55 + utils.deleteEmptyDirectoriesRecursive(new File(baseStoragePath));56 + } catch (IOException e) {57 + logger.error("Errore nell'esplorazione delle sotto directory", e);58 + }59 + }60 +}dg1cloud-core/src/main/java/it/digione/dg1cloud/service/CloudService.java
.. .. @@ -0,0 +1,332 @@ 1 +package it.digione.dg1cloud.service;2 +3 +import java.io.File;4 +import java.io.FileInputStream;5 +import java.io.FileNotFoundException;6 +import java.io.IOException;7 +import java.io.InputStream;8 +import java.net.URL;9 +import java.nio.charset.StandardCharsets;10 +import java.security.NoSuchAlgorithmException;11 +import java.time.LocalDate;12 +import java.time.ZoneId;13 +14 +import org.apache.commons.codec.digest.DigestUtils;15 +import org.apache.commons.io.FileUtils;16 +import org.apache.commons.io.FilenameUtils;17 +import org.slf4j.Logger;18 +import org.slf4j.LoggerFactory;19 +import org.springframework.beans.factory.annotation.Autowired;20 +import org.springframework.stereotype.Service;21 +22 +import com.fasterxml.jackson.core.JsonParseException;23 +import com.fasterxml.jackson.core.type.TypeReference;24 +import com.fasterxml.jackson.databind.JsonMappingException;25 +import com.fasterxml.jackson.databind.ObjectMapper;26 +import com.fasterxml.jackson.databind.SerializationFeature;27 +28 +import it.digione.dg1cloud.config.AppConfig;29 +import it.digione.dg1cloud.model.RegDocument;30 +import it.digione.dg1cloud.pojo.UploadedFileDescriptor;31 +import it.digione.dg1cloud.pojo.UploadedFileDescriptorOk;32 +import it.digione.dg1cloud.repository.RegDocumentRepository;33 +34 +@Service("cloudService")35 +public class CloudService {36 +37 + private static final Logger logger = LoggerFactory.getLogger(CloudService.class);38 +39 + @Autowired private AppConfig appConfig;40 + @Autowired private Utils utils;41 + @Autowired private RegDocumentRepository regDocumentRepository;42 +43 + public void scannAccountHomeDirs() throws JsonParseException, JsonMappingException, NoSuchAlgorithmException, IOException {44 +45 + String repositoryPath = appConfig.getRepositoryBaseUploadPath();46 + File basePath = new File(repositoryPath);47 +48 + if ( basePath.exists() == false || basePath.isDirectory() == false )49 + throw new RuntimeException("La directory '" + basePath.getAbsolutePath() + "' non esiste oppure non e' una directory");50 +51 + for ( File folder : basePath.listFiles(File::isDirectory)) {52 + for ( File descriptor : folder.listFiles(53 + (dir, name) -> {54 + return name.toLowerCase().endsWith(".dg1cloud");55 + }))56 + {57 + boolean checkFile = false;58 + try {59 + checkFile = checkFile(descriptor.getAbsolutePath());60 + } catch (Exception e ) {61 + logger.error("Errore durante la fase di verifica del file", e);62 + writeKoFile(descriptor.getAbsolutePath(), "Errore durante la fase di verifica del file\n" + e.getMessage());63 + continue;64 + }65 +66 + if ( checkFile == true ) {67 + logger.debug("Controllo file descrittore completato con successo");68 + try {69 + storeFile(descriptor.getAbsolutePath());70 + } catch (Exception e) {71 + writeKoFile(descriptor.getAbsolutePath(), "Errore duranto la memorizzazione del file nello store\n" + e.getMessage());72 + }73 + } else {74 + logger.debug("Il file non ha passato le verifiche");75 + }76 + }77 + }78 + }79 +80 + public boolean checkFile(String cloudFileDescriptorPath) throws IOException, NoSuchAlgorithmException {81 + logger.debug("Controllo il file {}", cloudFileDescriptorPath);82 +83 + TypeReference<UploadedFileDescriptor> typeReference = new TypeReference<UploadedFileDescriptor>() {};84 + File cloudFileDescriptor = new File(cloudFileDescriptorPath);85 +86 + String koMessage = null;87 +88 + if ( cloudFileDescriptor.exists() == false ) {89 + koMessage = "Il file descrittore inviato '" + cloudFileDescriptor + "' non esiste";90 + writeKoFile(cloudFileDescriptorPath, koMessage);91 + return false;92 + }93 +94 + if ( cloudFileDescriptor.isFile() == false ) {95 + koMessage = "Il file descrittore inviato '" + cloudFileDescriptor + "' non e' di tipo file";96 + writeKoFile(cloudFileDescriptorPath, koMessage);97 + return false;98 + }99 +100 + InputStream is = new FileInputStream(cloudFileDescriptor);101 +102 + ObjectMapper mapper = new ObjectMapper();103 +104 + UploadedFileDescriptor uploadedFileDescriptor;105 + try {106 + uploadedFileDescriptor = mapper.readValue(is, typeReference);107 + } catch (IOException e) {108 + koMessage = "Il file descrittore non conforme:\n" + e.getMessage();109 + writeKoFile(cloudFileDescriptorPath, koMessage);110 + return false;111 + }112 +113 + is.close();114 +115 + File uploadedFile = new File(cloudFileDescriptor.getParentFile(), uploadedFileDescriptor.getFileName());116 + if ( uploadedFile.exists() == false ) {117 + koMessage = "Il file inviato '" + uploadedFile + "' non esiste";118 + writeKoFile(cloudFileDescriptorPath, koMessage);119 + return false;120 + }121 +122 + if ( uploadedFile.isFile() == false ) {123 + koMessage = "Il file inviato '" + uploadedFile + "' non e' di tipo file";124 + writeKoFile(cloudFileDescriptorPath, koMessage);125 + return false;126 + }127 +128 + FileInputStream fis = new FileInputStream(uploadedFile);129 + String hash = DigestUtils.sha256Hex(fis);130 + fis.close();131 +132 + if ( hash.equalsIgnoreCase(uploadedFileDescriptor.getSha256()) == false ) {133 + koMessage = "L'hash del file inviato non corrisponde con l'hash dichiarato nel descrittore del file:\n\t" +134 + "hash file inviato: " + hash + "\n\t" +135 + "hash dichiarato nel descrittore: " + uploadedFileDescriptor.getSha256();136 + writeKoFile(cloudFileDescriptorPath, koMessage);137 + return false;138 + }139 +140 + return true;141 + }142 +143 + public void storeFile(String cloudFileDescriptorPath) {144 + logger.debug("Avvio processo di memorizzazione file nello store");145 + TypeReference<UploadedFileDescriptor> typeReference = new TypeReference<UploadedFileDescriptor>() {};146 + File cloudFileDescriptor = new File(cloudFileDescriptorPath);147 +148 + InputStream is;149 + try {150 + is = new FileInputStream(cloudFileDescriptor);151 + } catch (FileNotFoundException e) {152 + throw new RuntimeException("Errore apertura stream file descrittore", e);153 + }154 +155 + ObjectMapper mapper = new ObjectMapper();156 +157 + UploadedFileDescriptor uploadedFileDescriptor;158 + try {159 + uploadedFileDescriptor = mapper.readValue(is, typeReference);160 + } catch (IOException e) {161 + throw new RuntimeException("Errore caricamento classe dal json del descrittore", e);162 + }163 +164 + logger.debug("Controllo esistenza file sul db");165 + RegDocument regDocument = regDocumentRepository.findOneByHashAndName(uploadedFileDescriptor.getSha256(), uploadedFileDescriptor.getFileName());166 +167 + String userName = cloudFileDescriptor.getParentFile().getName();168 +169 + File uploadedFile = new File(getUploadedFilePath(cloudFileDescriptorPath));170 +171 + if ( regDocument == null ) {172 +173 + logger.debug("Creazione nuovo record per il documento da conservare");174 + regDocument = new RegDocument();175 + regDocument.setCreatedBy(userName);176 + regDocument.setModifiedBy(userName);177 + regDocument.setFileHash(uploadedFileDescriptor.getSha256());178 + regDocument.setFileName(uploadedFileDescriptor.getFileName());179 + regDocument.setFileSize(uploadedFile.length());180 + regDocument.setDueDate(uploadedFileDescriptor.getDueDate());181 + regDocument.setFilePath("");182 +183 + regDocumentRepository.save(regDocument);184 +185 + } else {186 + logger.debug("Trovato 1 record per il documento da memorizzare");187 + }188 +189 + try {190 + moveUploadedFileToStorage(uploadedFile.getAbsolutePath(), regDocument);191 + } catch (Exception e) {192 + try {193 + writeKoFile(cloudFileDescriptorPath, e.getMessage());194 + } finally {195 + logger.debug("Rimozione regDocument");196 + regDocumentRepository.delete(regDocument);197 + }198 + }199 + try {200 + createOkFile(cloudFileDescriptorPath, regDocument);201 + } catch (Exception e) {202 + try {203 + writeKoFile(cloudFileDescriptorPath, e.getMessage());204 + } finally {205 + logger.debug("Rimozione regDocument");206 + regDocumentRepository.delete(regDocument);207 + }208 + }209 + }210 +211 + private void moveUploadedFileToStorage( String source, RegDocument regDocument ) throws IOException {212 + logger.debug("Spostamento file nello storage");213 +214 + String sha256Descriptor = regDocument.getFileHash();215 +216 + File sourceFile = new File(source);217 + File destinationFile = new File(generateStoragePath(regDocument));218 +219 + if ( destinationFile.exists() == false ) {220 + logger.debug("Creazione alberatura directory: " + destinationFile.getParent());221 + FileUtils.forceMkdirParent(destinationFile);222 + FileUtils.copyFile(sourceFile, destinationFile);223 + } else {224 + logger.debug("Il file risulta gia' presente nello storage. Verifico l'integrita'");225 + FileInputStream fis = new FileInputStream(destinationFile);226 + String hash = DigestUtils.sha256Hex(fis);227 + fis.close();228 + if ( sha256Descriptor.equalsIgnoreCase(hash) == false ) {229 + throw new IllegalStateException("L'hash del file nello storage non corrisponde con l'hash dichiarato nel descrittore del file:\n\t" +230 + "hash file inviato: " + hash + "\n\t" +231 + "hash dichiarato nel descrittore: " + sha256Descriptor);232 + }233 + }234 +235 + regDocument.setFilePath(destinationFile.getAbsolutePath());236 + logger.debug("Salvo il path nel regDocument: {}", regDocument.getFilePath());237 + regDocumentRepository.save(regDocument);238 + }239 +240 + private void createOkFile( String cloudFileDescriptorPath, RegDocument regDocument ) throws IOException {241 + logger.debug("Creazione file di OK");242 +243 + File fileDescriptor = new File(cloudFileDescriptorPath);244 + File okFile = new File(fileDescriptor.getParentFile(), fileDescriptor.getName() + ".ok");245 +246 + ObjectMapper mapper = new ObjectMapper();247 + mapper.enable(SerializationFeature.INDENT_OUTPUT);248 + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);249 +250 + UploadedFileDescriptorOk uploadedFileDescriptorOk = new UploadedFileDescriptorOk();251 +252 + uploadedFileDescriptorOk.setFileName(regDocument.getFileName());253 +254 + URL url = utils.generateUrl(regDocument);255 +256 + uploadedFileDescriptorOk.setUrl(url.toExternalForm());257 +258 + try {259 + String json = mapper.writeValueAsString(uploadedFileDescriptorOk);260 + logger.debug("Scrittura json di ok:\n{}", json);261 + FileUtils.writeStringToFile(okFile, json, StandardCharsets.UTF_8);262 + } catch (IOException e) {263 + throw new RuntimeException("Errore nella scrittura del file di OK", e);264 + }265 +266 + File cloudFile = new File( getUploadedFilePath(cloudFileDescriptorPath) );267 + if (cloudFile.exists() == true )268 + FileUtils.deleteQuietly(cloudFile);269 +270 + try {271 + FileUtils.forceDelete(fileDescriptor);272 + } catch (IOException e) {273 + throw new RuntimeException("Errore rimozione del file descrittore", e);274 + }275 + }276 +277 + public void writeKoFile( String cloudFileDescriptorPath, String errorMessage ) {278 + logger.debug("Si e' verificato il seguente errore nella verifica tramite {}: {}", cloudFileDescriptorPath, errorMessage);279 +280 + File fileDescriptor = new File(cloudFileDescriptorPath);281 + File koFile = new File(fileDescriptor.getParentFile(), fileDescriptor.getName() + ".ko");282 +283 + try {284 + FileUtils.writeStringToFile(koFile, errorMessage, StandardCharsets.UTF_8);285 + } catch (IOException e) {286 + throw new RuntimeException("Errore nella scrittura del file di KO", e);287 + }288 +289 + File cloudFile = new File( getUploadedFilePath(cloudFileDescriptorPath) );290 + if (cloudFile.exists() == true )291 + FileUtils.deleteQuietly(cloudFile);292 +293 + try {294 + FileUtils.forceDelete(fileDescriptor);295 + } catch (IOException e) {296 + throw new RuntimeException("Errore rimozione del file descrittore", e);297 + }298 + }299 +300 + public String getUploadedFilePath( String cloudFileDescriptorPath ) {301 + File fileDescriptor = new File(cloudFileDescriptorPath);302 + return fileDescriptor.getParentFile().getAbsolutePath() + File.separator + FilenameUtils.getBaseName(fileDescriptor.getName());303 + }304 +305 + private String generateStoragePath( RegDocument regDocument ) {306 +307 + if ( regDocument.getCreated() == null )308 + throw new IllegalStateException("La data di creazione del RegDocument non e' valorizzata");309 +310 + LocalDate localDate = regDocument.getCreated().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();311 + int year = localDate.getYear();312 + int month = localDate.getMonthValue();313 + int day = localDate.getDayOfMonth();314 +315 + StringBuffer sb = new StringBuffer();316 + sb.append(appConfig.getRepositoryBaseStoragePath());317 + sb.append(File.separator);318 + sb.append(regDocument.getCreatedBy());319 + sb.append(File.separator);320 + sb.append(year);321 + sb.append(File.separator);322 + sb.append(month);323 + sb.append(File.separator);324 + sb.append(day);325 + sb.append(File.separator);326 + sb.append(regDocument.getDocumentId());327 + sb.append(File.separator);328 + sb.append(regDocument.getFileName());329 +330 + return sb.toString();331 + }332 +}dg1cloud-core/src/main/java/it/digione/dg1cloud/service/Utils.java
.. .. @@ -0,0 +1,52 @@ 1 +package it.digione.dg1cloud.service;2 +3 +import java.io.File;4 +import java.io.IOException;5 +import java.net.MalformedURLException;6 +import java.net.URL;7 +8 +import org.apache.commons.io.FileUtils;9 +import org.slf4j.Logger;10 +import org.slf4j.LoggerFactory;11 +import org.springframework.beans.factory.annotation.Autowired;12 +import org.springframework.stereotype.Service;13 +import org.springframework.web.util.UriBuilder;14 +import org.springframework.web.util.UriComponentsBuilder;15 +16 +import it.digione.dg1cloud.config.AppConfig;17 +import it.digione.dg1cloud.model.RegDocument;18 +19 +@Service("utils")20 +public class Utils {21 +22 + @Autowired private AppConfig appConfig;23 +24 + private static final Logger logger = LoggerFactory.getLogger(CloudService.class);25 +26 + public URL generateUrl(RegDocument regDocument) throws MalformedURLException {27 + logger.debug("Genero l'url per il record file {} con id {}", regDocument.getFileName(), regDocument.getDocumentId());28 + UriBuilder uriBuilder = UriComponentsBuilder.fromUriString(appConfig.getExternalBaseUrl());29 + uriBuilder.path("/downloadFile");30 + uriBuilder.queryParam("fileName", regDocument.getFileName());31 + uriBuilder.queryParam("id", regDocument.getDocumentId());32 + return uriBuilder.build().toURL();33 + }34 +35 + public void deleteDir( File directory ) throws IOException {36 + logger.debug("Rimozione directory {}", directory.getAbsolutePath());37 + FileUtils.deleteDirectory(directory);38 + }39 +40 + public void deleteEmptyDirectoriesRecursive( File directory) throws IOException {41 + for (File subDirectory : directory.listFiles(File::isDirectory) ) {42 + logger.debug("Analizzo sottodirectory {}", subDirectory.getAbsolutePath());43 + deleteEmptyDirectoriesRecursive(subDirectory);44 + }45 + if ( directory.listFiles().length == 0 ) {46 + logger.debug("La directory {} e' vuota", directory.getAbsolutePath());47 + deleteDir(directory);48 + } else {49 + logger.debug("La directory {} non e' vuota", directory.getAbsolutePath());50 + }51 + }52 +}dg1cloud-core/src/main/resources/application.properties
.. .. @@ -0,0 +1,19 @@ 1 +spring.datasource.url=jdbc:postgresql://localhost:5432/dg1cloud2 +spring.datasource.username=postgres3 +spring.datasource.password=passero4 +spring.datasource.driver-class-name=org.postgresql.Driver5 +spring.datasource.tomcat.initial-size=106 +spring.datasource.tomcat.max-wait=300007 +spring.datasource.tomcat.max-active=258 +spring.datasource.tomcat.max-idle=209 +spring.datasource.tomcat.min-idle=1010 +spring.datasource.tomcat.test-on-borrow=true11 +spring.datasource.tomcat.test-while-idle=true12 +spring.datasource.tomcat.validation-query=SELECT 113 +spring.datasource.type=com.zaxxer.hikari.HikariDataSource14 +15 +spring.jpa.open-in-view=true16 +17 +server.address=vannux.grupposistematica.it18 +19 +logging.level.it.digione.dg1cloud=DEBUGdg1cloud-core/src/test/java/it/digione/cloud/Dg1cloudCoreApplicationTests.java
.. .. @@ -0,0 +1,22 @@ 1 +package it.digione.cloud;2 +3 +import org.junit.Test;4 +import org.junit.runner.RunWith;5 +import org.springframework.beans.factory.annotation.Autowired;6 +import org.springframework.boot.test.context.SpringBootTest;7 +import org.springframework.test.context.junit4.SpringRunner;8 +9 +import it.digione.dg1cloud.app.Dg1cloudCoreApplication;10 +import it.digione.dg1cloud.service.CleanerService;11 +12 +@RunWith(SpringRunner.class)13 +@SpringBootTest(classes = Dg1cloudCoreApplication.class)14 +public class Dg1cloudCoreApplicationTests {15 +16 + @Autowired CleanerService cleanerService;17 + @Test18 + public void contextLoads() {19 + cleanerService.cleanEmptyStorageFolder();20 + }21 +22 +}dg1cloud-core/target/classes/META-INF/MANIFEST.MF
.. .. @@ -0,0 +1,10 @@ 1 +Manifest-Version: 1.02 +Implementation-Title: dg1cloud-core3 +Implementation-Version: 0.0.1-SNAPSHOT4 +Built-By: lvannucci5 +Implementation-Vendor-Id: it.digione.cloud6 +Build-Jdk: 1.8.0_1317 +Implementation-URL: https://projects.spring.io/spring-boot/#/spring-bo8 + ot-starter-parent/dg1cloud-core9 +Created-By: Maven Integration for Eclipse10 +dg1cloud-core/target/classes/META-INF/maven/it.digione.cloud/dg1cloud-core/pom.properties
.. .. @@ -0,0 +1,7 @@ 1 +#Generated by Maven Integration for Eclipse2 +#Wed Aug 01 09:46:22 CEST 20183 +version=0.0.1-SNAPSHOT4 +groupId=it.digione.cloud5 +m2e.projectName=dg1cloud-core6 +m2e.projectLocation=E\:\\users\\lvannucci\\GIT_Projects\\dg1cloud\\dg1cloud-core7 +artifactId=dg1cloud-coredg1cloud-core/target/classes/META-INF/maven/it.digione.cloud/dg1cloud-core/pom.xml
.. .. @@ -0,0 +1,94 @@ 1 +<?xml version="1.0" encoding="UTF-8"?>2 +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"3 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">4 + <modelVersion>4.0.0</modelVersion>5 +6 + <groupId>it.digione.cloud</groupId>7 + <artifactId>dg1cloud-core</artifactId>8 + <version>0.0.1-SNAPSHOT</version>9 + <packaging>jar</packaging>10 +11 + <name>dg1cloud-core</name>12 + <description>Servizio cloud per ricezione file</description>13 +14 + <parent>15 + <groupId>org.springframework.boot</groupId>16 + <artifactId>spring-boot-starter-parent</artifactId>17 + <version>2.0.3.RELEASE</version>18 + <relativePath/> <!-- lookup parent from repository -->19 + </parent>20 +21 + <properties>22 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>23 + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>24 + <java.version>1.8</java.version>25 + </properties>26 +27 + <dependencies>28 + <dependency>29 + <groupId>org.springframework.boot</groupId>30 + <artifactId>spring-boot-starter-data-jpa</artifactId>31 + </dependency>32 +33 + <dependency>34 + <groupId>org.flywaydb</groupId>35 + <artifactId>flyway-core</artifactId>36 + </dependency>37 +38 + <dependency>39 + <groupId>org.springframework.boot</groupId>40 + <artifactId>spring-boot-starter-test</artifactId>41 + <scope>test</scope>42 + </dependency>43 +44 + <dependency>45 + <groupId>org.springframework.boot</groupId>46 + <artifactId>spring-boot-starter-web</artifactId>47 + </dependency>48 +49 + <dependency>50 + <groupId>org.springframework.boot</groupId>51 + <artifactId>spring-boot-starter-tomcat</artifactId>52 + <scope>provided</scope>53 + </dependency>54 +55 + <dependency>56 + <groupId>org.postgresql</groupId>57 + <artifactId>postgresql</artifactId>58 + </dependency>59 +60 + <dependency>61 + <groupId>org.eclipse.persistence</groupId>62 + <artifactId>eclipselink</artifactId>63 + <version>2.5.0</version>64 + </dependency>65 +66 + <dependency>67 + <groupId>com.fasterxml.jackson.core</groupId>68 + <artifactId>jackson-databind</artifactId>69 + </dependency>70 +71 + <dependency>72 + <groupId>commons-io</groupId>73 + <artifactId>commons-io</artifactId>74 + <version>2.6</version>75 + </dependency>76 +77 + <dependency>78 + <groupId>commons-codec</groupId>79 + <artifactId>commons-codec</artifactId>80 + </dependency>81 +82 + </dependencies>83 +84 + <build>85 + <plugins>86 + <plugin>87 + <groupId>org.springframework.boot</groupId>88 + <artifactId>spring-boot-maven-plugin</artifactId>89 + </plugin>90 + </plugins>91 + </build>92 +93 +94 +</project>dg1cloud-core/target/classes/META-INF/persistence.xml
.. .. @@ -0,0 +1,9 @@ 1 +<?xml version="1.0" encoding="UTF-8"?>2 +<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">3 + <persistence-unit name="dg1cloud-core">4 + <class>it.digione.dg1cloud.model.RegDocument</class>5 + <properties>6 + <property name="eclipselink.jdbc.batch-writing" value="JDBC"/>7 + </properties>8 + </persistence-unit>9 +</persistence>dg1cloud-core/target/classes/application.properties
.. .. @@ -0,0 +1,19 @@ 1 +spring.datasource.url=jdbc:postgresql://localhost:5432/dg1cloud2 +spring.datasource.username=postgres3 +spring.datasource.password=passero4 +spring.datasource.driver-class-name=org.postgresql.Driver5 +spring.datasource.tomcat.initial-size=106 +spring.datasource.tomcat.max-wait=300007 +spring.datasource.tomcat.max-active=258 +spring.datasource.tomcat.max-idle=209 +spring.datasource.tomcat.min-idle=1010 +spring.datasource.tomcat.test-on-borrow=true11 +spring.datasource.tomcat.test-while-idle=true12 +spring.datasource.tomcat.validation-query=SELECT 113 +spring.datasource.type=com.zaxxer.hikari.HikariDataSource14 +15 +spring.jpa.open-in-view=true16 +17 +server.address=vannux.grupposistematica.it18 +19 +logging.level.it.digione.dg1cloud=DEBUGdg1cloud-core/target/classes/db/migration/V0.1__DG1CLOUD.sql
.. .. @@ -0,0 +1,27 @@ 1 +-- Table: public.reg_document2 +CREATE TABLE public.reg_document3 +(4 + document_id bigint NOT NULL,5 + created timestamp without time zone NOT NULL DEFAULT now(),6 + createdby character varying(255) NOT NULL,7 + modified timestamp without time zone NOT NULL DEFAULT now(),8 + modifiedby character varying(255) NOT NULL,9 + file_hash character varying(255),10 + file_name text NOT NULL,11 + file_path text NOT NULL,12 + file_size bigint,13 + due_date date,14 + CONSTRAINT reg_document_pkey PRIMARY KEY (document_id)15 +)16 +WITH (17 + OIDS = FALSE18 +);19 +20 +CREATE SEQUENCE public.reg_document_seq21 + INCREMENT 122 + START 123 + MINVALUE 124 + MAXVALUE 922337203685477580725 + CACHE 1;26 +27 +dg1cloud-core/target/classes/it/digione/dg1cloud/app/Dg1cloudCoreApplication.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/config/AppConfig.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/config/dg1cloud.properties
.. .. @@ -0,0 +1,16 @@ 1 +application.version=v0.0.1beta2 +3 +repository.base.upload.path=/etc/dg1cloud/repository/upload4 +repository.base.storage.path=/etc/dg1cloud/repository/storage5 +6 +repository.scanner.job.fixed.delay=600007 +repository.scanner.job.initial.delay=10008 +9 +repository.cleaner.job.fixed.delay=6000010 +repository.cleaner.job.initial.delay=100011 +12 +repository.dircleaner.job.cron=0 0 5 * * *13 +14 +server.servlet.context-path=/dg1cloud15 +16 +external.server.address.base.url=http://vannux.grupposistematica.it:8080/dg1clouddg1cloud-core/target/classes/it/digione/dg1cloud/controller/DownloadFileController.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/model/RegDocument.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/pojo/UploadedFileDescriptor.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/pojo/UploadedFileDescriptorOk.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/repository/RegDocumentRepository.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/scheduler/RepositoryJob.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/service/CleanerService.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/service/CloudService$1.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/service/CloudService$2.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/service/CloudService.classBinary files differ
dg1cloud-core/target/classes/it/digione/dg1cloud/service/Utils.classBinary files differ
dg1cloud-core/target/test-classes/it/digione/cloud/Dg1cloudCoreApplicationTests.classBinary files differ