eu.bitwalker.useragentutils.UserAgent Java Examples

The following examples show how to use eu.bitwalker.useragentutils.UserAgent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebLogAspect.java    From SpringBoot-Home with Apache License 2.0 6 votes vote down vote up
/**
 * 前置通知:
 * 1. 在执行目标方法之前执行,比如请求接口之前的登录验证;
 * 2. 在前置通知中设置请求日志信息,如开始时间,请求参数,注解内容等
 *
 * @param joinPoint
 * @throws Throwable
 */
@Before("webLogPointcut()")
public void doBefore(JoinPoint joinPoint) {

    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    //获取请求头中的User-Agent
    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
    //打印请求的内容
    startTime = System.currentTimeMillis();
    log.info("请求开始时间:{}" , LocalDateTime.now());
    log.info("请求Url : {}" , request.getRequestURL().toString());
    log.info("请求方式 : {}" , request.getMethod());
    log.info("请求ip : {}" , request.getRemoteAddr());
    log.info("请求参数 : {}" , Arrays.toString(joinPoint.getArgs()));
    // 系统信息
    log.info("浏览器:{}", userAgent.getBrowser().toString());
    log.info("浏览器版本:{}", userAgent.getBrowserVersion());
    log.info("操作系统: {}", userAgent.getOperatingSystem().toString());
}
 
Example #2
Source File: UserConfigService.java    From eds-starter6-jpa with Apache License 2.0 6 votes vote down vote up
@ExtDirectMethod(STORE_READ)
@Transactional(readOnly = true)
public List<PersistentLogin> readPersistentLogins(
		@AuthenticationPrincipal JpaUserDetails jpaUserDetails) {
	List<PersistentLogin> persistentLogins = this.jpaQueryFactory
			.selectFrom(QPersistentLogin.persistentLogin)
			.where(QPersistentLogin.persistentLogin.user.id
					.eq(jpaUserDetails.getUserDbId()))
			.fetch();

	persistentLogins.forEach(p -> {
		String ua = p.getUserAgent();
		if (StringUtils.hasText(ua)) {
			UserAgent userAgent = UserAgent.parseUserAgentString(ua);
			p.setUserAgentName(userAgent.getBrowser().getGroup().getName());
			p.setUserAgentVersion(userAgent.getBrowserVersion().getMajorVersion());
			p.setOperatingSystem(userAgent.getOperatingSystem().getName());
		}
	});

	return persistentLogins;
}
 
Example #3
Source File: OnlineSessionFactory.java    From RuoYi with Apache License 2.0 6 votes vote down vote up
@Override
public Session createSession(SessionContext initData) {
    OnlineSession session = new OnlineSession();
    if (initData instanceof WebSessionContext) {
        WebSessionContext sessionContext = (WebSessionContext) initData;
        HttpServletRequest request = (HttpServletRequest) sessionContext.getServletRequest();
        if (request != null) {
            UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            session.setHost(IpUtils.getIpAddr(request));
            session.setBrowser(browser);
            session.setOs(os);
        }
    }
    return session;
}
 
Example #4
Source File: RememberLastUsernameAuthenticationSuccessHandler.java    From lemon with Apache License 2.0 6 votes vote down vote up
public void handleDevice(HttpServletRequest request,
        HttpServletResponse response) {
    String deviceId = getCookie(request, "SECURITY_DEVICE_ID");

    if (deviceId == null) {
        deviceId = UUID.randomUUID().toString();
        this.addCookie(response, "SECURITY_DEVICE_ID", deviceId,
                3600 * 24 * 365 * 100);
    }

    DeviceDTO deviceDto = authnClient.findDevice(deviceId);

    if (deviceDto == null) {
        deviceDto = new DeviceDTO();
        deviceDto.setCode(deviceId);

        UserAgent userAgent = UserAgent.parseUserAgentString(request
                .getHeader("User-Agent"));
        deviceDto.setType(userAgent.getOperatingSystem().getDeviceType()
                .toString());
        deviceDto.setOs(userAgent.getOperatingSystem().toString());
        deviceDto.setClient(userAgent.getBrowser().toString());
    }

    authnClient.saveDevice(deviceDto);
}
 
