comparison src/nabble/view/web/template/NamlDownload.java @ 0:7ecd1a4ef557

add content
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 21 Mar 2019 19:15:52 -0600
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:7ecd1a4ef557
1 package nabble.view.web.template;
2
3 import fschmidt.util.java.IoUtils;
4 import nabble.model.Site;
5 import nabble.view.lib.Jtp;
6 import nabble.view.lib.UrlMappable;
7
8 import javax.servlet.ServletException;
9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.ByteArrayInputStream;
13 import java.io.ByteArrayOutputStream;
14 import java.io.IOException;
15 import java.text.DateFormat;
16 import java.text.SimpleDateFormat;
17 import java.util.Collections;
18 import java.util.Date;
19 import java.util.Map;
20 import java.util.regex.Matcher;
21 import java.util.regex.Pattern;
22 import java.util.zip.ZipEntry;
23 import java.util.zip.ZipOutputStream;
24
25
26 public class NamlDownload extends HttpServlet implements UrlMappable {
27
28 private static final Pattern URL_PATTERN = Pattern.compile("/naml/naml_.+_\\d+.zip$");
29
30 private static final DateFormat DATE = new SimpleDateFormat("yyyyMMdd");
31
32 public static String getFilePath(Site site) {
33 String filename = Jtp.subjectEncode(site.getRootNode().getSubject());
34 return "/naml/naml_" + filename + '_' + DATE.format(new Date()) + ".zip";
35 }
36
37 public Map<String, String[]> getParameterMapFromUrl(HttpServletRequest request,String mappedUrl) {
38 Matcher m = URL_PATTERN.matcher(mappedUrl);
39 if (!m.find())
40 throw new RuntimeException();
41 return Collections.emptyMap();
42 }
43
44 public Pattern getUrlPattern() {
45 return URL_PATTERN;
46 }
47
48 protected void service(HttpServletRequest request, HttpServletResponse response)
49 throws ServletException, IOException
50 {
51 Site site = Jtp.getSite(request);
52 Map<String,String> tweaks = site.getCustomTweaks();
53 try {
54 ByteArrayOutputStream baos = new ByteArrayOutputStream();
55 ZipOutputStream zout = new ZipOutputStream(baos);
56 for( Map.Entry<String,String> entry : tweaks.entrySet() ) {
57 String name = entry.getKey();
58 String content = entry.getValue();
59 zout.putNextEntry(new ZipEntry(name + ".naml"));
60 zout.write(content.getBytes());
61 zout.flush();
62 }
63 zout.close();
64 byte[] zipFileContents = baos.toByteArray();
65 baos.close();
66 response.setContentType("application/zip");
67 IoUtils.copyAll(new ByteArrayInputStream(zipFileContents), response.getOutputStream());
68 } catch(IOException e) {
69 throw new RuntimeException("Backup generation error", e);
70 }
71 }
72 }