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