Example #5
Source File: AsyncFactory.java    From DimpleBlog with Apache License 2.0 6 votes vote down vote up
/**
 * record login log
 *
 * @param username user name
 * @param status   status
 * @param message  message
 * @param args     args
 * @return timeTask
 */
public static TimerTask recordLoginLog(final String username, final Boolean status, final String message,
                                       final Object... args) {
    final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
    final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
    return new TimerTask() {
        @Override
        public void run() {
            String address = AddressUtils.getCityInfoByIp(ip);
            String os = userAgent.getOperatingSystem().getName();
            String browser = userAgent.getBrowser().getName();
            LoginLog loginLog = new LoginLog();
            loginLog.setUserName(username);
            loginLog.setIp(ip);
            loginLog.setBrowser(browser);
            loginLog.setOs(os);
            loginLog.setMsg(message);
            loginLog.setLocation(address);
            loginLog.setStatus(status);
            log.info("insert login log {}", loginLog);
            SpringUtils.getBean(LoginLogService.class).insertLoginLog(loginLog);
        }
    };
}
 
Example #6
Source File: OnlineSessionFactory.java    From supplierShop with MIT License 6 votes vote down vote up
@Override
public Session createSession(SessionContext initData)
{
    OnlineSession session = new OnlineSession();
    if (initData != null && initData instanceof WebSessionContext)
    {
        WebSessionContext sessionContext = (WebSessionContext) initData;
        HttpServletRequest request = (HttpServletRequest) sessionContext.getServletRequest();
        if (request != null)
        {
            UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            session.setHost(IpUtils.getIpAddr(request));
            session.setBrowser(browser);
            session.setOs(os);
        }
    }
    return session;
}
 
Example #7
Source File: LoginControll.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 创建登陆日志
 *
 * @param request
 * @param user
 * @return
 */
public static ID createLoginLog(HttpServletRequest request, ID user) {
	String ipAddr = ServletUtils.getRemoteAddr(request);
	String UA = request.getHeader("user-agent");
	if (AppUtils.isRbMobile(request)) {
		UA = UA.toUpperCase();
	} else {
		UserAgent uas = UserAgent.parseUserAgentString(UA);
		try {
			UA = String.format("%s-%s (%s)",
					uas.getBrowser(), uas.getBrowserVersion().getMajorVersion(), uas.getOperatingSystem());
		} catch (Exception ex) {
			LOG.warn("Unknow user-agent : " + UA);
			UA = "UNKNOW";
		}
	}

	Record record = EntityHelper.forNew(EntityHelper.LoginLog, UserService.SYSTEM_USER);
	record.setID("user", user);
	record.setString("ipAddr", ipAddr);
	record.setString("userAgent", UA);
	record.setDate("loginTime", CalendarUtils.now());
	record = Application.getCommonService().create(record);
	return record.getPrimary();
}
 
Example #8
Source File: FrontServiceImpl.java    From DimpleBlog with Apache License 2.0 6 votes vote down vote up
@Override
public int insertComment(Comment comment) {
    comment.setAdminReply(SecurityUtils.isAdmin());
    final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
    comment.setOs(userAgent.getOperatingSystem().getName());
    comment.setBrowser(userAgent.getBrowser().getName());
    comment.setDisplay(true);
    comment.setIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
    comment.setLocation(AddressUtils.getCityInfoByIp(comment.getIp()));
    if (comment.getParentId() != null) {
        Comment tempComment = frontMapper.selectCommentById(comment.getParentId());
        String title = frontMapper.selectBlogTitleById(comment.getPageId());
        if (tempComment.getReply()) {
            ReplayEmail replayEmail = new ReplayEmail();
            replayEmail.setCreateTime(tempComment.getCreateTime());
            replayEmail.setOriginContent(tempComment.getHtmlContent());
            replayEmail.setReplyContent(comment.getHtmlContent());
            replayEmail.setUrl(comment.getUrl());
            replayEmail.setTitle(title);
            AsyncManager.me().execute(AsyncFactory.sendReplyEmail(comment.getUrl(), comment.getHtmlContent(), comment.getNickName(), tempComment.getEmail(), replayEmail));
        }
    }
    return frontMapper.insertComment(comment);
}
 
