项目启动完成自动打开浏览器

5 篇文章 0 订阅
package com.jy.expert.config.listener;


import java.net.URI;
import java.net.URISyntaxException;

import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;

import com.jy.expert.util.CommandUtil;

/**
 * 系统启动完成监听
 * 
 * @author ShuoYuan
 *
 */
@SuppressWarnings("rawtypes")
public class ServerListener implements ApplicationListener {

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof ApplicationEnvironmentPreparedEvent) { // 初始化环境变量
		} else if (event instanceof ApplicationPreparedEvent) {
			// 初始化完成 }
		} else if (event instanceof ContextRefreshedEvent) {
			// 应用刷新 }
		} else if (event instanceof ApplicationReadyEvent) {
			System.out.println("应用完成::+++++++++++++++++++++++++++++++++++++++++");
			browsePage();//启动默认浏览器访问
			// 应用已启动完成
			// 初始化环信在线用户监听器;
			// try{
			// ChatOnlineConfig onlineConfig =
			// SpringContextUtils.getBean(ChatOnlineConfig.class);
			// if (onlineConfig != null) {
			// onlineConfig.start();
			// }
			// }catch(Exception e){
			// }
			// TokenConfig.getEntity().init();// 初始化
		} else if (event instanceof ContextStartedEvent) {
			System.out.println("应用启动::+++++++++++++++++++++++++++++++++++++++++");
			// 应用启动,需要在代码动态添加监听器才可捕获 }
		} else if (event instanceof ContextStoppedEvent) {
			System.out.println("应用停止::+++++++++++++++++++++++++++++++++++++++++");
			// 应用停止 }
		} else if (event instanceof ContextClosedEvent) {
			System.out.println("应用停止::+++++++++++++++++++++++++++++++++++++++++");
			// 应用关闭 }
		} else {
		}
	}
	public static void browsePage() {
		try {
			String url = "http://127.0.0.1:9599/login.html";
			// 调用默认浏览器
			CommandUtil.browse(new URI(url));
		} catch (URISyntaxException e) {
			System.out.println("打开浏览器访问失败,请手动打开浏览器,访问 http://localhost:9599/login.html");
		}
	}
}

