Project

General

Profile

1
package eu.dnetlib.data.objectstore.filesystem;
2

    
3
import java.io.FileInputStream;
4
import java.io.IOException;
5
import java.io.InputStream;
6
import java.nio.file.*;
7
import java.nio.file.attribute.BasicFileAttributes;
8

    
9
import eu.dnetlib.miscutils.collections.Pair;
10
import eu.dnetlib.miscutils.functional.xml.DnetXsltFunctions;
11
import org.apache.commons.lang3.StringUtils;
12
import org.apache.commons.logging.Log;
13
import org.apache.commons.logging.LogFactory;
14

    
15
/**
16
 * The Class FileSystemUtility.
17
 *
18
 * @author sandro
19
 */
20
public class FileSystemUtility {
21

    
22
	private static final Log log = LogFactory.getLog(FileSystemUtility.class); // NOPMD by marko on 11/24/08 5:02 PM
23

    
24
	public static Pair<String, Long> saveAndGenerateMD5(final InputStream inputStream, final Path filePath) {
25
		if(inputStream==null) return null;
26

    
27
		String md5 = null;
28
		long size = 0;
29
		try {
30
			Files.copy(inputStream, filePath);
31

    
32
			FileInputStream fis = new FileInputStream(filePath.toFile());
33
			md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
34
			fis.close();
35
			size = Files.size(filePath);
36

    
37
		} catch (IOException e1) {
38
			log.error(e1);
39
		}
40

    
41
		return new Pair<String, Long>(md5, size);
42
	}
43

    
44
	/**
45
	 * Delete folder recursive.
46
	 *
47
	 * @param path the path
48
	 * @return true, if successful
49
	 * @throws IOException Signals that an I/O exception has occurred.
50
	 */
51
	public static boolean deleteFolderRecursive(final Path path) throws IOException {
52

    
53
		Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
54
			@Override
55
			public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
56
				Files.delete(file);
57
				return FileVisitResult.CONTINUE;
58
			}
59

    
60
			@Override
61
			public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
62
				Files.delete(dir);
63
				return FileVisitResult.CONTINUE;
64
			}
65
		});
66
		return true;
67
	}
68

    
69
	public static Path objectStoreFilePath(final String basePath, final String objectStoreId, final String objectIdentifier) {
70
		final Path baseDirPath = FileSystems.getDefault().getPath(basePath).resolve(objectStoreId);
71
		final String md5id = DnetXsltFunctions.md5(objectIdentifier);
72
		final String firstLevel = StringUtils.substring(md5id, 0, 2);
73
		final String secondLevel = StringUtils.substring(md5id, 2, 4);
74
		final String fileName = StringUtils.substring(md5id, 4) + ".obj";
75
		return baseDirPath.resolve(firstLevel).resolve(secondLevel).resolve(fileName);
76
	}
77

    
78
}
(4-4/8)