Java Code Examples for eu.bitwalker.useragentutils.UserAgent

The following examples show how to use eu.bitwalker.useragentutils.UserAgent. These examples are extracted from open source projects. 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 Project: supplierShop   Source File: OnlineSessionFactory.java    License: 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 2
Source Project: ruoyiplus   Source File: OnlineSessionFactory.java    License: 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 3
Source Project: SpringBoot-Home   Source File: WebLogAspect.java    License: 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 4
Source Project: SpringBoot-Home   Source File: WebLogAspect.java    License: 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 5
Source Project: DimpleBlog   Source File: FrontServiceImpl.java    License: 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 6
Source Project: DimpleBlog   Source File: AsyncFactory.java    License: 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 7
Source Project: RuoYi   Source File: OnlineSessionFactory.java    License: 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 8
@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 9
Source Project: rebuild   Source File: LoginControll.java    License: 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 10
Source Project: boubei-tss   Source File: URLUtil.java    License: 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 Project: uavstack   Source File: UEMServiceGFHandler.java    License: 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
@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 13
@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 14
@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 Project: xnx3   Source File: TerminalDetection.java    License: 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 16
Source Project: xnx3   Source File: TerminalDetection.java    License: 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 17
Source Project: browserprint   Source File: Predictor.java    License: 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 18
Source Project: eds-starter6-jpa   Source File: UserConfigService.java    License: 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 19
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 20
/**
 * 添加登录日志
 * @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 21
Source Project: kk-anti-reptile   Source File: UaRule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doExecute(HttpServletRequest request, HttpServletResponse response) {
    AntiReptileProperties.UaRule uaRule = properties.getUaRule();
    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
    OperatingSystem os = userAgent.getOperatingSystem();
    OperatingSystem osGroup = userAgent.getOperatingSystem().getGroup();
    DeviceType deviceType = userAgent.getOperatingSystem().getDeviceType();
    if (DeviceType.UNKNOWN.equals(deviceType)) {
        System.out.println("Intercepted request, uri: " + request.getRequestURI() + " Unknown device, User-Agent: " + userAgent.toString());
        return true;
    } else if (OperatingSystem.UNKNOWN.equals(os)
            || OperatingSystem.UNKNOWN_MOBILE.equals(os)
            || OperatingSystem.UNKNOWN_TABLET.equals(os)) {
        System.out.println("Intercepted request, uri: " + request.getRequestURI() + " Unknown OperatingSystem, User-Agent: " + userAgent.toString());
        return true;
    }
    if (!uaRule.isAllowedLinux() && (OperatingSystem.LINUX.equals(osGroup) || OperatingSystem.LINUX.equals(os))) {
        System.out.println("Intercepted request, uri: " + request.getRequestURI() + " Not Allowed Linux request, User-Agent: " + userAgent.toString());
        return true;
    }
    if (!uaRule.isAllowedMobile() && (DeviceType.MOBILE.equals(deviceType) || DeviceType.TABLET.equals(deviceType))) {
        System.out.println("Intercepted request, uri: " + request.getRequestURI() + " Not Allowed Mobile Device request, User-Agent: " + userAgent.toString());
        return true;
    }
    if (!uaRule.isAllowedPc() && DeviceType.COMPUTER.equals(deviceType)) {
        System.out.println("Intercepted request, uri: " + request.getRequestURI() + " Not Allowed PC request, User-Agent: " + userAgent.toString());
        return true;
    }
    if (!uaRule.isAllowedIot() && (DeviceType.DMR.equals(deviceType) || DeviceType.GAME_CONSOLE.equals(deviceType) || DeviceType.WEARABLE.equals(deviceType))) {
        System.out.println("Intercepted request, uri: " + request.getRequestURI() + " Not Allowed Iot Device request, User-Agent: " + userAgent.toString());
        return true;
    }
    if (!uaRule.isAllowedProxy() && OperatingSystem.PROXY.equals(os)) {
        System.out.println("Intercepted request, uri: " + request.getRequestURI() + " Not Allowed Proxy request, User-Agent: " + userAgent.toString());
        return true;
    }
    return false;
}
 
Example 22
Source Project: app-version   Source File: UserAgentUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String getOS(String ua) {

        if (null == ua) return noDevice;
        UserAgent userAgent = UserAgent.parseUserAgentString(ua);
        OperatingSystem os = userAgent.getOperatingSystem();
        return os.toString();
    }
 
Example 23
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest req = ctx.getRequest();
    UserAgent userAgent = UserAgent.parseUserAgentString(req.getHeader("User-Agent"));

    //埋点
    PointUtil.debug("0", "request-statistics",
            "ip=" + AddrUtil.getRemoteAddr(req)
                    + "&browser=" + getBrowser(userAgent.getBrowser().getName())
                    + "&operatingSystem=" + getOperatingSystem(userAgent.getOperatingSystem().getName()));

    return null;
}
 
Example 24
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    Map<String, String> headers = request.getHeaders().toSingleValueMap();
    UserAgent userAgent = UserAgent.parseUserAgentString(headers.get("User-Agent"));
    //埋点
    PointUtil.debug("1", "request-statistics",
            "ip=" + ReactiveAddrUtil.getRemoteAddr(request)
                    + "&browser=" + getBrowser(userAgent.getBrowser().name())
                    + "&operatingSystem=" + getOperatingSystem(userAgent.getOperatingSystem().name()));

    return chain.filter(exchange);
}
 
Example 25
Source Project: RuoYi-Vue   Source File: TokenService.java    License: MIT License 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.setIpaddr(ip);
    loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
    loginUser.setBrowser(userAgent.getBrowser().getName());
    loginUser.setOs(userAgent.getOperatingSystem().getName());
}
 
Example 26
Source Project: NutzSite   Source File: SlogService.java    License: Apache License 2.0 5 votes vote down vote up
public SlogBean c(String t, String tag, String source, String msg) {
    SlogBean sysLog = new SlogBean();
    sysLog.setCt(new Date());
    if (t == null || tag == null || msg == null) {
        throw new RuntimeException("t/tag/msg can't null");
    }
    if (source == null) {
        StackTraceElement[] tmp = Thread.currentThread().getStackTrace();
        if (tmp.length > 3) {
            source = tmp[3].getClassName() + "#" + tmp[3].getMethodName();
        } else {
            source = "main";
        }
    }
    sysLog.setT(t);;
    sysLog.setTag(tag);;
    sysLog.setSource(source);;
    sysLog.setMsg(msg);;
    if (Mvcs.getReq() != null) {
        sysLog.setUrl(Mvcs.getReq().getRequestURI());
        sysLog.setIp(Lang.getIP(Mvcs.getReq()));
        //获取地址
        sysLog.setLocation(AddressUtils.getRealAddressByIP(sysLog.getIp()));
        Map<String, String[]> map = Mvcs.getReq().getParameterMap();
        String params = JSONObject.toJSONString(map);
        //设置参数值
        sysLog.setParam(StringUtils.substring(params, 0, 255));
        UserAgent userAgent = UserAgent.parseUserAgentString(Mvcs.getReq().getHeader("User-Agent"));
        if(Lang.isNotEmpty(userAgent)){
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            sysLog.setOs(os);
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            sysLog.setBrowser(browser);
        }
    }
    return sysLog;
}
 
Example 27
Source Project: spring-boot-demo   Source File: AopLog.java    License: 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 28
Source Project: charging_pile_cloud   Source File: HttpRequestUtil.java    License: 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 29
Source Project: plumemo   Source File: HttpContextUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取发起请求的浏览器名称
 */
public static String getBrowserName(HttpServletRequest request) {
	try{
		String header = request.getHeader("User-Agent");
		UserAgent userAgent = UserAgent.parseUserAgentString(header);
		Browser browser = userAgent.getBrowser();
		return browser.getName();
	}catch (Exception e){
		return "not found name";
	}
}
 
Example 30
Source Project: plumemo   Source File: HttpContextUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取发起请求的浏览器版本号
 */
public static String getBrowserVersion(HttpServletRequest request) {
	try{
		String header = request.getHeader("User-Agent");
		UserAgent userAgent = UserAgent.parseUserAgentString(header);
		Browser browser = userAgent.getBrowser();// 获取浏览器信息
		Version version = browser.getVersion(header);// 获取浏览器版本号
		return version.getVersion();
	}catch (Exception e){
		return "not found version";
	}

}