package com.jy.expert.util;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CommandUtil {
	/** LOG日志 */
	private static final Logger LOGGER = LoggerFactory.getLogger(CommandUtil.class);

	/**
	 * 打开浏览器
	 * 
	 * @param uri uri地址
	 * @return 是否成功
	 */
	public static boolean browse(URI uri) {
		if (openSystemSpecific(uri.toString())) {
			return true;
		}

		if (browseDESKTOP(uri)) {
			return true;
		}

		return false;
	}

	/**
	 * 打开文件
	 * 
	 * @param file 文件
	 * @return 是否成功
	 */
	public static boolean open(File file) {
		if (openSystemSpecific(file.getPath())) {
			return true;
		}

		if (openDESKTOP(file)) {
			return true;
		}

		return false;
	}

	/**
	 * 编辑指令
	 * 
	 * @param file 文件
	 * @return 是否成功
	 */
	public static boolean edit(File file) {
		// you can try something like
		// runCommand("gimp", "%s", file.getPath())
		// based on user preferences.

		if (openSystemSpecific(file.getPath())) {
			return true;
		}

		if (editDESKTOP(file)) {
			return true;
		}

		return false;
	}

	/**
	 * 打开系统特殊的指令
	 * 
	 * @param what 指令
	 * @return 是否成功
	 */
	private static boolean openSystemSpecific(String what) {
		EnumOS os = getOs();

		if (os.isLinux()) {
			if (runCommand("kde-open", "%s", what))
				return true;
			if (runCommand("gnome-open", "%s", what))
				return true;
			if (runCommand("xdg-open", "%s", what))
				return true;
		}

		if (os.isMac()) {
			if (runCommand("open", "%s", what))
				return true;
		}

		if (os.isWindows()) {
			if (runCommand("explorer", "%s", what))
				return true;
		}

		return false;
	}

	/**
	 * @param uri URI
	 * @return boolean
	 */
	private static boolean browseDESKTOP(URI uri) {
		LOGGER.info("Trying to use Desktop.getDesktop().browse() with " + uri.toString());
		try {
			if (!Desktop.isDesktopSupported()) {
				LOGGER.error("Platform is not supported.");
				return false;
			}

			if (!Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
				LOGGER.error("BROWSE is not supported.");
				return false;
			}

			Desktop.getDesktop().browse(uri);

			return true;
		} catch (Throwable t) {
			LOGGER.error("Error using desktop browse.", t);
			return false;
		}
	}

	/**
	 * @param file File
	 * @return boolean
	 */
	private static boolean openDESKTOP(File file) {

		LOGGER.info("Trying to use Desktop.getDesktop().open() with " + file.toString());
		try {
			if (!Desktop.isDesktopSupported()) {
				LOGGER.error("Platform is not supported.");
				return false;
			}

			if (!Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
				LOGGER.error("OPEN is not supported.");
				return false;
			}

			Desktop.getDesktop().open(file);

			return true;
		} catch (Throwable t) {
			LOGGER.error("Error using desktop open.", t);
			return false;
		}
	}

	/**
	 * 调用jdk工具类
	 * 
	 * @param file File
	 * @return boolean
	 */
	private static boolean editDESKTOP(File file) {
		LOGGER.info("Trying to use Desktop.getDesktop().edit() with " + file);
		try {
			if (!Desktop.isDesktopSupported()) {
				LOGGER.error("Platform is not supported.");
				return false;
			}

			if (!Desktop.getDesktop().isSupported(Desktop.Action.EDIT)) {
				LOGGER.error("EDIT is not supported.");
				return false;
			}
			Desktop.getDesktop().edit(file);

			return true;
		} catch (Throwable t) {
			LOGGER.error("Error using desktop edit.", t);
			return false;
		}
	}

	/**
	 * 运行命令
	 * 
	 * @param command 指令
	 * @param args    参数
	 * @param file    文件
	 * @return 是否
	 */
	private static boolean runCommand(String command, String args, String file) {
		LOGGER.info("Trying to exec:\n   cmd = {}\n   args = {}\n   {} = ", command, args, file);
		String[] parts = prepareCommand(command, args, file);

		try {
			Process p = Runtime.getRuntime().exec(parts);
			if (p == null)
				return false;

			try {
				int retval = p.exitValue();
				if (retval == 0) {
					LOGGER.error("Process ended immediately.");
					return false;
				}
				LOGGER.error("Process crashed.");
				return false;
			} catch (IllegalThreadStateException itse) {
				LOGGER.error("Process is running.");
				return true;
			}
		} catch (IOException e) {
			LOGGER.error("Error running command.", e);
			return false;
		}
	}

	/**
	 * 准备命令
	 * 
	 * @param command 指令
	 * @param args    参数
	 * @param file    文件
	 * @return string array
	 */
	private static String[] prepareCommand(String command, String args, String file) {
		List<String> parts = new ArrayList<>();
		parts.add(command);

		if (args != null) {
			for (String s : args.split(" ")) {
				s = String.format(s, file); // put in the filename thing

				parts.add(s.trim());
			}
		}

		return parts.toArray(new String[parts.size()]);
	}

	/**
	 * 操作系统
	 * 
	 * @author 许畅
	 * @since JDK1.7
	 * @version 2018年9月14日 许畅 新建
	 */
	public static enum EnumOS {
		/** linux系统 */
		linux,

		/** macos系统 */
		macos,

		/** solaris系统 */
		solaris,

		/** unknown系统 */
		unknown,

		/** windows系统 */
		windows;

		/**
		 * @return 是否linux
		 */
		public boolean isLinux() {
			return this == linux || this == solaris;
		}

		/**
		 * @return 是否mac
		 */
		public boolean isMac() {
			return this == macos;
		}

		/**
		 * @return 是否windows
		 */
		public boolean isWindows() {
			return this == windows;
		}
	}

	/**
	 * @return EnumOS
	 */
	public static EnumOS getOs() {
		String s = System.getProperty("os.name").toLowerCase();

		if (s.contains("win")) {
			return EnumOS.windows;
		}

		if (s.contains("mac")) {
			return EnumOS.macos;
		}

		if (s.contains("solaris")) {
			return EnumOS.solaris;
		}

		if (s.contains("sunos")) {
			return EnumOS.solaris;
		}

		if (s.contains("linux")) {
			return EnumOS.linux;
		}

		if (s.contains("unix")) {
			return EnumOS.linux;
		}
		return EnumOS.unknown;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值