com.vigglet.servlet.PostJsonServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.vigglet.servlet.PostJsonServlet.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vigglet.servlet;

import com.vigglet.model.BaseModel;
import com.vigglet.oei.user.User;
import com.vigglet.util.JsonUtil;
import java.io.IOException;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;

/**
 *
 * @author vikn
 */
public abstract class PostJsonServlet<T extends BaseModel> extends BaseJsonServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    @Override
    protected void processRequest(HttpServletRequest req, HttpServletResponse resp, User user) throws Exception {

        StringWriter writer = new StringWriter();
        IOUtils.copy(req.getInputStream(), writer, "UTF-8");
        String theString = writer.toString();

        T model = JsonUtil.read(theString, getModelClass());
        if (model != null) {
            model = setCompany(user, model);
            JsonUtil.write(resp.getOutputStream(), update(req, resp, user, model));
        } else {
            Logger.getLogger(PostJsonServlet.class.getName()).log(Level.WARNING, "Could not read json!", theString);
        }
    }

    protected abstract Class<T> getModelClass();

    protected abstract T setCompany(User user, T model);

    protected abstract T update(HttpServletRequest request, HttpServletResponse response, User user, T model)
            throws Exception;
}