Example #9
Source File: Predictor.java    From browserprint with MIT License 6 votes vote down vote up
public static PredictionBean getPredictionBean(Fingerprint fp) throws Exception{
	PredictionBean predictionBean = new PredictionBean();
	UserAgent ua = new UserAgent(fp.getUser_agent());
	
	BrowserOsGuessFingerprintNumericRepresentation fnr = new BrowserOsGuessFingerprintNumericRepresentation(
			fp.getAllHeaders(), fp.getFontsJS_CSS(), 
			fp.getSuperCookieLocalStorage(), fp.getSuperCookieSessionStorage(), fp.getSuperCookieUserData(),
			fp.getHstsEnabled(), fp.getIndexedDBEnabled(), fp.getMathTan(), fp.isUsingTor(), fp.getTbbVersion(),
			fp.getTouchPoints(), fp.getTouchEvent(), fp.getTouchStart());
	double fingerprintArray[];
	{
		double fingerprintArrayRaw[] = fnr.getFingerprintArray();
		fingerprintArray = new double[fingerprintArrayRaw.length + 1];
		fingerprintArray[0] = 0;
		for(int i = 0; i < fingerprintArrayRaw.length; ++i){
			fingerprintArray[i + 1] = fingerprintArrayRaw[i];
		}
	}
	
	predictionBean.setUseragentSpecifiedBrowser(ua.getBrowser().getGroup().toString());
	predictionBean.setBrowserPrediction(browserClassify(fingerprintArray));
	predictionBean.setUseragentSpecifiedOs(ua.getOperatingSystem().getGroup().toString());
	predictionBean.setOsPrediction(osClassify(fingerprintArray));
	
	return predictionBean;
}
 
Example #10
Source File: URLUtil.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
public static String parseBrowser(String useragent) {
 	useragent = (useragent + "").toLowerCase();
 	if(useragent.indexOf(browsers[0]) >= 0 && useragent.indexOf(browsers[1]) < 0) { // 微信客户端,注意区分QQ浏览器
 		return QQ_WX;
 	} 
 	
 	String origin = useragent;
 	try {
UserAgent userAgent = UserAgent.parseUserAgentString( useragent );
     	Browser browser = userAgent.getBrowser();
     	OperatingSystem opsys = userAgent.getOperatingSystem(); // 访问设备系统
     	Version browserVersion = userAgent.getBrowserVersion(); // 详细版本
         String version = browserVersion.getMajorVersion();      // 浏览器主版本
         
         origin = browser.getGroup().getName() + version + "-" + opsys;
         
     } catch(Exception e) { }
     	
 	for(String _b : browsers) {
 		if(useragent.indexOf(_b) >= 0) {
 			origin += "," + _b;
 			break;
 		}
 	}
     return origin.toLowerCase();
 }
 
Example #11
Source File: UEMServiceGFHandler.java    From uavstack with Apache License 2.0 6 votes vote down vote up
/**
 * getUA
 * 
 * @param fdata
 * @param request
 */
private void getUA(StringBuilder fdata, HttpServletRequest request) {

    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));

    String bwrVersion = userAgent.getBrowserVersion().getMajorVersion();
    Browser bwr = userAgent.getBrowser();
    String bwrType = bwr.getBrowserType().getName();
    String bwrName = bwr.getName();
    String bwrEngine = bwr.getRenderingEngine().name();

    fdata.append(bwrName).append(";");
    fdata.append(bwrType).append(";");
    fdata.append(bwrEngine).append(";");
    fdata.append(bwrVersion).append(";");

    OperatingSystem os = userAgent.getOperatingSystem();

    String osName = os.getName();
    String deType = os.getDeviceType().getName();
    fdata.append(osName).append(";");
    fdata.append(deType).append(";");
}
 
