@Override public Response getApiInfoCache(UriInfo uriInfo) { logger.debug("ApiInfoVO requested"); CacheInfoVO cacheInfoVO = new CacheInfoVO(); cacheInfoVO.setServerTimestamp(timestampService.getDate()); cacheInfoVO.setCacheStats(getCacheStats()); return ResponseFactory.response(Response.Status.OK, cacheInfoVO, JsonPolicyDef.Policy.REST_SERVER_INFO); }
@HiveWebsocketAuth @PreAuthorize("permitAll") public void processServerInfo(JsonObject request, WebSocketSession session) { logger.debug("server/info action started. Session " + session.getId()); ApiInfoVO apiInfo = new ApiInfoVO(); apiInfo.setApiVersion(Constants.class.getPackage().getImplementationVersion()); session.getHandshakeHeaders().get("Host").stream() .findFirst() .ifPresent(host -> apiInfo.setRestServerUrl("http://" + host + contextPath + "/rest")); apiInfo.setServerTimestamp(timestampService.getDate()); WebSocketResponse response = new WebSocketResponse(); response.addValue(INFO, apiInfo, WEBSOCKET_SERVER_INFO); logger.debug("server/info action completed. Session {}", session.getId()); clientHandler.sendMessage(request, response, session); }
@Transactional(propagation = Propagation.REQUIRED) public void deviceSaveAndNotify(String deviceId, DeviceUpdate device, HivePrincipal principal) { logger.debug("Device: {}. Current principal: {}.", deviceId, principal == null ? null : principal.getName()); boolean principalHasUserAndAuthenticated = principal != null && principal.getUser() != null && principal.isAuthenticated(); if (!principalHasUserAndAuthenticated) { throw new HiveException(Messages.UNAUTHORIZED_REASON_PHRASE, UNAUTHORIZED.getStatusCode()); } DeviceNotification dn = deviceSaveByUser(deviceId, device, principal); dn.setTimestamp(timestampService.getDate()); deviceNotificationService.insert(dn, device.convertTo(deviceId)); }
.orElse(timestampService.getDate());
@Override public Response getApiInfo(UriInfo uriInfo, String protocol) { logger.debug("ApiInfoVO requested"); ApiInfoVO apiInfo = new ApiInfoVO(); String version = Constants.class.getPackage().getImplementationVersion(); if(version == null) { apiInfo.setApiVersion(appVersion); } else { apiInfo.setApiVersion(version); } apiInfo.setServerTimestamp(timestampService.getDate()); // Generate websocket url based on current request url int port = uriInfo.getBaseUri().getPort(); String wsScheme = "https".equals(protocol) ? "wss" : "ws"; if (port == -1) { apiInfo.setWebSocketServerUrl(wsScheme + "://" + uriInfo.getBaseUri().getHost() + contextPath + "/websocket"); } else { apiInfo.setWebSocketServerUrl(wsScheme + "://" + uriInfo.getBaseUri().getHost() + ":" + uriInfo.getBaseUri().getPort() + contextPath + "/websocket"); } return ResponseFactory.response(Response.Status.OK, apiInfo, JsonPolicyDef.Policy.REST_SERVER_INFO); }
@HiveWebsocketAuth @PreAuthorize("permitAll") public void processServerCacheInfo(JsonObject request, WebSocketSession session) { logger.debug("server/cacheInfo action started. Session " + session.getId()); CacheInfoVO cacheInfo = new CacheInfoVO(); cacheInfo.setServerTimestamp(timestampService.getDate()); cacheInfo.setCacheStats(getCacheStats()); WebSocketResponse response = new WebSocketResponse(); response.addValue(CACHE_INFO, cacheInfo, WEBSOCKET_SERVER_INFO); logger.debug("server/cacheI action completed. Session {}", session.getId()); clientHandler.sendMessage(request, response, session); }
private UserVO updateStatisticOnSuccessfulLogin(UserVO user, long loginTimeout) { boolean update = false; if (user.getLoginAttempts() != 0) { update = true; user.setLoginAttempts(0); } if (user.getLastLogin() == null || timestampService.getTimestamp() - user.getLastLogin().getTime() > loginTimeout) { update = true; user.setLastLogin(timestampService.getDate()); } return update ? userDao.merge(user) : user; }
@Override public Response refreshTokenRequest(JwtRefreshTokenVO requestTokenVO) { hiveValidator.validate(requestTokenVO); JwtPayload payload; try { payload = tokenService.getPayload(requestTokenVO.getRefreshToken()); } catch (JwtException e) { logger.error(e.getMessage()); return ResponseFactory.response(UNAUTHORIZED); } if (!payload.getTokenType().equals(TokenType.REFRESH.getId())) { logger.warn("JwtToken: refresh token is not valid"); return ResponseFactory.response(UNAUTHORIZED, new ErrorResponse(UNAUTHORIZED.getStatusCode(), INVALID_TOKEN_TYPE)); } if (payload.getExpiration().before(timestampService.getDate())) { logger.warn("JwtToken: refresh token has expired"); return ResponseFactory.response(UNAUTHORIZED, new ErrorResponse(UNAUTHORIZED.getStatusCode(), EXPIRED_TOKEN)); } return payload.isUserPayload() ? getRefreshResponse((JwtUserPayload) payload) : getRefreshResponse((JwtPluginPayload) payload); }
new ErrorResponse(UNAUTHORIZED.getStatusCode(), INVALID_TOKEN_TYPE)); if (jwtPluginPayload.getExpiration() != null && jwtPluginPayload.getExpiration().before(timestampService.getDate())) { logger.warn(EXPIRED_TOKEN); return ResponseFactory.response(UNAUTHORIZED,
.orElse(timestampService.getDate());
public CompletableFuture<Void> update(DeviceCommand cmd, DeviceCommandUpdate commandUpdate) { hiveValidator.validate(commandUpdate); if (cmd == null) { throw new NoSuchElementException("Command not found"); } cmd.setIsUpdated(true); cmd.setLastUpdated(timestampService.getDate()); if (commandUpdate.getStatus().isPresent()) { cmd.setStatus(commandUpdate.getStatus().get()); } if (commandUpdate.getResult().isPresent()) { cmd.setResult(commandUpdate.getResult().get()); } hiveValidator.validate(cmd); CompletableFuture<Response> commandUpdateFuture = new CompletableFuture<>(); rpcClient.call(Request.newBuilder() .withBody(new CommandUpdateRequest(cmd)) .build(), new ResponseConsumer(commandUpdateFuture)); CompletableFuture<Response> commandsUpdateFuture = new CompletableFuture<>(); rpcClient.call(Request.newBuilder() .withBody(new CommandsUpdateRequest(cmd)) .build(), new ResponseConsumer(commandsUpdateFuture)); return CompletableFuture.allOf(commandUpdateFuture, commandsUpdateFuture).thenApply(response -> null); }
command.setTimestamp(commandWrapper.getTimestamp().get()); } else { command.setTimestamp(timestampService.getDate());
public DeviceNotification convertWrapperToNotification(DeviceNotificationWrapper notificationSubmit, DeviceVO device) { DeviceNotification notification = new DeviceNotification(); notification.setId(Math.abs(new Random().nextInt())); notification.setDeviceId(device.getDeviceId()); notification.setNetworkId(device.getNetworkId()); notification.setDeviceTypeId(device.getDeviceTypeId()); if (notificationSubmit.getTimestamp() == null) { notification.setTimestamp(timestampService.getDate()); } else { notification.setTimestamp(notificationSubmit.getTimestamp()); } notification.setNotification(notificationSubmit.getNotification()); notification.setParameters(notificationSubmit.getParameters()); return notification; }
/** * Generates a JWT token containing all needed claims. These properties are taken from the specified * JwtUserPayload object. * * @param payload the payload entity with which the token will be generated * @return the JWT token */ public String generateToken(JwtUserPayload payload, TokenType tokenType, boolean useExpiration) { long maxAge = tokenType.equals(TokenType.ACCESS) ? accessTokenMaxAge : refreshTokenMaxAge; Date expiration = useExpiration && payload.getExpiration() != null ? payload.getExpiration() : timestampService.getDate(System.currentTimeMillis() + maxAge); JwtUserPayload generatedPayload = JwtUserPayload.newBuilder() .withPayload(payload) .withExpirationDate(expiration) .withTokenType(tokenType.getId()) .buildPayload(); Map<String, Object> jwtMap = new HashMap<>(); jwtMap.put(JwtUserPayload.JWT_CLAIM_KEY, generatedPayload); Claims claims = Jwts.claims(jwtMap); return Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS256, jwtSecretService.getJwtSecret()) .compact(); }
/** * Generates a JWT plugin token containing all needed claims. These properties are taken from the specified * JwtUserPayload object. * * @param payload the payload entity with which the token will be generated * @return the JWT plugin token */ public String generateToken(JwtPluginPayload payload, TokenType tokenType, boolean useExpiration) { long maxAge = tokenType.equals(TokenType.ACCESS) ? accessTokenMaxAge : refreshTokenMaxAge; Date expiration = useExpiration && payload.getExpiration() != null ? payload.getExpiration() : timestampService.getDate(System.currentTimeMillis() + maxAge); JwtPluginPayload generatedPayload = (JwtPluginPayload) JwtPluginPayload.newBuilder() .withPayload(payload) .withExpirationDate(expiration) .withTokenType(tokenType.getId()) .buildPayload(); Map<String, Object> jwtMap = new HashMap<>(); jwtMap.put(JwtUserPayload.JWT_CLAIM_KEY, generatedPayload); Claims claims = Jwts.claims(jwtMap); return Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS256, jwtSecretService.getJwtSecret()) .compact(); }
throw new BadCredentialsException("Unauthorized"); if (jwtPayload.getExpiration() != null && jwtPayload.getExpiration().before(timestampService.getDate())) { throw new ExpiredTokenException("Token expired");