| | |
| | |
|
| | | import java.io.BufferedReader;
|
| | | import java.io.IOException;
|
| | | import java.lang.reflect.Type;
|
| | | import java.text.MessageFormat;
|
| | |
|
| | | import javax.servlet.ServletException;
|
| | |
| | | import org.slf4j.Logger;
|
| | | import org.slf4j.LoggerFactory;
|
| | |
|
| | | import com.google.gson.Gson;
|
| | | import com.google.gson.GsonBuilder;
|
| | | import com.gitblit.utils.JsonUtils;
|
| | | import com.gitblit.utils.StringUtils;
|
| | |
|
| | | /**
|
| | | * Servlet class for interpreting json requests.
|
| | |
| | |
|
| | | private static final long serialVersionUID = 1L;
|
| | |
|
| | | protected final int forbiddenCode = HttpServletResponse.SC_FORBIDDEN;
|
| | | |
| | | protected final int notAllowedCode = HttpServletResponse.SC_METHOD_NOT_ALLOWED;
|
| | |
|
| | | protected final int failureCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
|
| | | |
| | | protected final Logger logger;
|
| | |
|
| | | public JsonServlet() {
|
| | |
| | |
|
| | | protected <X> X deserialize(HttpServletRequest request, HttpServletResponse response,
|
| | | Class<X> clazz) throws IOException {
|
| | | String json = readJson(request, response);
|
| | | if (StringUtils.isEmpty(json)) {
|
| | | return null;
|
| | | }
|
| | |
|
| | | X object = JsonUtils.fromJsonString(json.toString(), clazz);
|
| | | return object;
|
| | | }
|
| | |
|
| | | protected <X> X deserialize(HttpServletRequest request, HttpServletResponse response, Type type)
|
| | | throws IOException {
|
| | | String json = readJson(request, response);
|
| | | if (StringUtils.isEmpty(json)) {
|
| | | return null;
|
| | | }
|
| | |
|
| | | X object = JsonUtils.fromJsonString(json.toString(), type);
|
| | | return object;
|
| | | }
|
| | |
|
| | | private String readJson(HttpServletRequest request, HttpServletResponse response)
|
| | | throws IOException {
|
| | | BufferedReader reader = request.getReader();
|
| | | StringBuilder json = new StringBuilder();
|
| | | String line = null;
|
| | |
| | | response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
| | | return null;
|
| | | }
|
| | |
|
| | | Gson gson = new Gson();
|
| | | X object = gson.fromJson(json.toString(), clazz);
|
| | | return object;
|
| | | return json.toString();
|
| | | }
|
| | |
|
| | | protected void serialize(HttpServletResponse response, Object o) throws IOException {
|
| | | if (o != null) {
|
| | | // Send JSON response
|
| | | Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
| | | String json = gson.toJson(o);
|
| | | String json = JsonUtils.toJsonString(o);
|
| | | response.getWriter().append(json);
|
| | | }
|
| | | }
|