Example #12
Source File: OnlineSessionFactory.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Session createSession(SessionContext initData)
{
    OnlineSession session = new OnlineSession();
    if (initData instanceof WebSessionContext)
    {
        WebSessionContext sessionContext = (WebSessionContext) initData;
        HttpServletRequest request = (HttpServletRequest) sessionContext.getServletRequest();
        if (request != null)
        {
            UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            session.setHost(IpUtils.getIpAddr(request));
            session.setBrowser(browser);
            session.setOs(os);
        }
    }
    return session;
}
 
Example #13
Source File: WebLogAspect.java    From SpringBoot-Home with Apache License 2.0 6 votes vote down vote up
/**
 * 前置通知:
 * 1. 在执行目标方法之前执行,比如请求接口之前的登录验证;
 * 2. 在前置通知中设置请求日志信息,如开始时间,请求参数,注解内容等
 *
 * @param joinPoint
 * @throws Throwable
 */
@Before("webLogPointcut()")
public void doBefore(JoinPoint joinPoint) {

    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    //获取请求头中的User-Agent
    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
    //打印请求的内容
    startTime = System.currentTimeMillis();
    log.info("请求开始时间:{}" , LocalDateTime.now());
    log.info("请求Url : {}" , request.getRequestURL().toString());
    log.info("请求方式 : {}" , request.getMethod());
    log.info("请求ip : {}" , request.getRemoteAddr());
    log.info("请求参数 : {}" , Arrays.toString(joinPoint.getArgs()));
    // 系统信息
    log.info("浏览器:{}", userAgent.getBrowser().toString());
    log.info("浏览器版本:{}", userAgent.getBrowserVersion());
    log.info("操作系统: {}", userAgent.getOperatingSystem().toString());
}
 
Example #14
Source File: SAUCELABSCloudActionProvider.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean popuplateDevice( DeviceWebDriver webDriver, String deviceId, Device device, String xFID )
{
    String uAgent = (String) webDriver.executeScript("return navigator.userAgent;");
    UserAgent userAgent = new UserAgent( uAgent );
    device.setBrowserName( userAgent.getBrowser().getName() );
    device.setManufacturer( userAgent.getOperatingSystem().getManufacturer().getName() );
    String[] osSplit = userAgent.getOperatingSystem().getName().split( " " );
    device.setOs( osSplit[ 0 ].toUpperCase() );
    if ( osSplit.length > 1 )
        device.setOsVersion( userAgent.getOperatingSystem().getName().split( " " )[ 1 ].toUpperCase() );
    
    Dimension winDim = webDriver.manage().window().getSize();
    if ( winDim != null )
        device.setResolution( winDim.getWidth() + " x " + winDim.height );
    else
        device.setResolution( null );
    
    return true;
}
 
Example #15
Source File: SELENIUMCloudActionProvider.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean popuplateDevice( DeviceWebDriver webDriver, String deviceId, Device device, String xFID )
{
    String uAgent = (String) webDriver.executeScript("return navigator.userAgent;");
    UserAgent userAgent = new UserAgent( uAgent );
    device.setBrowserName( userAgent.getBrowser().getName() );
    device.setManufacturer( userAgent.getOperatingSystem().getManufacturer().getName() );
    String[] osSplit = userAgent.getOperatingSystem().getName().split( " " );
    device.setOs( osSplit[ 0 ].toUpperCase() );
    if ( osSplit.length > 1 )
        device.setOsVersion( userAgent.getOperatingSystem().getName().split( " " )[ 1 ].toUpperCase() );
    
    Dimension winDim = webDriver.manage().window().getSize();
    if ( winDim != null )
        device.setResolution( winDim.getWidth() + " x " + winDim.height );
    else
        device.setResolution( null );
    
    return true;
}
 
