001/*
002 * Copyright 2012-2018 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 *      http://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.boot.devtools.autoconfigure;
018
019import org.apache.commons.logging.Log;
020import org.apache.commons.logging.LogFactory;
021
022import org.springframework.beans.factory.InitializingBean;
023import org.springframework.boot.devtools.livereload.LiveReloadServer;
024
025/**
026 * Manages an optional {@link LiveReloadServer}. The {@link LiveReloadServer} may
027 * gracefully fail to start (e.g. because of a port conflict) or may be omitted entirely.
028 *
029 * @author Phillip Webb
030 * @since 1.3.0
031 */
032public class OptionalLiveReloadServer implements InitializingBean {
033
034        private static final Log logger = LogFactory.getLog(OptionalLiveReloadServer.class);
035
036        private LiveReloadServer server;
037
038        /**
039         * Create a new {@link OptionalLiveReloadServer} instance.
040         * @param server the server to manage or {@code null}
041         */
042        public OptionalLiveReloadServer(LiveReloadServer server) {
043                this.server = server;
044        }
045
046        @Override
047        public void afterPropertiesSet() throws Exception {
048                startServer();
049        }
050
051        void startServer() throws Exception {
052                if (this.server != null) {
053                        try {
054                                if (!this.server.isStarted()) {
055                                        this.server.start();
056                                }
057                                logger.info(
058                                                "LiveReload server is running on port " + this.server.getPort());
059                        }
060                        catch (Exception ex) {
061                                logger.warn("Unable to start LiveReload server");
062                                logger.debug("Live reload start error", ex);
063                                this.server = null;
064                        }
065                }
066        }
067
068        /**
069         * Trigger LiveReload if the server is up and running.
070         */
071        public void triggerReload() {
072                if (this.server != null) {
073                        this.server.triggerReload();
074                }
075        }
076
077}