1
|
/**
|
2
|
*
|
3
|
*/
|
4
|
package eu.dnetlib.data.objectstore.filesystem;
|
5
|
|
6
|
import java.io.FileInputStream;
|
7
|
import java.io.IOException;
|
8
|
import java.io.InputStream;
|
9
|
import java.nio.file.*;
|
10
|
import java.nio.file.attribute.BasicFileAttributes;
|
11
|
|
12
|
import eu.dnetlib.miscutils.collections.Pair;
|
13
|
import eu.dnetlib.miscutils.functional.xml.DnetXsltFunctions;
|
14
|
import org.apache.commons.lang.StringUtils;
|
15
|
import org.apache.commons.logging.Log;
|
16
|
import org.apache.commons.logging.LogFactory;
|
17
|
|
18
|
/**
|
19
|
* The Class FileSystemUtility.
|
20
|
*
|
21
|
* @author sandro
|
22
|
*/
|
23
|
public class FileSystemUtility {
|
24
|
|
25
|
private static final Log log = LogFactory.getLog(FileSystemUtility.class); // NOPMD by marko on 11/24/08 5:02 PM
|
26
|
|
27
|
public static Pair<String, Integer> saveAndGenerateMD5(final InputStream inputStream, final Path filePath ){
|
28
|
if(inputStream==null) return null;
|
29
|
|
30
|
String md5 = null;
|
31
|
int size =0;
|
32
|
try {
|
33
|
Files.copy(inputStream, filePath);
|
34
|
|
35
|
FileInputStream fis = new FileInputStream(filePath.toFile());
|
36
|
md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
|
37
|
fis.close();
|
38
|
size =(int) Files.size(filePath);
|
39
|
|
40
|
} catch (IOException e1) {
|
41
|
log.error(e1);
|
42
|
}
|
43
|
|
44
|
return new Pair<String, Integer>(md5, size );
|
45
|
}
|
46
|
|
47
|
/**
|
48
|
* Delete folder recursive.
|
49
|
*
|
50
|
* @param path the path
|
51
|
* @return true, if successful
|
52
|
* @throws IOException Signals that an I/O exception has occurred.
|
53
|
*/
|
54
|
public static boolean deleteFolderRecursive(final Path path) throws IOException {
|
55
|
|
56
|
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
|
57
|
@Override
|
58
|
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
|
59
|
Files.delete(file);
|
60
|
return FileVisitResult.CONTINUE;
|
61
|
}
|
62
|
|
63
|
@Override
|
64
|
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
|
65
|
Files.delete(dir);
|
66
|
return FileVisitResult.CONTINUE;
|
67
|
}
|
68
|
});
|
69
|
return true;
|
70
|
}
|
71
|
|
72
|
public static Path objectStoreFilePath(final String basePath, final String objectStoreId, final String objectIdentifier) {
|
73
|
final Path baseDirPath = FileSystems.getDefault().getPath(basePath).resolve(objectStoreId);
|
74
|
final String md5id = DnetXsltFunctions.md5(objectIdentifier);
|
75
|
final String firstLevel = StringUtils.substring(md5id, 0, 2);
|
76
|
final String secondLevel = StringUtils.substring(md5id, 2, 4);
|
77
|
final String fileName = StringUtils.substring(md5id, 4) + ".obj";
|
78
|
return baseDirPath.resolve(firstLevel).resolve(secondLevel).resolve(fileName);
|
79
|
}
|
80
|
|
81
|
}
|