Example #16
Source File: BROWSERSTACKCloudActionProvider.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean popuplateDevice( DeviceWebDriver webDriver, String deviceId, Device device, String xFID )
{
    String uAgent = (String) webDriver.executeScript("return navigator.userAgent;");
    UserAgent userAgent = new UserAgent( uAgent );
    device.setBrowserName( userAgent.getBrowser().getName() );
    device.setManufacturer( userAgent.getOperatingSystem().getManufacturer().getName() );
    String[] osSplit = userAgent.getOperatingSystem().getName().split( " " );
    device.setOs( osSplit[ 0 ].toUpperCase() );
    if ( osSplit.length > 1 )
        device.setOsVersion( userAgent.getOperatingSystem().getName().split( " " )[ 1 ].toUpperCase() );
    
    Dimension winDim = webDriver.manage().window().getSize();
    if ( winDim != null )
        device.setResolution( winDim.getWidth() + " x " + winDim.height );
    else
        device.setResolution( null );
    
    return true;
}
 
Example #17
Source File: TerminalDetection.java    From xnx3 with Apache License 2.0 6 votes vote down vote up
/** 
 * 检测是PC端还是手机端访问,先判断PC端,若系统是 Windows或者Max OSX或者Ubuntu,则返回false,其他的都返回true
 * @param request {@link HttpServletRequest}
 * @return true:移动设备接入,false:pc端接入 
 */  
public static boolean checkMobileOrPc(HttpServletRequest request){    
	String userAgents = request.getHeader("User-Agent").toLowerCase();
	boolean isMobile = true;
	if(userAgents == null){
		return true;
	}
	
	UserAgent userAgent = UserAgent.parseUserAgentString(userAgents); 
	if(userAgent == null){
		return true;
	}
	String systemName = userAgent.getOperatingSystem().getName();
	if(systemName == null){
		return true;
	}
	for(int i=0;i<PC_SYSTEMS.length;i++){
		if(systemName.equals(PC_SYSTEMS[i])){
			return false;
		}
	}
	
    return isMobile;  
}
 
Example #18
Source File: TerminalDetection.java    From xnx3 with Apache License 2.0 6 votes vote down vote up
/** 
 * 检测是PC端还是手机端访问,先判断PC端,若系统是 Windows或者Max OSX或者Ubuntu,则返回false,其他的都返回true
 * @param userAgent 浏览器的 user-agent 字符串
 * @return true:移动设备接入,false:pc端接入 
 */  
public static boolean checkMobileOrPc(String userAgent){    
	String userAgents = userAgent.toLowerCase();
	boolean isMobile = true;
	if(userAgents == null){
		return true;
	}
	
	UserAgent ua = UserAgent.parseUserAgentString(userAgents); 
	if(ua == null){
		return true;
	}
	String systemName = ua.getOperatingSystem().getName();
	if(systemName == null){
		return true;
	}
	for(int i=0;i<PC_SYSTEMS.length;i++){
		if(systemName.equals(PC_SYSTEMS[i])){
			return false;
		}
	}
	
    return isMobile;  
}
 
Example #19
Source File: OnlineSessionFactory.java    From ruoyiplus with MIT License 6 votes vote down vote up
@Override
public Session createSession(SessionContext initData)
{
    OnlineSession session = new OnlineSession();
    if (initData != null && initData instanceof WebSessionContext)
    {
        WebSessionContext sessionContext = (WebSessionContext) initData;
        HttpServletRequest request = (HttpServletRequest) sessionContext.getServletRequest();
        if (request != null)
        {
            UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            session.setHost(IpUtils.getIpAddr(request));
            session.setBrowser(browser);
            session.setOs(os);
        }
    }
    return session;
}
 
Example #20
Source File: HttpRequestUtil.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
/**
 * 获取系统设备类型信息
 * @param request
 * @return
 */
public  static  String  getSystemDevice(HttpServletRequest request){
    String info = "";
    try{
        Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
        //获取浏览器版本号
        Version version = browser.getVersion(request.getHeader("User-Agent"));
        info = browser.getName() + "/" + version.getVersion();
    }catch (Exception e){
        log.info("获取系统设备信息失败:"+ ExceptionUtils.getStackTrace(e));
    }
    return info;
}
 
Example #21
Source File: CustomAuthenticationSuccessHandler.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 添加登录日志
 * @param auth 令牌
 * @param userId 用户id
 * @param request request
 */
private void insertLoginLog(String auth, String userId, HttpServletRequest request) {
	// 添加登录日志
	LoginLog loginLog = new LoginLog();
	loginLog.setClientIp(HttpServletUtil.getIpAddr(request));
	loginLog.setUserId(userId);
	UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
	loginLog.setBrowser(userAgent.getBrowser().getName());
	loginLog.setOsInfo(userAgent.getOperatingSystem().getName());
	loginLogServiceRpc.insertLoginLog("Bearer "+auth,loginLog);

}
 
Example #22
Source File: BizCommentServiceImpl.java    From OneBlog with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 保存当前评论时的设备信息
 *
 * @param comment
 */
private void setCurrentDeviceInfo(Comment comment) {
    String ua = RequestUtil.getUa();
    UserAgent agent = UserAgent.parseUserAgentString(ua);
    Browser browser = agent.getBrowser();
    String browserInfo = browser.getName();
    Version version = agent.getBrowserVersion();
    if (version != null) {
        browserInfo += " " + version.getVersion();
    }
    comment.setBrowser(browserInfo);
    OperatingSystem os = agent.getOperatingSystem();
    comment.setOs(os.getName());
    comment.setIp(RequestUtil.getIp());
}
 
Example #23
Source File: AsyncFactory.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
/**
 * 记录登陆信息
 *
 * @param username 用户名
 * @param status   状态
 * @param message  消息
 * @param args     列表
 * @return 任务task
 */
public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args) {
    final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
    final String ip = ShiroUtils.getIp();
    return new TimerTask() {
        @Override
        public void run() {
            // 打印信息到日志
            String address = AddressUtils.getRealAddressByIp(ip);
            String s = LogUtils.getBlock(ip) +
                    address +
                    LogUtils.getBlock(username) +
                    LogUtils.getBlock(status) +
                    LogUtils.getBlock(message);
            sys_user_logger.info(s, args);
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            // 封装对象
            SysLogininfor logininfor = new SysLogininfor();
            logininfor.setLoginName(username);
            logininfor.setIpaddr(ip);
            logininfor.setLoginLocation(address);
            logininfor.setBrowser(browser);
            logininfor.setOs(os);
            logininfor.setMsg(message);
            // 日志状态
            if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
                logininfor.setStatus(Constants.SUCCESS);
            } else if (Constants.LOGIN_FAIL.equals(status)) {
                logininfor.setStatus(Constants.FAIL);
            }
            // 插入数据
            SpringUtils.getBean(SysLogininforServiceImpl.class).insertLogininfor(logininfor);
        }
    };
}
 
Example #24
Source File: AsyncFactory.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
/**
 * record visit log
 *
 * @param visitLog visitLog
 * @return timeTask
 */
public static TimerTask recordVisitLog(final VisitLog visitLog) {
    final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
    final String spider = SpiderUtils.parseUserAgent(ServletUtils.getUserAgent());
    return new TimerTask() {
        @Override
        public void run() {
            visitLog.setOs(userAgent.getOperatingSystem().getName());
            visitLog.setSpider(spider);
            visitLog.setBrowser(userAgent.getBrowser().getName());
            visitLog.setLocation(AddressUtils.getCityInfoByIp(visitLog.getIp()));
            SpringUtils.getBean(VisitLogService.class).insertVisitLog(visitLog);
        }
    };
}
 
Example #25
Source File: CommentServiceImpl.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
@Override
public int insertComment(Comment comment) {
    comment.setAdminReply(SecurityUtils.isAdmin());
    final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
    comment.setOs(userAgent.getOperatingSystem().getName());
    comment.setBrowser(userAgent.getBrowser().getName());
    comment.setIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
    comment.setLocation(AddressUtils.getCityInfoByIp(comment.getIp()));
    return commentMapper.insertComment(comment);
}
 
Example #26
Source File: SysLogServiceImpl.java    From OneBlog with GNU General Public License v3.0 5 votes vote down vote up
@Async
@Override
public void asyncSaveSystemLog(PlatformEnum platform, String bussinessName) {
    String ua = RequestUtil.getUa();
    Log sysLog = new Log();
    sysLog.setLogLevel(LogLevelEnum.INFO);
    sysLog.setType(platform.equals(PlatformEnum.WEB) ? LogTypeEnum.VISIT : LogTypeEnum.SYSTEM);
    sysLog.setIp(RequestUtil.getIp());
    sysLog.setReferer(RequestUtil.getReferer());
    sysLog.setRequestUrl(RequestUtil.getRequestUrl());
    sysLog.setUa(ua);
    sysLog.setSpiderType(WebSpiderUtils.parseUa(ua));
    sysLog.setParams(JSONObject.toJSONString(RequestUtil.getParametersMap()));
    User user = SessionUtil.getUser();
    if (user != null) {
        sysLog.setUserId(user.getId());
        sysLog.setContent(String.format("用户: [%s] | 操作: %s", user.getUsername(), bussinessName));
    } else {
        sysLog.setContent(String.format("访客: [%s] | 操作: %s", sysLog.getIp(), bussinessName));
    }

    try {
        UserAgent agent = UserAgent.parseUserAgentString(ua);
        sysLog.setBrowser(agent.getBrowser().getName());
        sysLog.setOs(agent.getOperatingSystem().getName());
        this.insert(sysLog);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #27
Source File: LogInterceptor.java    From jboot-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void intercept(Invocation inv) {
	if (inv.getController() instanceof BaseController) {
		BaseController c = (BaseController) inv.getController();

		User user = AuthUtils.getLoginUser();
		UserAgent userAgent = UserAgent.parseUserAgentString(c.getRequest().getHeader("User-Agent"));
		Browser browser = userAgent.getBrowser();

		Log log = new Log();
		log.setUid(user.getId());
		log.setBrowser(browser.getName());
		log.setOperation(c.getRequest().getMethod());
		log.setFrom(c.getReferer());
		log.setIp(c.getIPAddress());
		log.setUrl(c.getRequest().getRequestURI());
		log.setCreateDate(new Date());
		log.setLastUpdAcct(user.getId() == null ? "guest" : user.getName());
		log.setLastUpdTime(new Date());
		log.setNote("记录日志");

		try {
			LogService logService = Jboot.service(LogService.class);
			logService.save(log);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} finally {
			inv.invoke();
		}
	} else {
		inv.invoke();
	}
}
 
Example #28
Source File: TokenService.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
/**
 * 设置用户代理信息
 *
 * @param loginUser 登录信息
 */
public void setUserAgent(LoginUser loginUser) {
    UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
    String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
    loginUser.setIp(ip);
    loginUser.setLocation(AddressUtils.getCityInfoByIp(ip));
    loginUser.setBrowser(userAgent.getBrowser().getName());
    loginUser.setOs(userAgent.getOperatingSystem().getName());
}
 
Example #29
Source File: AopLog.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 后置操作
 */
@AfterReturning("log()")
public void afterReturning() {
	ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
	HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

	Long start = (Long) request.getAttribute(START_TIME);
	Long end = System.currentTimeMillis();
	log.info("【请求耗时】:{}毫秒", end - start);

	String header = request.getHeader("User-Agent");
	UserAgent userAgent = UserAgent.parseUserAgentString(header);
	log.info("【浏览器类型】:{},【操作系统】:{},【原始User-Agent】:{}", userAgent.getBrowser().toString(), userAgent.getOperatingSystem().toString(), header);
}
 
Example #30
Source File: AopLog.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 后置操作
 */
@AfterReturning("log()")
public void afterReturning() {
	ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
	HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

	Long start = (Long) request.getAttribute(START_TIME);
	Long end = System.currentTimeMillis();
	log.info("【请求耗时】:{}毫秒", end - start);

	String header = request.getHeader("User-Agent");
	UserAgent userAgent = UserAgent.parseUserAgentString(header);
	log.info("【浏览器类型】:{},【操作系统】:{},【原始User-Agent】:{}", userAgent.getBrowser().toString(), userAgent.getOperatingSystem().toString(), header);
}