view 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
line wrap: on
line source

package nabble.view.web.template;

import fschmidt.util.java.IoUtils;
import nabble.model.Site;
import nabble.view.lib.Jtp;
import nabble.view.lib.UrlMappable;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class NamlDownload extends HttpServlet implements UrlMappable {

	private static final Pattern URL_PATTERN = Pattern.compile("/naml/naml_.+_\\d+.zip$");

	private static final DateFormat DATE = new SimpleDateFormat("yyyyMMdd");

	public static String getFilePath(Site site) {
		String filename = Jtp.subjectEncode(site.getRootNode().getSubject());
		return "/naml/naml_" + filename + '_' + DATE.format(new Date()) + ".zip";
	}

	public Map<String, String[]> getParameterMapFromUrl(HttpServletRequest request,String mappedUrl) {
		Matcher m = URL_PATTERN.matcher(mappedUrl);
		if (!m.find())
			throw new RuntimeException();
		return Collections.emptyMap();
	}

	public Pattern getUrlPattern() {
		return URL_PATTERN;
	}

	protected void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		Site site = Jtp.getSite(request);
		Map<String,String> tweaks = site.getCustomTweaks();
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ZipOutputStream zout = new ZipOutputStream(baos);
			for( Map.Entry<String,String> entry : tweaks.entrySet() ) {
				String name = entry.getKey();
				String content = entry.getValue();
				zout.putNextEntry(new ZipEntry(name + ".naml"));
				zout.write(content.getBytes());
				zout.flush();
			}
			zout.close();
			byte[] zipFileContents = baos.toByteArray();
			baos.close();
			response.setContentType("application/zip");
			IoUtils.copyAll(new ByteArrayInputStream(zipFileContents), response.getOutputStream());
		} catch(IOException e) {
			throw new RuntimeException("Backup generation error", e);
		}
	}
}