All Downloads are FREE. Search and download functionalities are using the official Maven repository.

base.jee.servlet.TemplateFileUploadServlet Maven / Gradle / Ivy

Go to download

A collection of basic java utility classes that provide basic features for a standalone/simple JEE application. Backed by a Cassandra, MySQL, or SQLite database, it provides, web page templates, user and group management, and a searchable online audit log of all user activity.

The newest version!
/*
 This is free and unencumbered software released into the public domain.

 Anyone is free to copy, modify, publish, use, compile, sell, or
 distribute this software, either in source code form or as a compiled
 binary, for any purpose, commercial or non-commercial, and by any
 means.

 In jurisdictions that recognize copyright laws, the author or authors
 of this software dedicate any and all copyright interest in the
 software to the public domain. We make this dedication for the benefit
 of the public at large and to the detriment of our heirs and
 successors. We intend this dedication to be an overt act of
 relinquishment in perpetuity of all present and future rights to this
 software under copyright law.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
package base.jee.servlet;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import base.jee.JeeBase;
import base.jee.Constants;
import base.security.User;
import base.template.Template;
import base.text.StringHelper;

import static base.jee.servlet.BaseServlet.getIp;
import static base.jee.servlet.BaseServlet.getSite;

/**
 * Add or replace a template file with the contents uploaded from the end user.
 */
@MultipartConfig
public class TemplateFileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private JeeBase jee;

	public TemplateFileUploadServlet(JeeBase jee) {
		this.jee = jee;
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		throw new IOException("Missing file upload contents.");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String token = (String)request.getAttribute("token");
		if(token == null) {
			for (Cookie cookie : request.getCookies()) {
				if (cookie.getName().equalsIgnoreCase(jee.cookieName)) {
					token = cookie.getValue();
					break;
				}
			}
		}

		String ip = getIp(request);
		String site = getSite(request);
		User u = jee.getAPI().getUserSession(site, token, ip);

		if(!u.hasRole(Constants.TEMPLATE_MANAGE_ROLE)) {
			throw new IllegalStateException("You do not have permission to manage templates.");
		}


		String auth = getStringValue(request.getPart("a"), request.getCharacterEncoding());
		if(auth == null || !auth.equals(u.getFormAuthToken())) {
			throw new IllegalArgumentException("Invalid authentication token. " + auth);
		}

		String templateName = getStringValue(request.getPart("name"), request.getCharacterEncoding());
		if(templateName == null) {
			throw new IllegalArgumentException("Invalid template name.");
		}

		Template template = jee.getTemplateManager().getTemplate(site, templateName);
		if(template == null) {
			throw new IllegalArgumentException("Invalid template name.");
		}

		Part file = request.getPart("file");
		if(file == null) {
			throw new IllegalArgumentException("Please attach a file to the upload form.");
		}

		loadResourceIntoTemplate(template, file, u);

		response.setHeader("Location", jee.getSettings().get("base.url", "") + "/template?name=" + StringHelper.urlEscape(templateName));
		response.setStatus(BaseServlet.HTTP_MOVED_TEMPORARILY);
	}

	protected void loadResourceIntoTemplate(Template template, Part file, User u) throws ServletException, IOException {
		String name = getFileName(file);

		// TODO: Don't guess, actually make user specify if it is binary
		boolean binary = !(name.toLowerCase().endsWith(".txt")
					|| name.toLowerCase().endsWith(".css")
					|| name.toLowerCase().endsWith(".html")
					|| name.toLowerCase().endsWith(".js")
					|| name.toLowerCase().endsWith(".st")
					|| name.toLowerCase().endsWith(".xml"));

		InputStream in = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			int read = 0;
			final byte[] bytes = new byte[16*1024];
			in = file.getInputStream();

			while ((read = in.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}

			out.flush();

			byte[] content = out.toByteArray();
			jee.getAPI().upsertTemplateResource(u, template.getName(), name, content, binary);
			template.defineResource(name, content, binary, false);
		} finally {
			if(in != null) { in.close(); }
		}
	}

	private String getFileName(final Part part) {
		final String partHeader = part.getHeader("content-disposition");
		for (String content : partHeader.split(";")) {
			if(content.trim().startsWith("filename")) {
				return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
			}
		}
		return null;
	}

	private String getStringValue(Part part, String encoding) throws IOException {
		if(encoding == null) {
			encoding = "UTF-8";
		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), encoding));
		StringBuilder value = new StringBuilder();
		char[] buffer = new char[20*1024];
		for (int length; (length = reader.read(buffer)) > 0;) {
			value.append(buffer, 0, length);
		}
		return value.toString();
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy