001/*
002 * Copyright 2002-2017 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.web.context.support;
018
019import java.io.IOException;
020
021import javax.servlet.ServletException;
022import javax.servlet.http.HttpServlet;
023import javax.servlet.http.HttpServletRequest;
024import javax.servlet.http.HttpServletResponse;
025
026import org.springframework.context.support.LiveBeansView;
027import org.springframework.lang.Nullable;
028import org.springframework.util.Assert;
029
030/**
031 * Servlet variant of {@link LiveBeansView}'s MBean exposure.
032 *
033 * <p>Generates a JSON snapshot for current beans and their dependencies in
034 * all ApplicationContexts that live within the current web application.
035 *
036 * @author Juergen Hoeller
037 * @since 3.2
038 * @see org.springframework.context.support.LiveBeansView#getSnapshotAsJson()
039 */
040@SuppressWarnings("serial")
041public class LiveBeansViewServlet extends HttpServlet {
042
043        @Nullable
044        private LiveBeansView liveBeansView;
045
046
047        @Override
048        public void init() throws ServletException {
049                this.liveBeansView = buildLiveBeansView();
050        }
051
052        protected LiveBeansView buildLiveBeansView() {
053                return new ServletContextLiveBeansView(getServletContext());
054        }
055
056
057        @Override
058        protected void doGet(HttpServletRequest request, HttpServletResponse response)
059                        throws ServletException, IOException {
060
061                Assert.state(this.liveBeansView != null, "No LiveBeansView available");
062                String content = this.liveBeansView.getSnapshotAsJson();
063                response.setContentType("application/json");
064                response.setContentLength(content.length());
065                response.getWriter().write(content);
066        }
067
068}