Function bodies 105 total
getSigningKey method · java · L25-L27 (3 LOC)backend/src/main/java/com/remotecare/security/JwtUtil.java
private SecretKey getSigningKey() {
return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
}extractUsername method · java · L29-L31 (3 LOC)backend/src/main/java/com/remotecare/security/JwtUtil.java
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}extractExpiration method · java · L33-L35 (3 LOC)backend/src/main/java/com/remotecare/security/JwtUtil.java
public Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}extractClaim method · java · L37-L40 (4 LOC)backend/src/main/java/com/remotecare/security/JwtUtil.java
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}extractAllClaims method · java · L42-L48 (7 LOC)backend/src/main/java/com/remotecare/security/JwtUtil.java
private Claims extractAllClaims(String token) {
return Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload();
}isTokenExpired method · java · L50-L52 (3 LOC)backend/src/main/java/com/remotecare/security/JwtUtil.java
private Boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}generateToken method · java · L54-L59 (6 LOC)backend/src/main/java/com/remotecare/security/JwtUtil.java
public String generateToken(String username, Long userId, String role) {
Map<String, Object> claims = new HashMap<>();
claims.put("userId", userId);
claims.put("role", role);
return createToken(claims, username);
}Repobility · open methodology · https://repobility.com/research/
createToken method · java · L61-L69 (9 LOC)backend/src/main/java/com/remotecare/security/JwtUtil.java
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.claims(claims)
.subject(subject)
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + expiration))
.signWith(getSigningKey())
.compact();
}validateToken method · java · L71-L74 (4 LOC)backend/src/main/java/com/remotecare/security/JwtUtil.java
public Boolean validateToken(String token, String username) {
final String extractedUsername = extractUsername(token);
return (extractedUsername.equals(username) && !isTokenExpired(token));
}extractUserId method · java · L76-L79 (4 LOC)backend/src/main/java/com/remotecare/security/JwtUtil.java
public Long extractUserId(String token) {
Claims claims = extractAllClaims(token);
return claims.get("userId", Long.class);
}extractRole method · java · L81-L84 (4 LOC)backend/src/main/java/com/remotecare/security/JwtUtil.java
public String extractRole(String token) {
Claims claims = extractAllClaims(token);
return claims.get("role", String.class);
}passwordEncoder function · java · L64-L66 (3 LOC)backend/src/main/java/com/remotecare/security/SecurityConfig.java
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}AuthService class · java · L18-L84 (67 LOC)backend/src/main/java/com/remotecare/service/AuthService.java
public class AuthService {
private final UserRepository userRepository;
private final AuditLogRepository auditLogRepository;
private final PasswordEncoder passwordEncoder;
private final JwtUtil jwtUtil;
@Transactional
public AuthResponse signup(SignupRequest request) {
if (userRepository.existsByEmail(request.getEmail())) {
throw new RuntimeException("Email already exists");
}
User user = User.builder()
.email(request.getEmail())
.passwordHash(passwordEncoder.encode(request.getPassword()))
.role(request.getRole())
.name(request.getName())
.build();
user = userRepository.save(user);
auditLogRepository.save(AuditLog.builder()
.type(AuditLog.Type.USER_SIGNUP)
.actorUserId(user.getId())
.build());
String token = jwtUtil.generateToken(user.getEmail(), user.getId(), user.getRolsignup method · java · L26-L56 (31 LOC)backend/src/main/java/com/remotecare/service/AuthService.java
public AuthResponse signup(SignupRequest request) {
if (userRepository.existsByEmail(request.getEmail())) {
throw new RuntimeException("Email already exists");
}
User user = User.builder()
.email(request.getEmail())
.passwordHash(passwordEncoder.encode(request.getPassword()))
.role(request.getRole())
.name(request.getName())
.build();
user = userRepository.save(user);
auditLogRepository.save(AuditLog.builder()
.type(AuditLog.Type.USER_SIGNUP)
.actorUserId(user.getId())
.build());
String token = jwtUtil.generateToken(user.getEmail(), user.getId(), user.getRole().name());
return AuthResponse.builder()
.accessToken(token)
.user(AuthResponse.UserDto.builder()
.id(user.getId())
.email(user.getEmail())
login method · java · L59-L83 (25 LOC)backend/src/main/java/com/remotecare/service/AuthService.java
public AuthResponse login(AuthRequest request) {
User user = userRepository.findByEmail(request.getEmail())
.orElseThrow(() -> new RuntimeException("Invalid credentials"));
if (!passwordEncoder.matches(request.getPassword(), user.getPasswordHash())) {
throw new RuntimeException("Invalid credentials");
}
auditLogRepository.save(AuditLog.builder()
.type(AuditLog.Type.USER_LOGIN)
.actorUserId(user.getId())
.build());
String token = jwtUtil.generateToken(user.getEmail(), user.getId(), user.getRole().name());
return AuthResponse.builder()
.accessToken(token)
.user(AuthResponse.UserDto.builder()
.id(user.getId())
.email(user.getEmail())
.role(user.getRole())
.name(user.getName())
.build())
.build(Provenance: Repobility (https://repobility.com) — every score reproducible from /scan/
CallService class · java · L21-L260 (240 LOC)backend/src/main/java/com/remotecare/service/CallService.java
public class CallService {
private final CallSessionRepository callSessionRepository;
private final PairingRepository pairingRepository;
private final PatientDeviceRepository patientDeviceRepository;
private final UserRepository userRepository;
private final AuditLogRepository auditLogRepository;
private final WebSocketEventService webSocketEventService;
@Value("${call.rate-limit.max-calls-per-hour}")
private int maxCallsPerHour;
@Value("${device.heartbeat.timeout}")
private long heartbeatTimeout;
@Transactional
public CallSessionDto requestCall(Long guardianUserId, CallRequestDto request) {
System.out.println(">>> Call request received from guardian: " + guardianUserId);
System.out.println(">>> Patient ID: " + request.getPatientUserId());
User guardian = userRepository.findById(guardianUserId)
.orElseThrow(() -> new RuntimeException("Guardian not found"));
System.out.println(">requestCall method · java · L37-L122 (86 LOC)backend/src/main/java/com/remotecare/service/CallService.java
public CallSessionDto requestCall(Long guardianUserId, CallRequestDto request) {
System.out.println(">>> Call request received from guardian: " + guardianUserId);
System.out.println(">>> Patient ID: " + request.getPatientUserId());
User guardian = userRepository.findById(guardianUserId)
.orElseThrow(() -> new RuntimeException("Guardian not found"));
System.out.println(">>> Guardian found: " + guardian.getName());
if (guardian.getRole() != User.Role.GUARDIAN) {
throw new RuntimeException("User is not a guardian");
}
Long patientUserId = request.getPatientUserId();
User patient = userRepository.findById(patientUserId)
.orElseThrow(() -> new RuntimeException("Patient not found"));
System.out.println(">>> Patient found: " + patient.getName());
// Check pairing
boolean paired = pairingRepository.existsByPatientUserIdAndGuardianUserIdAndStatus(
acceptCall method · java · L125-L168 (44 LOC)backend/src/main/java/com/remotecare/service/CallService.java
public CallSessionDto acceptCall(Long patientUserId, CallAcceptRequest request) {
CallSession callSession = callSessionRepository.findById(request.getCallSessionId())
.orElseThrow(() -> new RuntimeException("Call session not found"));
if (!callSession.getPatientUserId().equals(patientUserId)) {
throw new RuntimeException("Unauthorized");
}
if (callSession.getStatus() != CallSession.Status.REQUESTED) {
throw new RuntimeException("Call is not in requested status");
}
callSession.setStatus(CallSession.Status.ACCEPTED);
callSession = callSessionRepository.save(callSession);
auditLogRepository.save(AuditLog.builder()
.type(AuditLog.Type.CALL_ACCEPTED)
.actorUserId(patientUserId)
.targetUserId(callSession.getGuardianUserId())
.payloadJson(toJson(Map.of("callSessionId", callSession.getId())))
.build());
endCall method · java · L171-L206 (36 LOC)backend/src/main/java/com/remotecare/service/CallService.java
public void endCall(Long userId, CallEndRequest request) {
CallSession callSession = callSessionRepository.findById(request.getCallSessionId())
.orElseThrow(() -> new RuntimeException("Call session not found"));
// Check authorization
if (!callSession.getPatientUserId().equals(userId)
&& !callSession.getGuardianUserId().equals(userId)) {
User user = userRepository.findById(userId).orElseThrow();
if (user.getRole() != User.Role.ADMIN) {
throw new RuntimeException("Unauthorized");
}
}
if (callSession.getStatus() == CallSession.Status.ENDED) {
return; // Already ended
}
callSession.setStatus(CallSession.Status.ENDED);
callSession.setEndedAt(LocalDateTime.now());
callSession = callSessionRepository.save(callSession);
auditLogRepository.save(AuditLog.builder()
.type(AuditLog.Type.CALL_ENDED)
getCallSession method · java · L209-L213 (5 LOC)backend/src/main/java/com/remotecare/service/CallService.java
public CallSessionDto getCallSession(Long callSessionId) {
CallSession callSession = callSessionRepository.findById(callSessionId)
.orElseThrow(() -> new RuntimeException("Call session not found"));
return buildCallSessionDto(callSession);
}getCallHistory method · java · L216-L232 (17 LOC)backend/src/main/java/com/remotecare/service/CallService.java
public List<CallSessionDto> getCallHistory(Long userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
List<CallSession> sessions;
if (user.getRole() == User.Role.PATIENT) {
sessions = callSessionRepository.findByPatientUserId(userId);
} else if (user.getRole() == User.Role.GUARDIAN) {
sessions = callSessionRepository.findByGuardianUserId(userId);
} else {
throw new RuntimeException("Invalid role");
}
return sessions.stream()
.map(this::buildCallSessionDto)
.collect(Collectors.toList());
}buildCallSessionDto method · java · L234-L251 (18 LOC)backend/src/main/java/com/remotecare/service/CallService.java
private CallSessionDto buildCallSessionDto(CallSession session) {
User patient = userRepository.findById(session.getPatientUserId()).orElse(null);
User guardian = userRepository.findById(session.getGuardianUserId()).orElse(null);
return CallSessionDto.builder()
.id(session.getId())
.patientUserId(session.getPatientUserId())
.patientName(patient != null ? patient.getName() : "Unknown")
.guardianUserId(session.getGuardianUserId())
.guardianName(guardian != null ? guardian.getName() : "Unknown")
.status(session.getStatus())
.requestedAt(session.getRequestedAt())
.connectedAt(session.getConnectedAt())
.endedAt(session.getEndedAt())
.failReason(session.getFailReason())
.providerSessionId(session.getProviderSessionId())
.build();
}toJson method · java · L253-L259 (7 LOC)backend/src/main/java/com/remotecare/service/CallService.java
private String toJson(Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
return "{}";
}
}Open data scored by Repobility · https://repobility.com
DeviceService class · java · L20-L108 (89 LOC)backend/src/main/java/com/remotecare/service/DeviceService.java
public class DeviceService {
private final PatientDeviceRepository deviceRepository;
private final UserRepository userRepository;
private final AuditLogRepository auditLogRepository;
@Transactional
public PatientDevice registerDevice(Long patientUserId, DeviceRegisterRequest request) {
User patient = userRepository.findById(patientUserId)
.orElseThrow(() -> new RuntimeException("Patient not found"));
if (patient.getRole() != User.Role.PATIENT) {
throw new RuntimeException("User is not a patient");
}
PatientDevice device = deviceRepository.findByPatientUserId(patientUserId)
.orElse(PatientDevice.builder()
.patientUserId(patientUserId)
.deviceId(request.getDeviceId())
.build());
device.setDeviceId(request.getDeviceId());
device.setLastSeenAt(LocalDateTime.now());
device.setOnline(true);
registerDevice method · java · L27-L53 (27 LOC)backend/src/main/java/com/remotecare/service/DeviceService.java
public PatientDevice registerDevice(Long patientUserId, DeviceRegisterRequest request) {
User patient = userRepository.findById(patientUserId)
.orElseThrow(() -> new RuntimeException("Patient not found"));
if (patient.getRole() != User.Role.PATIENT) {
throw new RuntimeException("User is not a patient");
}
PatientDevice device = deviceRepository.findByPatientUserId(patientUserId)
.orElse(PatientDevice.builder()
.patientUserId(patientUserId)
.deviceId(request.getDeviceId())
.build());
device.setDeviceId(request.getDeviceId());
device.setLastSeenAt(LocalDateTime.now());
device.setOnline(true);
device = deviceRepository.save(device);
auditLogRepository.save(AuditLog.builder()
.type(AuditLog.Type.DEVICE_REGISTERED)
.actorUserId(patientUserId)
.build(heartbeat method · java · L56-L76 (21 LOC)backend/src/main/java/com/remotecare/service/DeviceService.java
public void heartbeat(Long patientUserId, DeviceHeartbeatRequest request) {
PatientDevice device = deviceRepository.findByPatientUserId(patientUserId)
.orElseThrow(() -> new RuntimeException("Device not registered"));
if (!device.getDeviceId().equals(request.getDeviceId())) {
String errorMsg = String.format(
"Device ID mismatch for user %d: registered='%s', received='%s'",
patientUserId,
device.getDeviceId(),
request.getDeviceId()
);
System.err.println(errorMsg);
throw new RuntimeException(errorMsg);
}
device.setLastSeenAt(LocalDateTime.now());
device.setOnline(true);
deviceRepository.save(device);
// Don't log every heartbeat to avoid bloat
}updateSettings method · java · L79-L101 (23 LOC)backend/src/main/java/com/remotecare/service/DeviceService.java
public PatientDevice updateSettings(Long patientUserId, DeviceSettingsRequest request) {
PatientDevice device = deviceRepository.findByPatientUserId(patientUserId)
.orElseThrow(() -> new RuntimeException("Device not registered"));
if (request.getAutoAnswerEnabled() != null) {
device.setAutoAnswerEnabled(request.getAutoAnswerEnabled());
}
if (request.getAllowedTimeStart() != null) {
device.setAllowedTimeStart(request.getAllowedTimeStart());
}
if (request.getAllowedTimeEnd() != null) {
device.setAllowedTimeEnd(request.getAllowedTimeEnd());
}
device = deviceRepository.save(device);
auditLogRepository.save(AuditLog.builder()
.type(AuditLog.Type.DEVICE_SETTINGS_UPDATED)
.actorUserId(patientUserId)
.build());
return device;
}getDeviceByPatientId method · java · L104-L107 (4 LOC)backend/src/main/java/com/remotecare/service/DeviceService.java
public PatientDevice getDeviceByPatientId(Long patientUserId) {
return deviceRepository.findByPatientUserId(patientUserId)
.orElseThrow(() -> new RuntimeException("Device not found"));
}PairingService class · java · L20-L166 (147 LOC)backend/src/main/java/com/remotecare/service/PairingService.java
public class PairingService {
private final PairingRepository pairingRepository;
private final PairingCodeRepository pairingCodeRepository;
private final UserRepository userRepository;
private final PatientDeviceRepository patientDeviceRepository;
private final AuditLogRepository auditLogRepository;
@Value("${pairing.code.length}")
private int codeLength;
@Value("${pairing.code.expiration}")
private long codeExpiration;
@Value("${device.heartbeat.timeout}")
private long heartbeatTimeout;
@Transactional
public PairingCodeResponse generateCode(Long patientUserId) {
User patient = userRepository.findById(patientUserId)
.orElseThrow(() -> new RuntimeException("Patient not found"));
if (patient.getRole() != User.Role.PATIENT) {
throw new RuntimeException("User is not a patient");
}
String code = generateRandomCode();
LocalDateTime expiresAt = LocalDateTime.now().plugenerateCode method · java · L38-L67 (30 LOC)backend/src/main/java/com/remotecare/service/PairingService.java
public PairingCodeResponse generateCode(Long patientUserId) {
User patient = userRepository.findById(patientUserId)
.orElseThrow(() -> new RuntimeException("Patient not found"));
if (patient.getRole() != User.Role.PATIENT) {
throw new RuntimeException("User is not a patient");
}
String code = generateRandomCode();
LocalDateTime expiresAt = LocalDateTime.now().plusNanos(codeExpiration * 1_000_000);
PairingCode pairingCode = PairingCode.builder()
.code(code)
.patientUserId(patientUserId)
.expiresAt(expiresAt)
.used(false)
.build();
pairingCodeRepository.save(pairingCode);
auditLogRepository.save(AuditLog.builder()
.type(AuditLog.Type.PAIRING_CODE_GENERATED)
.actorUserId(patientUserId)
.build());
return PairingCodeResponse.builder()
.code(claimPairing method · java · L70-L110 (41 LOC)backend/src/main/java/com/remotecare/service/PairingService.java
public PairingDto claimPairing(Long guardianUserId, ClaimPairingRequest request) {
User guardian = userRepository.findById(guardianUserId)
.orElseThrow(() -> new RuntimeException("Guardian not found"));
if (guardian.getRole() != User.Role.GUARDIAN) {
throw new RuntimeException("User is not a guardian");
}
PairingCode pairingCode = pairingCodeRepository.findByCode(request.getCode())
.orElseThrow(() -> new RuntimeException("Invalid pairing code"));
if (!pairingCode.isValid()) {
throw new RuntimeException("Pairing code expired or already used");
}
Long patientUserId = pairingCode.getPatientUserId();
if (pairingRepository.existsByPatientUserIdAndGuardianUserIdAndStatus(
patientUserId, guardianUserId, Pairing.Status.ACTIVE)) {
throw new RuntimeException("Pairing already exists");
}
pairingCode.setUsed(true);
paiAbout: code-quality intelligence by Repobility · https://repobility.com
getMyPairings method · java · L113-L129 (17 LOC)backend/src/main/java/com/remotecare/service/PairingService.java
public List<PairingDto> getMyPairings(Long userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
List<Pairing> pairings;
if (user.getRole() == User.Role.PATIENT) {
pairings = pairingRepository.findByPatientUserId(userId);
} else if (user.getRole() == User.Role.GUARDIAN) {
pairings = pairingRepository.findByGuardianUserId(userId);
} else {
throw new RuntimeException("Invalid role for pairing");
}
return pairings.stream()
.map(this::buildPairingDto)
.collect(Collectors.toList());
}buildPairingDto method · java · L131-L156 (26 LOC)backend/src/main/java/com/remotecare/service/PairingService.java
private PairingDto buildPairingDto(Pairing pairing) {
User patient = userRepository.findById(pairing.getPatientUserId()).orElse(null);
User guardian = userRepository.findById(pairing.getGuardianUserId()).orElse(null);
PatientDevice device = patientDeviceRepository.findByPatientUserId(pairing.getPatientUserId())
.orElse(null);
PairingDto.DeviceStatusDto deviceStatus = null;
if (device != null) {
deviceStatus = PairingDto.DeviceStatusDto.builder()
.online(device.isOnline(heartbeatTimeout))
.lastSeenAt(device.getLastSeenAt())
.build();
}
return PairingDto.builder()
.id(pairing.getId())
.patientUserId(pairing.getPatientUserId())
.patientName(patient != null ? patient.getName() : "Unknown")
.guardianUserId(pairing.getGuardianUserId())
.guardianName(guardian != nulgenerateRandomCode method · java · L158-L165 (8 LOC)backend/src/main/java/com/remotecare/service/PairingService.java
private String generateRandomCode() {
Random random = new Random();
StringBuilder code = new StringBuilder();
for (int i = 0; i < codeLength; i++) {
code.append(random.nextInt(10));
}
return code.toString();
}SimpleWebSocketHandler class · java · L18-L250 (233 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
public class SimpleWebSocketHandler extends TextWebSocketHandler {
private final JwtUtil jwtUtil;
private final ObjectMapper objectMapper = new ObjectMapper();
// userId -> WebSocketSession 매핑
private final Map<Long, WebSocketSession> sessions = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("🔌 WebSocket connection established: " + session.getId());
System.out.println(" URI: " + session.getUri());
System.out.println(" Remote: " + session.getRemoteAddress());
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
// Don't log full payload for CAMERA_FRAME to reduce console spam
if (!payload.contains("CAMERA_FRAME")) {
System.out.println("📨 Received message: " + payload);
}
afterConnectionEstablished method · java · L27-L31 (5 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("🔌 WebSocket connection established: " + session.getId());
System.out.println(" URI: " + session.getUri());
System.out.println(" Remote: " + session.getRemoteAddress());
}handleTextMessage method · java · L34-L69 (36 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
// Don't log full payload for CAMERA_FRAME to reduce console spam
if (!payload.contains("CAMERA_FRAME")) {
System.out.println("📨 Received message: " + payload);
}
try {
Map<String, Object> msg = objectMapper.readValue(payload, Map.class);
String type = (String) msg.get("type");
if (!"CAMERA_FRAME".equals(type)) {
System.out.println(" Message type: " + type);
}
if ("AUTH".equals(type)) {
handleAuth(session, msg);
} else if ("SUBSCRIBE".equals(type)) {
handleSubscribe(session, msg);
} else if ("PING".equals(type)) {
handlePing(session);
} else if ("CAMERA_REQUEST".equals(type)) {
handleCameraRequesthandleAuth method · java · L71-L117 (47 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
private void handleAuth(WebSocketSession session, Map<String, Object> msg) throws IOException {
String token = (String) msg.get("token");
if (token == null || token.isEmpty()) {
System.err.println("❌ No token provided");
sendError(session, "No token provided");
return;
}
try {
String username = jwtUtil.extractUsername(token);
if (jwtUtil.validateToken(token, username)) {
Long userId = jwtUtil.extractUserId(token);
String role = jwtUtil.extractRole(token);
System.out.println("✅ Auth successful! userId=" + userId + ", role=" + role);
// 세션에 사용자 정보 저장
session.getAttributes().put("userId", userId);
session.getAttributes().put("username", username);
session.getAttributes().put("role", role);
session.getAttributes()handleSubscribe method · java · L119-L139 (21 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
private void handleSubscribe(WebSocketSession session, Map<String, Object> msg) throws IOException {
Boolean authenticated = (Boolean) session.getAttributes().get("authenticated");
if (authenticated == null || !authenticated) {
System.err.println("❌ Not authenticated");
sendError(session, "Not authenticated");
return;
}
Long userId = (Long) session.getAttributes().get("userId");
String destination = (String) msg.get("destination");
System.out.println("📬 Subscribe request: userId=" + userId + ", destination=" + destination);
// SUBSCRIBE 성공 응답
Map<String, Object> response = Map.of(
"type", "SUBSCRIBED",
"destination", destination
);
session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
}Repobility · open methodology · https://repobility.com/research/
handlePing method · java · L141-L144 (4 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
private void handlePing(WebSocketSession session) throws IOException {
Map<String, Object> response = Map.of("type", "PONG");
session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
}afterConnectionClosed method · java · L147-L157 (11 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
System.out.println("🔌 WebSocket connection closed: " + session.getId());
System.out.println(" Status: " + status);
Long userId = (Long) session.getAttributes().get("userId");
if (userId != null) {
sessions.remove(userId);
System.out.println(" Removed session for userId: " + userId);
System.out.println(" Remaining sessions: " + sessions.size());
}
}handleTransportError method · java · L160-L163 (4 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
System.err.println("❌ WebSocket transport error: " + exception.getMessage());
exception.printStackTrace();
}sendToUser method · java · L166-L181 (16 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
public void sendToUser(Long userId, Map<String, Object> event) {
WebSocketSession session = sessions.get(userId);
if (session != null && session.isOpen()) {
try {
String json = objectMapper.writeValueAsString(event);
session.sendMessage(new TextMessage(json));
System.out.println("✅ Message sent to userId " + userId + ": " + event.get("type"));
} catch (Exception e) {
System.err.println("❌ Error sending message to userId " + userId + ": " + e.getMessage());
e.printStackTrace();
}
} else {
System.err.println("⚠️ No active session for userId: " + userId);
}
}handleCameraRequest method · java · L184-L197 (14 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
private void handleCameraRequest(WebSocketSession session, Map<String, Object> msg) throws IOException {
Long senderUserId = getLongValue(msg.get("senderUserId"));
Long targetUserId = getLongValue(msg.get("targetUserId"));
Object data = msg.get("data");
System.out.println("📹 Camera request from " + senderUserId + " to " + targetUserId);
// 환자에게 카메라 요청 전달
Map<String, Object> event = Map.of(
"type", "CAMERA_REQUEST",
"data", data != null ? data : Map.of()
);
sendToUser(targetUserId, event);
}handleCameraFrame method · java · L199-L215 (17 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
private void handleCameraFrame(WebSocketSession session, Map<String, Object> msg) throws IOException {
Long senderUserId = getLongValue(msg.get("senderUserId"));
Long targetUserId = getLongValue(msg.get("targetUserId"));
Object data = msg.get("data");
// Log every 10th frame to reduce spam
if (Math.random() < 0.1) {
System.out.println("📹 Camera frame: " + senderUserId + " → " + targetUserId);
}
// Guardian에게 카메라 프레임 전달
Map<String, Object> event = Map.of(
"type", "CAMERA_FRAME",
"data", data != null ? data : Map.of()
);
sendToUser(targetUserId, event);
}handleCameraStop method · java · L217-L231 (15 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
private void handleCameraStop(WebSocketSession session, Map<String, Object> msg) throws IOException {
Long senderUserId = getLongValue(msg.get("senderUserId"));
Long targetUserId = getLongValue(msg.get("targetUserId"));
System.out.println("📹 Camera stop from " + senderUserId + " to " + targetUserId);
// 대상 사용자에게 카메라 종료 전달
Map<String, Object> event = Map.of(
"type", "CAMERA_STOP",
"data", Map.of(
"senderUserId", senderUserId
)
);
sendToUser(targetUserId, event);
}getLongValue method · java · L234-L241 (8 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
private Long getLongValue(Object value) {
if (value instanceof Integer) {
return ((Integer) value).longValue();
} else if (value instanceof Long) {
return (Long) value;
}
return null;
}Provenance: Repobility (https://repobility.com) — every score reproducible from /scan/
sendError method · java · L243-L249 (7 LOC)backend/src/main/java/com/remotecare/websocket/SimpleWebSocketHandler.java
private void sendError(WebSocketSession session, String error) throws IOException {
Map<String, Object> response = Map.of(
"type", "ERROR",
"error", error
);
session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
}WebSocketConfig class · java · L12-L25 (14 LOC)backend/src/main/java/com/remotecare/websocket/WebSocketConfig.java
public class WebSocketConfig implements WebSocketConfigurer {
private final SimpleWebSocketHandler simpleWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
System.out.println("🔧 Registering WebSocket handlers...");
registry.addHandler(simpleWebSocketHandler, "/ws")
.setAllowedOrigins("*");
System.out.println(" ✅ Registered handler at /ws");
}
}registerWebSocketHandlers method · java · L17-L24 (8 LOC)backend/src/main/java/com/remotecare/websocket/WebSocketConfig.java
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
System.out.println("🔧 Registering WebSocket handlers...");
registry.addHandler(simpleWebSocketHandler, "/ws")
.setAllowedOrigins("*");
System.out.println(" ✅ Registered handler at /ws");
}