Java tutorial
/* * Copyright 2013 Matt Bertolini * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mattbertolini.statusboard.view.graph; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.beans.factory.InitializingBean; import org.springframework.web.servlet.view.AbstractView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.util.Map; /** * @author Matt Bertolini */ public abstract class AbstractGraphView extends AbstractView implements InitializingBean { private static final String DEFAULT_CONTENT_TYPE = "application/json; charset=UTF-8"; private ObjectMapper objectMapper; public AbstractGraphView() { this(new ObjectMapper()); } public AbstractGraphView(final ObjectMapper objectMapper) { super(); if (objectMapper == null) { throw new IllegalArgumentException("Object mapper is required."); } this.objectMapper = objectMapper; this.setContentType(DEFAULT_CONTENT_TYPE); } @Override protected void renderMergedOutputModel(Map<String, Object> stringObjectMap, HttpServletRequest request, HttpServletResponse response) throws Exception { if (this.objectMapper == null) { throw new IllegalStateException("Unable to render Status Board graph view. ObjectMapper is null."); } Graph graph = new Graph(); this.buildGraph(stringObjectMap, graph); PrintWriter writer = response.getWriter(); this.objectMapper.writeValue(writer, graph); writer.flush(); } @Override public void afterPropertiesSet() throws Exception { this.objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); } public void setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } protected abstract void buildGraph(Map<String, Object> stringObjectMap, Graph graph); }