Mercurial > hg > LGServices
diff src/main/java/de/mpiwg/gazetteer/utils/FileManager.java @ 0:3e62083dbcbf
First commit. This project comes from LGServer. We removed the framework icefaces. Now, LGServices uses just JSP and jquery.
author | "jurzua <jurzua@mpiwg-berlin.mpg.de>" |
---|---|
date | Thu, 23 Apr 2015 15:46:01 +0200 |
parents | |
children | 37840afb7b80 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/mpiwg/gazetteer/utils/FileManager.java Thu Apr 23 15:46:01 2015 +0200 @@ -0,0 +1,87 @@ +package de.mpiwg.gazetteer.utils; + +import java.io.File; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import org.apache.commons.lang.RandomStringUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; + +import de.mpiwg.gazetteer.bo.LGBranch; +import de.mpiwg.gazetteer.bo.LGFile; + +public class FileManager { + + private static Logger logger = Logger.getLogger(FileManager.class); + + private static DateFormat dfmt = new SimpleDateFormat( "yyyy.MM.dd_hh.mm.ss.SSS" ); + + + + private static String getRootPath() throws Exception{ + String base = PropertiesUtils.getPropValue("files_root"); + + if(StringUtils.isEmpty(base)){ + throw new Exception("Property files_root no found. The files can be stored without this property."); + } + + if(!base.endsWith("/")){ + base += "/"; + } + + logger.info("files_root=" + base); + + return base; + } + + public static String saveFile(LGBranch branch, LGFile file, Date date, Long userId) throws Exception{ + + String absolutePath = getRootPath() + branch.getSectionId() + "/"; + String fileName = + branch.getSectionId() + "_" + + branch.getId() + "_" + + file.getId() + "_" + + dfmt.format(date) + "_" + + userId + + ".txt"; + + File folder = new File(absolutePath); + folder.mkdirs(); + + logger.info("Trying to save file " + absolutePath + fileName + "."); + + PrintWriter out = new PrintWriter(absolutePath + fileName); + out.println(file.getContent()); + out.close(); + + logger.info("The file " + fileName + " has been saved correctly."); + return fileName; + } + + public static String getFileAsText(LGFile file) throws Exception{ + + LGBranch branch = DataProvider.getInstance().getBranch(file.getBranchId()); + + String absolutePath = getRootPath() + branch.getSectionId() + "/" + file.getFileName(); + System.out.println("Loading: " + absolutePath); + byte[] encoded = Files.readAllBytes(Paths.get(absolutePath)); + return new String(encoded, "UTF8"); + } + + public static File getFileAsFile(LGFile file) throws Exception{ + + LGBranch branch = DataProvider.getInstance().getBranch(file.getBranchId()); + + String absolutePath = getRootPath() + branch.getSectionId() + "/" + file.getFileName(); + System.out.println("Loading: " + absolutePath); + return new File(absolutePath); + } + + +}