package eu.lsem.bakalarka.service;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import java.io.*;
import eu.lsem.bakalarka.filetypeprocess.archives.ArchiveDecompressor;
import eu.lsem.bakalarka.service.util.ProcessOutputReader;
public class FileSystemUtilsImpl implements FileSystemUtils {
private ApplicationConfiguration applicationConfiguration;
private static Logger log = Logger.getLogger(FileSystemUtilsImpl.class);
public void setApplicationConfiguration(ApplicationConfiguration applicationConfiguration) {
this.applicationConfiguration = applicationConfiguration;
}
@Override
public long calculateDirectorySize(File file) throws IllegalArgumentException, IOException {
return FileUtils.sizeOfDirectory(file);
}
@Override
public void unpackArchive(File archive, File path) throws IOException {
try {
ArchiveDecompressor dec = applicationConfiguration.getArchiveDecompressor(archive);
FileUtils.forceMkdir(path);
dec.unpackFiles(archive, path);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
@Override
public InputStream getThesisArchiveInputStream(File thesisDir) throws IOException, InterruptedException {
log.debug("Pokus o stazeni:" + thesisDir.getAbsolutePath());
if (thesisDir == null || !thesisDir.exists() || !thesisDir.canRead()) {
throw new IOException("P�edan� soubor je neplatn�, nebo neexistuje, nebo k n�mu nejsou dostate�n� opr�vn�n�.");
}
File f = File.createTempFile("_file", ".zip"); //docasny soubor v adresari tomcatu
f.delete(); //musim smazat
// de.schlichtherle.io.File tempArchiveFile = new de.schlichtherle.io.File(f + "/" + thesisDir.getName()); //docasny soubor truezipu a adresar s loginem v nem
// boolean result = tempArchiveFile.copyAllFrom(thesisDir); //zkusim zabalit. v result je vysledek operace
// de.schlichtherle.io.File.umount(); //odmontuju
// log.debug("Zabaleno: " + result);
// if (!result) //pokud se nezabalilo, vrat error
// throw new IOException("Nebylo mo�n� zabalit pr�ci.");
Runtime r = Runtime.getRuntime();
String command = "zip -r " + f.getAbsolutePath() + " " + thesisDir.getName();
Process p = r.exec(command, null, thesisDir.getParentFile());
new ProcessOutputReader(p.getInputStream()).start();
new ProcessOutputReader(p.getErrorStream()).start();
int result = p.waitFor();
return new FileInputStream(f);
}
@Override
public boolean isPathSafe(String pathName) {
if (pathName != null)
for (String d : pathName.split("[/[\\\\]]"))
if (d.equals("..")) return false;
return true;
}
@Override
public boolean deleteDirectory(String path) {
File f = new File(path);
if (!f.exists() || !f.isDirectory() || !f.canWrite())
return false;
try {
FileUtils.deleteDirectory(f);
} catch (IOException e) {
return false;
}
return true;
}
}