Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
B
baby-monitoring-spring-backend
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Analytics
Analytics
CI / CD
Repository
Value Stream
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
R24-145
baby-monitoring-spring-backend
Commits
6b62e55e
Commit
6b62e55e
authored
May 18, 2024
by
Ishankha K.C
Browse files
Options
Browse Files
Download
Plain Diff
Merge branch 'feature/chamode_dev' into 'master'
Feature/chamode dev See merge request
!1
parents
4e940852
08d23468
Changes
49
Show whitespace changes
Inline
Side-by-side
Showing
49 changed files
with
1712 additions
and
5 deletions
+1712
-5
pom.xml
pom.xml
+117
-5
secretes/baby-care-db-firebase-adminsdk-j785c-6250427b6c.json
...etes/baby-care-db-firebase-adminsdk-j785c-6250427b6c.json
+13
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/BabyCareBackendServiceApplication.java
...carebackendservice/BabyCareBackendServiceApplication.java
+2
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/AppConfig.java
.../enterprises/babycarebackendservice/config/AppConfig.java
+45
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/AuthenticationFilter.java
...s/babycarebackendservice/config/AuthenticationFilter.java
+70
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/SecurityConfig.java
...rprises/babycarebackendservice/config/SecurityConfig.java
+83
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/SwaggerConfig.java
...erprises/babycarebackendservice/config/SwaggerConfig.java
+45
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/WebSocketClient.java
...prises/babycarebackendservice/config/WebSocketClient.java
+52
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/WebSocketConfig.java
...prises/babycarebackendservice/config/WebSocketConfig.java
+125
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/constants/Common.java
.../enterprises/babycarebackendservice/constants/Common.java
+5
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/constants/Status.java
.../enterprises/babycarebackendservice/constants/Status.java
+5
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/constants/TableNames.java
...erprises/babycarebackendservice/constants/TableNames.java
+8
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/constants/UserRoles.java
...terprises/babycarebackendservice/constants/UserRoles.java
+6
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dao/BabyDao.java
...aluwa/enterprises/babycarebackendservice/dao/BabyDao.java
+9
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dao/UserDao.java
...aluwa/enterprises/babycarebackendservice/dao/UserDao.java
+14
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/AuthenticationDto.java
...rprises/babycarebackendservice/dto/AuthenticationDto.java
+19
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/BabyDto.java
...aluwa/enterprises/babycarebackendservice/dto/BabyDto.java
+27
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/EmotionDetectionResponse.java
.../babycarebackendservice/dto/EmotionDetectionResponse.java
+13
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/LoginRequest.java
.../enterprises/babycarebackendservice/dto/LoginRequest.java
+19
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/RegisterRequest.java
...terprises/babycarebackendservice/dto/RegisterRequest.java
+30
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/ResponseDto.java
...a/enterprises/babycarebackendservice/dto/ResponseDto.java
+13
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/TokenDto.java
...luwa/enterprises/babycarebackendservice/dto/TokenDto.java
+15
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/UserDto.java
...aluwa/enterprises/babycarebackendservice/dto/UserDto.java
+19
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/error/AuthorizationAlertException.java
...carebackendservice/error/AuthorizationAlertException.java
+26
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/error/BadRequestAlertException.java
...abycarebackendservice/error/BadRequestAlertException.java
+38
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/error/ErrorHandler.java
...nterprises/babycarebackendservice/error/ErrorHandler.java
+33
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/global/CustomExceptionHandler.java
...babycarebackendservice/global/CustomExceptionHandler.java
+30
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/global/ErrorResponse.java
...erprises/babycarebackendservice/global/ErrorResponse.java
+14
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/mappers/BabyMapper.java
...nterprises/babycarebackendservice/mappers/BabyMapper.java
+28
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/mappers/UserMapper.java
...nterprises/babycarebackendservice/mappers/UserMapper.java
+14
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/model/Baby.java
...kaluwa/enterprises/babycarebackendservice/model/Baby.java
+28
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/model/User.java
...kaluwa/enterprises/babycarebackendservice/model/User.java
+62
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/AuthenticationController.java
...babycarebackendservice/rest/AuthenticationController.java
+48
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/BabyController.java
...terprises/babycarebackendservice/rest/BabyController.java
+53
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/EmotionalDetectionController.java
...carebackendservice/rest/EmotionalDetectionController.java
+22
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/TestController.java
...terprises/babycarebackendservice/rest/TestController.java
+21
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/UserController.java
...terprises/babycarebackendservice/rest/UserController.java
+50
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/service/BabyService.java
...terprises/babycarebackendservice/service/BabyService.java
+18
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/service/UserService.java
...terprises/babycarebackendservice/service/UserService.java
+19
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/service/impl/BabyCareUserDetailsService.java
...ckendservice/service/impl/BabyCareUserDetailsService.java
+22
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/service/impl/BabyServiceImpl.java
.../babycarebackendservice/service/impl/BabyServiceImpl.java
+106
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/service/impl/UserServiceImpl.java
.../babycarebackendservice/service/impl/UserServiceImpl.java
+184
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/socketHandlers/BoundingBox.java
...es/babycarebackendservice/socketHandlers/BoundingBox.java
+15
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/socketHandlers/EmotionPrediction.java
...ycarebackendservice/socketHandlers/EmotionPrediction.java
+13
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/socketHandlers/SendVideoHandler.java
...bycarebackendservice/socketHandlers/SendVideoHandler.java
+12
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/socketHandlers/VideoFrameHandler.java
...ycarebackendservice/socketHandlers/VideoFrameHandler.java
+15
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/utils/JWTUtils.java
...wa/enterprises/babycarebackendservice/utils/JWTUtils.java
+69
-0
src/main/resources/application.yaml
src/main/resources/application.yaml
+16
-0
src/test/java/com/kaluwa/enterprises/babycarebackendservice/BabyCareBackendServiceApplicationTests.java
...ackendservice/BabyCareBackendServiceApplicationTests.java
+2
-0
No files found.
pom.xml
View file @
6b62e55e
...
...
@@ -15,6 +15,7 @@
<description>
baby-care-backend-service
</description>
<properties>
<java.version>
17
</java.version>
<org.mapstruct.version>
1.4.2.Final
</org.mapstruct.version>
</properties>
<dependencies>
<dependency>
...
...
@@ -29,6 +30,14 @@
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-security
</artifactId>
</dependency>
<dependency>
<groupId>
org.springframework.security
</groupId>
<artifactId>
spring-security-config
</artifactId>
</dependency>
<dependency>
<groupId>
org.springframework.security
</groupId>
<artifactId>
spring-security-web
</artifactId>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-validation
</artifactId>
...
...
@@ -44,11 +53,6 @@
<scope>
runtime
</scope>
<optional>
true
</optional>
</dependency>
<dependency>
<groupId>
com.h2database
</groupId>
<artifactId>
h2
</artifactId>
<scope>
runtime
</scope>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-configuration-processor
</artifactId>
...
...
@@ -69,6 +73,84 @@
<artifactId>
spring-security-test
</artifactId>
<scope>
test
</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>
io.springfox
</groupId>
<artifactId>
springfox-swagger2
</artifactId>
<version>
2.9.2
</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>
io.springfox
</groupId>
<artifactId>
springfox-swagger-ui
</artifactId>
<version>
2.9.2
</version>
</dependency>
<dependency>
<groupId>
org.springdoc
</groupId>
<artifactId>
springdoc-openapi-starter-webmvc-ui
</artifactId>
<version>
2.5.0
</version>
</dependency>
<dependency>
<groupId>
com.fasterxml.jackson.datatype
</groupId>
<artifactId>
jackson-datatype-jsr310
</artifactId>
<version>
2.15.4
</version>
</dependency>
<dependency>
<groupId>
com.mysql
</groupId>
<artifactId>
mysql-connector-j
</artifactId>
<scope>
runtime
</scope>
</dependency>
<!--jwt deps-->
<dependency>
<groupId>
io.jsonwebtoken
</groupId>
<artifactId>
jjwt-api
</artifactId>
<version>
0.11.5
</version>
</dependency>
<dependency>
<groupId>
io.jsonwebtoken
</groupId>
<artifactId>
jjwt-impl
</artifactId>
<version>
0.11.5
</version>
</dependency>
<dependency>
<groupId>
io.jsonwebtoken
</groupId>
<artifactId>
jjwt-jackson
</artifactId>
<version>
0.11.5
</version>
</dependency>
<!--mappers-->
<dependency>
<groupId>
org.mapstruct
</groupId>
<artifactId>
mapstruct
</artifactId>
<version>
${org.mapstruct.version}
</version>
</dependency>
<!--handle live feeds-->
<dependency>
<groupId>
javax.websocket
</groupId>
<artifactId>
javax.websocket-api
</artifactId>
<version>
1.1
</version>
</dependency>
<dependency>
<groupId>
org.glassfish.tyrus.bundles
</groupId>
<artifactId>
tyrus-standalone-client
</artifactId>
<version>
1.17
</version>
</dependency>
<dependency>
<groupId>
org.bytedeco
</groupId>
<artifactId>
opencv
</artifactId>
<version>
4.9.0-1.5.10
</version>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-websocket
</artifactId>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-tomcat
</artifactId>
</dependency>
</dependencies>
<build>
...
...
@@ -85,7 +167,37 @@
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>
org.apache.maven.plugins
</groupId>
<artifactId>
maven-compiler-plugin
</artifactId>
<version>
3.11.0
</version>
<configuration>
<source>
1.8
</source>
<target>
1.8
</target>
<annotationProcessorPaths>
<path>
<groupId>
org.mapstruct
</groupId>
<artifactId>
mapstruct-processor
</artifactId>
<version>
${org.mapstruct.version}
</version>
</path>
<path>
<groupId>
org.projectlombok
</groupId>
<artifactId>
lombok
</artifactId>
<version>
1.18.22
</version>
</path>
<path>
<groupId>
org.projectlombok
</groupId>
<artifactId>
lombok-mapstruct-binding
</artifactId>
<version>
0.2.0
</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<arg>
-Amapstruct.verbose=true
</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
<finalName>
baby-care-service
</finalName>
</build>
</project>
secretes/baby-care-db-firebase-adminsdk-j785c-6250427b6c.json
0 → 100644
View file @
6b62e55e
{
"type"
:
"service_account"
,
"project_id"
:
"baby-care-db"
,
"private_key_id"
:
"6250427b6ce3875947e6c1bba3cf35de4d73ae01"
,
"private_key"
:
"-----BEGIN PRIVATE KEY-----
\n
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCPllNzLD8Kl5nt
\n
Hdy7JnEJeVYYUQzEt7zzMl3IOOSdHX9F982rTX4Co1J6pqlzb6g1GHltaHcyDwO6
\n
iCXDF+hg7SXQ//UC3O4sz+/LFHDuCGV9t2/R6MOH6SYiNAlg7UY+5UdUN1M2Si0C
\n
BEXGJ3pvKwRv25Yx4cd4ea0IviNxqnX9H6r2FfSE7OHO4f1yastu0swPsBYizP2c
\n
iB7SeThhQz02X5ICvXN3qrET+3/QT1R95svZmTczKmOsc5mMnUmjPkzr2yxrq28Q
\n
d3G76sBqs2lMeOe3nCqqppRmbJBjXErx/fQDeNcHcDpWIT4bprUPFA2JOJftzxe2
\n
3TC339ITAgMBAAECggEAEgqO2LFOCHws7ISsh91YJZsXzL1eT9dQR/RjoTU40F70
\n
72sn7eayNw2jXuLS9ryoU2eMVklidKk7TDQwHnfCDG+vqTeH5wCwcnP8CrW6TMZE
\n
Tkv+ok7PRqPuVSzZotKdWWjAkh3TeEZQqmi0BaZPNWmfyJg8Im9ee046hhcx5+WV
\n
aghN26wX42mAb0TumdCWG2ZcBRwdJ9o32VIDOU98fD28NlRQkE/raGzKr/U6PqJI
\n
vLN8JFCbKemyGNKrPqnewj+SiB3MoQ7FoADtNUXEXPYHd9oRS/DY+4lmMG0CkPOG
\n
joiuM9vSAahwrjyLjqocEEcKFoSUlik5rP15QX6hDQKBgQDJRpr0RGI4gi9L+Xyj
\n
3kj22l8ACSfJ+pCRr8H36nWt6O6b4F5QrRkHdlIBs3yR90m6xrVTVmW31qcqsDhu
\n
ae3C45ULb21FT7SReuflamMpjpn3LnlrmgSE5bAu7RqyZ4Xx67ke9/jrklZ5ouMC
\n
/vagSD6WcFMy5Qt4TX0nRIudNQKBgQC2oGxP+k+wZh56X7K716aoyrf+GEen4q3P
\n
t+1yXTY00EYRDR3YODudcO7i/fJ+vbGqOWLIRt2ljaMakHwkTRpFmT2iLn7CwWPz
\n
PpalMuR6aBBqrNV+shlCPhJ+Wa5LSviDlUUC6kPgSB3sc7jJ/UB/JnWjcYpRKToD
\n
er/EV15DJwKBgGI+cWIrgtncSaPG6ly+IlVDr70/usku4aQK6x3MtpYlrVougTrV
\n
0vK+gTbNWk+RKc7eMSG1eT7rqnr+uvzB/cjz9ws231pGlnewS0LC1BYzwdlSOPgZ
\n
nH0V9BJjr3VHbKzyB1Ejbr/llQoYRMBwnQcNXGdn+mRMQnX9NMqW/aLFAoGAP0ly
\n
n3iX2wJYd4HoV24RBBdUEYrqcgR8xSnw8BvbKAww68HG4OIDzriPIDxup3snMV03
\n
nT3pm3Bs4EzHqHDLtOi40hYYuXb5IxdCbzcmtECRx9XjGkevtyP5lq2PV+pAGqFE
\n
zBDQus1jCUjE9cJ8clOqmpxDGYMW5pPIFstMECsCgYBmqjb/qRjzcm7m1FW+JhO9
\n
oJsqRNQ/5tYAw+FvmbwaQ3ySXuXGwHlzMu7neaNMGJc3GSSucj6wauTJKCBp4UhP
\n
mpK/YJ5lCjnbl2ZxNGJNjtEnCLWbkvLxg9++aZ0lsxbGiEVGW6V9WZ/RfcpAJQNa
\n
eN73MvA+QbV2+8h28CKGfA==
\n
-----END PRIVATE KEY-----
\n
"
,
"client_email"
:
"firebase-adminsdk-j785c@baby-care-db.iam.gserviceaccount.com"
,
"client_id"
:
"116620214787799634875"
,
"auth_uri"
:
"https://accounts.google.com/o/oauth2/auth"
,
"token_uri"
:
"https://oauth2.googleapis.com/token"
,
"auth_provider_x509_cert_url"
:
"https://www.googleapis.com/oauth2/v1/certs"
,
"client_x509_cert_url"
:
"https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-j785c%40baby-care-db.iam.gserviceaccount.com"
,
"universe_domain"
:
"googleapis.com"
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/BabyCareBackendServiceApplication.java
View file @
6b62e55e
...
...
@@ -2,6 +2,7 @@ package com.kaluwa.enterprises.babycarebackendservice;
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.autoconfigure.SpringBootApplication
;
import
org.springframework.context.annotation.ComponentScan
;
@SpringBootApplication
public
class
BabyCareBackendServiceApplication
{
...
...
@@ -11,3 +12,4 @@ public class BabyCareBackendServiceApplication {
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/AppConfig.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.config
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
;
import
org.springframework.beans.factory.annotation.Qualifier
;
import
org.springframework.boot.web.client.RestTemplateBuilder
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.web.client.RestTemplate
;
import
org.springframework.web.socket.client.WebSocketClient
;
import
org.springframework.web.socket.client.standard.StandardWebSocketClient
;
import
org.springframework.web.socket.config.annotation.EnableWebSocket
;
import
org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean
;
@Configuration
@EnableWebSocket
public
class
AppConfig
{
@Bean
public
ObjectMapper
objectMapper
()
{
ObjectMapper
objectMapper
=
new
ObjectMapper
();
objectMapper
.
registerModule
(
new
JavaTimeModule
());
return
objectMapper
;
}
@Bean
@Qualifier
(
"primaryWebsocketClient"
)
public
WebSocketClient
webSocketClient
()
{
return
new
StandardWebSocketClient
();
}
@Bean
public
RestTemplate
restTemplate
(
RestTemplateBuilder
builder
)
{
return
builder
.
build
();
}
@Bean
public
ServletServerContainerFactoryBean
createWebSocketContainer
()
{
ServletServerContainerFactoryBean
container
=
new
ServletServerContainerFactoryBean
();
container
.
setMaxTextMessageBufferSize
(
500000
);
container
.
setMaxBinaryMessageBufferSize
(
500000
);
return
container
;
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/AuthenticationFilter.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.config
;
import
com.kaluwa.enterprises.babycarebackendservice.error.AuthorizationAlertException
;
import
com.kaluwa.enterprises.babycarebackendservice.service.impl.BabyCareUserDetailsService
;
import
com.kaluwa.enterprises.babycarebackendservice.utils.JWTUtils
;
import
jakarta.servlet.FilterChain
;
import
jakarta.servlet.ServletException
;
import
jakarta.servlet.http.HttpServletRequest
;
import
jakarta.servlet.http.HttpServletResponse
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Qualifier
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
import
org.springframework.security.core.context.SecurityContext
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.web.authentication.WebAuthenticationDetailsSource
;
import
org.springframework.stereotype.Component
;
import
org.springframework.web.filter.OncePerRequestFilter
;
import
org.springframework.web.servlet.HandlerExceptionResolver
;
import
java.io.IOException
;
@Component
public
class
AuthenticationFilter
extends
OncePerRequestFilter
{
private
final
JWTUtils
jwtUtils
;
private
final
BabyCareUserDetailsService
userDetailsService
;
@Autowired
@Qualifier
(
"handlerExceptionResolver"
)
private
HandlerExceptionResolver
resolver
;
public
AuthenticationFilter
(
JWTUtils
jwtUtils
,
BabyCareUserDetailsService
userDetailsService
)
{
this
.
jwtUtils
=
jwtUtils
;
this
.
userDetailsService
=
userDetailsService
;
}
@Override
protected
void
doFilterInternal
(
HttpServletRequest
request
,
HttpServletResponse
response
,
FilterChain
filterChain
)
throws
ServletException
,
IOException
{
try
{
final
String
authHeader
=
request
.
getHeader
(
"Authorization"
);
final
String
jwtToken
;
final
String
userEmail
;
if
(
authHeader
==
null
||
authHeader
.
isBlank
()
||
!
authHeader
.
startsWith
(
"Bearer "
))
{
filterChain
.
doFilter
(
request
,
response
);
return
;
}
jwtToken
=
authHeader
.
substring
(
7
);
userEmail
=
jwtUtils
.
extractUsername
(
jwtToken
);
if
(
userEmail
!=
null
&&
SecurityContextHolder
.
getContext
().
getAuthentication
()
==
null
)
{
UserDetails
userDetails
=
userDetailsService
.
loadUserByUsername
(
userEmail
);
if
(
jwtUtils
.
isTokenValid
(
jwtToken
,
userDetails
))
{
SecurityContext
securityContext
=
SecurityContextHolder
.
createEmptyContext
();
UsernamePasswordAuthenticationToken
token
=
new
UsernamePasswordAuthenticationToken
(
userDetails
,
null
,
userDetails
.
getAuthorities
()
);
token
.
setDetails
(
new
WebAuthenticationDetailsSource
().
buildDetails
(
request
));
securityContext
.
setAuthentication
(
token
);
SecurityContextHolder
.
setContext
(
securityContext
);
}
}
filterChain
.
doFilter
(
request
,
response
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
resolver
.
resolveException
(
request
,
response
,
null
,
new
AuthorizationAlertException
(
e
.
getMessage
(),
"error"
,
"unauthorized"
));
}
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/SecurityConfig.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.config
;
import
com.kaluwa.enterprises.babycarebackendservice.service.impl.BabyCareUserDetailsService
;
import
jakarta.servlet.DispatcherType
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.security.authentication.AuthenticationManager
;
import
org.springframework.security.authentication.AuthenticationProvider
;
import
org.springframework.security.authentication.dao.DaoAuthenticationProvider
;
import
org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration
;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity
;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
;
import
org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer
;
import
org.springframework.security.config.http.SessionCreationPolicy
;
import
org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
;
import
org.springframework.security.crypto.password.PasswordEncoder
;
import
org.springframework.security.web.SecurityFilterChain
;
import
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
;
import
static
org
.
springframework
.
security
.
config
.
Customizer
.
withDefaults
;
@Configuration
@EnableWebSecurity
public
class
SecurityConfig
{
private
final
BabyCareUserDetailsService
userDetailsService
;
private
final
AuthenticationFilter
authFilter
;
public
SecurityConfig
(
BabyCareUserDetailsService
userDetailsService
,
AuthenticationFilter
authFilter
)
{
this
.
userDetailsService
=
userDetailsService
;
this
.
authFilter
=
authFilter
;
}
String
[]
whiteListedEndpoints
=
new
String
[]{
"/auth/login"
,
"/auth/register"
,
"/auth/forgot-password"
,
// swagger
"/v2/api-docs"
,
"/v3/api-docs"
,
"/v3/api-docs/**"
,
"/swagger-resources"
,
"/swagger-resources/**"
,
"/configuration/ui"
,
"/configuration/security"
,
"/swagger-ui/**"
,
"/webjars/**"
,
"/swagger-ui.html"
,
"/emotional/video-process"
,
};
@Bean
public
SecurityFilterChain
filterChain
(
HttpSecurity
http
)
throws
Exception
{
http
.
csrf
(
AbstractHttpConfigurer:
:
disable
)
.
authorizeHttpRequests
(
request
->
request
.
requestMatchers
(
whiteListedEndpoints
).
permitAll
()
.
anyRequest
()
.
authenticated
())
.
sessionManagement
(
sessionManagement
->
sessionManagement
.
sessionCreationPolicy
(
SessionCreationPolicy
.
STATELESS
))
.
authenticationProvider
(
authenticationProvider
()).
addFilterBefore
(
authFilter
,
UsernamePasswordAuthenticationFilter
.
class
);
return
http
.
build
();
}
@Bean
public
AuthenticationProvider
authenticationProvider
()
{
DaoAuthenticationProvider
daoAuthenticationProvider
=
new
DaoAuthenticationProvider
();
daoAuthenticationProvider
.
setUserDetailsService
(
userDetailsService
);
daoAuthenticationProvider
.
setPasswordEncoder
(
passwordEncoder
());
return
daoAuthenticationProvider
;
}
@Bean
public
PasswordEncoder
passwordEncoder
()
{
return
new
BCryptPasswordEncoder
();
}
@Bean
public
AuthenticationManager
authenticationManager
(
AuthenticationConfiguration
authenticationConfiguration
)
throws
Exception
{
return
authenticationConfiguration
.
getAuthenticationManager
();
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/SwaggerConfig.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.config
;
import
io.swagger.v3.oas.annotations.OpenAPIDefinition
;
import
io.swagger.v3.oas.annotations.enums.SecuritySchemeIn
;
import
io.swagger.v3.oas.annotations.enums.SecuritySchemeType
;
import
io.swagger.v3.oas.annotations.info.Contact
;
import
io.swagger.v3.oas.annotations.info.Info
;
import
io.swagger.v3.oas.annotations.info.License
;
import
io.swagger.v3.oas.annotations.security.SecurityScheme
;
import
io.swagger.v3.oas.annotations.servers.Server
;
@OpenAPIDefinition
(
info
=
@Info
(
title
=
"BabyCare Backend API"
,
version
=
"v1.0"
,
description
=
"API for managing BabyCare backend services"
,
termsOfService
=
"Terms of service"
,
contact
=
@Contact
(
name
=
"Kaluwa Enterprises"
,
email
=
"kaluwa.enterprises@gmail.com"
,
url
=
"https://www.kaluwa-enterprises.com"
),
license
=
@License
(
name
=
"Apache 2.0"
,
url
=
"http://www.apache.org/licenses/LICENSE-2.0.html"
)
),
servers
=
{
@Server
(
description
=
"Local ENV"
,
url
=
"http://localhost:8080/api/v1/baby-care"
)
}
)
@SecurityScheme
(
name
=
"BearerAuth"
,
description
=
"Bearer Token Authentication"
,
scheme
=
"bearer"
,
type
=
SecuritySchemeType
.
HTTP
,
bearerFormat
=
"JWT"
,
in
=
SecuritySchemeIn
.
HEADER
)
public
class
SwaggerConfig
{
}
\ No newline at end of file
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/WebSocketClient.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.config
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.kaluwa.enterprises.babycarebackendservice.socketHandlers.EmotionPrediction
;
import
org.springframework.web.socket.BinaryMessage
;
import
org.springframework.web.socket.TextMessage
;
import
org.springframework.web.socket.WebSocketSession
;
import
org.springframework.web.socket.client.standard.StandardWebSocketClient
;
import
org.springframework.web.socket.handler.TextWebSocketHandler
;
import
static
com
.
kaluwa
.
enterprises
.
babycarebackendservice
.
config
.
WebSocketConfig
.
SendVideoHandler
.
sendTextMessageToClient
;
public
class
WebSocketClient
{
private
WebSocketSession
session
;
public
WebSocketClient
()
{
try
{
this
.
session
=
new
StandardWebSocketClient
()
.
doHandshake
(
new
MyWebSocketHandler
(),
"ws://localhost:8000/ws/emotion"
)
.
get
();
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
public
void
sendBytesToWebSocket
(
byte
[]
bytes
)
{
try
{
session
.
sendMessage
(
new
BinaryMessage
(
bytes
));
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
static
ObjectMapper
objectMapper
=
new
ObjectMapper
();
public
static
EmotionPrediction
[]
predictions
;
static
class
MyWebSocketHandler
extends
TextWebSocketHandler
{
@Override
protected
void
handleTextMessage
(
WebSocketSession
session
,
TextMessage
message
)
throws
Exception
{
// This method will be called when the server sends a text message
// Deserialize JSON array of objects into an array of Java objects
predictions
=
objectMapper
.
readValue
(
message
.
getPayload
(),
EmotionPrediction
[].
class
);
if
(
predictions
!=
null
&&
predictions
.
length
>
0
)
{
EmotionPrediction
lastPrediction
=
predictions
[
predictions
.
length
-
1
];
// Now you can work with the last prediction
System
.
out
.
println
(
"Last emotion prediction: "
+
lastPrediction
);
sendTextMessageToClient
(
lastPrediction
);
}
}
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/WebSocketConfig.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.config
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.kaluwa.enterprises.babycarebackendservice.socketHandlers.EmotionPrediction
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Qualifier
;
import
org.springframework.boot.configurationprocessor.json.JSONStringer
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.stereotype.Component
;
import
org.springframework.web.socket.BinaryMessage
;
import
org.springframework.web.socket.CloseStatus
;
import
org.springframework.web.socket.TextMessage
;
import
org.springframework.web.socket.WebSocketSession
;
import
org.springframework.web.socket.adapter.standard.StandardWebSocketSession
;
import
org.springframework.web.socket.config.annotation.WebSocketConfigurer
;
import
org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry
;
import
org.springframework.web.socket.handler.BinaryWebSocketHandler
;
import
springfox.documentation.spring.web.json.Json
;
import
java.io.IOException
;
@Configuration
@Slf4j
public
class
WebSocketConfig
implements
WebSocketConfigurer
{
@Override
public
void
registerWebSocketHandlers
(
WebSocketHandlerRegistry
registry
)
{
registry
.
addHandler
(
new
VideoFrameHandler
(),
"/emotional/video-process"
).
setAllowedOrigins
(
"*"
);
registry
.
addHandler
(
new
SendVideoHandler
(),
"/emotional/video-send"
).
setAllowedOrigins
(
"*"
);
}
@Bean
@Qualifier
(
"customWebsocketClient"
)
public
WebSocketClient
customWebSocketClient
()
{
return
new
WebSocketClient
();
}
@Component
class
VideoFrameHandler
extends
BinaryWebSocketHandler
{
WebSocketClient
webSocketClient
=
customWebSocketClient
();
@Override
protected
void
handleBinaryMessage
(
WebSocketSession
session
,
BinaryMessage
message
)
throws
Exception
{
byte
[]
binaryData
=
message
.
getPayload
().
array
();
// Process the binary data representing the video frame
// log.info("Received binary data from client: {}", binaryData);
// Here you can process the binary data as needed, such as saving it to a file, performing image processing, etc.
webSocketClient
.
sendBytesToWebSocket
(
binaryData
);
SendVideoHandler
.
sendBinaryMessageToClient
(
binaryData
);
}
@Override
protected
void
handleTextMessage
(
WebSocketSession
session
,
TextMessage
message
)
{
super
.
handleTextMessage
(
session
,
message
);
}
}
@Component
class
SendVideoHandler
extends
BinaryWebSocketHandler
{
WebSocketClient
webSocketClient
=
customWebSocketClient
();
private
static
StandardWebSocketSession
session
;
@Override
public
void
afterConnectionEstablished
(
WebSocketSession
session
)
throws
Exception
{
SendVideoHandler
.
session
=
(
StandardWebSocketSession
)
session
;
log
.
info
(
"Connection established with client: {}"
,
session
);
super
.
afterConnectionEstablished
(
session
);
}
@Override
protected
void
handleBinaryMessage
(
WebSocketSession
session
,
BinaryMessage
message
)
throws
Exception
{
byte
[]
binaryData
=
message
.
getPayload
().
array
();
}
@Override
public
void
afterConnectionClosed
(
WebSocketSession
session
,
CloseStatus
status
)
throws
Exception
{
// Handle session closure here
// For example, cleanup resources or attempt to reconnect
SendVideoHandler
.
session
=
null
;
// Reset session variable
log
.
info
(
"Connection closed with client: {}"
,
session
);
super
.
afterConnectionClosed
(
session
,
status
);
}
@Override
protected
void
handleTextMessage
(
WebSocketSession
session
,
TextMessage
message
)
{
super
.
handleTextMessage
(
session
,
message
);
try
{
System
.
out
.
println
(
"Received text message from client: "
+
message
.
getPayload
());
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
// Method to send a message back to the client
public
static
void
sendBinaryMessageToClient
(
byte
[]
bytes
)
{
try
{
if
(
session
!=
null
&&
session
.
isOpen
())
{
session
.
sendMessage
(
new
BinaryMessage
(
bytes
));
System
.
out
.
println
(
"Sent message to client: "
+
bytes
.
length
);
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
}
public
static
void
sendTextMessageToClient
(
EmotionPrediction
emotionPrediction
)
{
try
{
if
(
session
!=
null
&&
session
.
isOpen
())
{
ObjectMapper
objectMapper
=
new
ObjectMapper
();
String
json
=
objectMapper
.
writeValueAsString
(
emotionPrediction
);
session
.
sendMessage
(
new
TextMessage
(
json
));
System
.
out
.
println
(
"Sent message to client: "
+
json
);
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
}
}
}
\ No newline at end of file
src/main/java/com/kaluwa/enterprises/babycarebackendservice/constants/Common.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.constants
;
public
class
Common
{
public
static
final
String
TOKEN_TYPE
=
"bearer"
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/constants/Status.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.constants
;
public
class
Status
{
public
final
static
String
STATUS_NEW
=
"NEW"
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/constants/TableNames.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.constants
;
public
class
TableNames
{
public
final
static
String
USER_TABLE
=
"users"
;
public
final
static
String
BABY_TABLE
=
"babies"
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/constants/UserRoles.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.constants
;
public
class
UserRoles
{
public
static
final
String
ADMIN
=
"ADMIN"
;
public
static
final
String
USER
=
"USER"
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dao/BabyDao.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.dao
;
import
com.kaluwa.enterprises.babycarebackendservice.model.Baby
;
import
org.springframework.data.jpa.repository.JpaRepository
;
import
org.springframework.stereotype.Repository
;
@Repository
public
interface
BabyDao
extends
JpaRepository
<
Baby
,
Long
>
{
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dao/UserDao.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.dao
;
import
com.kaluwa.enterprises.babycarebackendservice.model.User
;
import
org.springframework.data.jpa.repository.JpaRepository
;
import
org.springframework.stereotype.Repository
;
import
java.util.Optional
;
@Repository
public
interface
UserDao
extends
JpaRepository
<
User
,
Long
>
{
Optional
<
User
>
findByEmail
(
String
username
);
boolean
existsByEmail
(
String
email
);
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/AuthenticationDto.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.dto
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
AuthenticationDto
{
private
Long
userId
;
private
String
firstName
;
private
String
lastName
;
private
String
email
;
private
String
phone
;
private
String
role
;
private
String
status
;
private
TokenDto
tokenDto
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/BabyDto.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.dto
;
import
jakarta.validation.constraints.NotEmpty
;
import
jakarta.validation.constraints.NotNull
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
import
java.time.LocalDate
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
BabyDto
{
private
Long
babyId
;
@NotNull
(
message
=
"Baby name is required"
)
@NotEmpty
(
message
=
"Baby name is required"
)
private
String
babyName
;
private
String
babyGender
;
private
LocalDate
babyDob
;
private
String
babyWeight
;
private
UserDto
user
;
@NotNull
(
message
=
"Logged user id is required"
)
@NotEmpty
(
message
=
"Logged user id is required"
)
private
Long
userId
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/EmotionDetectionResponse.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.dto
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
EmotionDetectionResponse
{
private
String
emotion
;
private
String
feeds
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/LoginRequest.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.dto
;
import
jakarta.validation.constraints.NotEmpty
;
import
jakarta.validation.constraints.NotNull
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
LoginRequest
{
@NotEmpty
(
message
=
"Email is required"
)
@NotNull
(
message
=
"Email is required"
)
private
String
email
;
@NotEmpty
(
message
=
"Password is required"
)
@NotNull
(
message
=
"Password is required"
)
private
String
password
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/RegisterRequest.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.dto
;
import
jakarta.validation.constraints.NotEmpty
;
import
jakarta.validation.constraints.NotNull
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
RegisterRequest
{
@NotEmpty
(
message
=
"First name is required"
)
@NotNull
(
message
=
"First name is required"
)
private
String
firstName
;
@NotEmpty
(
message
=
"Last name is required"
)
@NotNull
(
message
=
"Last name is required"
)
private
String
lastName
;
@NotEmpty
(
message
=
"Email is required"
)
@NotNull
(
message
=
"Email is required"
)
private
String
email
;
@NotEmpty
(
message
=
"Password is required"
)
@NotNull
(
message
=
"Password is required"
)
private
String
password
;
@NotEmpty
(
message
=
"Phone is required"
)
@NotNull
(
message
=
"Phone is required"
)
private
String
phone
;
private
String
role
;
private
String
status
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/ResponseDto.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.dto
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
ResponseDto
{
private
Long
id
;
private
String
message
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/TokenDto.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.dto
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
TokenDto
{
private
String
tokenType
;
private
long
expiresIn
;
private
String
token
;
private
String
refreshToken
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/dto/UserDto.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.dto
;
import
com.fasterxml.jackson.annotation.JsonIgnore
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
UserDto
{
private
Long
userId
;
private
String
firstName
;
private
String
lastName
;
private
String
email
;
private
String
phone
;
private
String
role
;
private
String
status
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/error/AuthorizationAlertException.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.error
;
import
lombok.Getter
;
import
lombok.Setter
;
@Getter
@Setter
public
class
AuthorizationAlertException
extends
RuntimeException
{
private
final
String
message
;
private
final
String
entityName
;
private
final
String
errorKey
;
/**
* Instantiates a new Bad request alert exception.
*
* @param message the message
* @param entityName the entity name
* @param errorKey the error key
*/
public
AuthorizationAlertException
(
String
message
,
String
entityName
,
String
errorKey
)
{
this
.
message
=
message
;
this
.
entityName
=
entityName
;
this
.
errorKey
=
errorKey
;
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/error/BadRequestAlertException.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.error
;
import
lombok.Getter
;
import
lombok.Setter
;
/**
* The type Bad request alert exception.
*/
@Getter
@Setter
/**
* @author : Steffan Devotta
* @version : 1.0
* @date : Sep 30, 2021
* @copyright : © 2010-2021 Informatics International Limited. All Rights Reserved
*/
public
class
BadRequestAlertException
extends
RuntimeException
{
private
static
final
long
serialVersionUID
=
1L
;
private
final
String
message
;
private
final
String
entityName
;
private
final
String
errorKey
;
/**
* Instantiates a new Bad request alert exception.
*
* @param message the message
* @param entityName the entity name
* @param errorKey the error key
*/
public
BadRequestAlertException
(
String
message
,
String
entityName
,
String
errorKey
)
{
this
.
message
=
message
;
this
.
entityName
=
entityName
;
this
.
errorKey
=
errorKey
;
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/error/ErrorHandler.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.error
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.web.bind.annotation.ControllerAdvice
;
import
org.springframework.web.bind.annotation.ExceptionHandler
;
import
org.springframework.web.context.request.WebRequest
;
import
org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
;
import
java.time.LocalDateTime
;
import
java.util.LinkedHashMap
;
import
java.util.Map
;
@ControllerAdvice
public
class
ErrorHandler
extends
ResponseEntityExceptionHandler
{
@ExceptionHandler
(
BadRequestAlertException
.
class
)
public
ResponseEntity
<
Object
>
handleBadRequestAlertException
(
BadRequestAlertException
ex
,
WebRequest
request
)
{
Map
<
String
,
Object
>
body
=
new
LinkedHashMap
<>();
body
.
put
(
"timestamp"
,
LocalDateTime
.
now
().
toString
());
body
.
put
(
"message"
,
ex
.
getMessage
());
body
.
put
(
"error"
,
ex
.
getErrorKey
());
return
new
ResponseEntity
<>(
body
,
HttpStatus
.
BAD_REQUEST
);
}
@ExceptionHandler
(
AuthorizationAlertException
.
class
)
public
ResponseEntity
<
Object
>
handleAuthorizationAlertException
(
AuthorizationAlertException
ae
,
WebRequest
request
)
{
Map
<
String
,
Object
>
body
=
new
LinkedHashMap
<>();
body
.
put
(
"timestamp"
,
LocalDateTime
.
now
().
toString
());
body
.
put
(
"error"
,
ae
.
getMessage
());
return
new
ResponseEntity
<>(
body
,
HttpStatus
.
UNAUTHORIZED
);
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/global/CustomExceptionHandler.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.global
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.validation.BindingResult
;
import
org.springframework.validation.FieldError
;
import
org.springframework.web.bind.MethodArgumentNotValidException
;
import
org.springframework.web.bind.annotation.ExceptionHandler
;
import
org.springframework.web.bind.annotation.RestControllerAdvice
;
@RestControllerAdvice
@Slf4j
public
class
CustomExceptionHandler
{
@ExceptionHandler
(
MethodArgumentNotValidException
.
class
)
public
ResponseEntity
<
ErrorResponse
>
handleValidationExceptions
(
MethodArgumentNotValidException
ex
)
{
BindingResult
result
=
ex
.
getBindingResult
();
FieldError
error
=
result
.
getFieldError
();
String
message
=
error
.
getField
()+
" : "
+
error
.
getDefaultMessage
();
log
.
debug
(
"Validation error: {}"
,
message
);
ErrorResponse
errorResponse
=
new
ErrorResponse
();
errorResponse
.
setHttpCode
(
400
);
errorResponse
.
setErrorCode
(
"VALIDATION FAILED!"
);
errorResponse
.
setDescription
(
message
);
return
new
ResponseEntity
<>(
errorResponse
,
HttpStatus
.
BAD_REQUEST
);
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/global/ErrorResponse.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.global
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
ErrorResponse
{
private
int
httpCode
;
private
String
errorCode
;
private
String
description
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/mappers/BabyMapper.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.mappers
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.BabyDto
;
import
com.kaluwa.enterprises.babycarebackendservice.model.Baby
;
import
org.mapstruct.Mapper
;
import
org.mapstruct.Mapping
;
import
org.mapstruct.Mappings
;
import
java.util.List
;
@Mapper
(
componentModel
=
"spring"
)
public
interface
BabyMapper
{
@Mappings
({
@Mapping
(
source
=
"user.userId"
,
target
=
"userId"
)
})
BabyDto
toDto
(
Baby
baby
);
@Mappings
({
@Mapping
(
target
=
"user.userId"
,
source
=
"userId"
)
})
Baby
toEntity
(
BabyDto
babyDto
);
@Mappings
({
@Mapping
(
source
=
"user.userId"
,
target
=
"userId"
)
})
List
<
BabyDto
>
toDtoList
(
List
<
Baby
>
babyList
);
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/mappers/UserMapper.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.mappers
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.UserDto
;
import
com.kaluwa.enterprises.babycarebackendservice.model.User
;
import
org.mapstruct.Mapper
;
import
java.util.List
;
@Mapper
(
componentModel
=
"spring"
)
public
interface
UserMapper
{
UserDto
toDto
(
User
user
);
User
toEntity
(
UserDto
userDto
);
List
<
UserDto
>
listToDto
(
List
<
User
>
users
);
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/model/Baby.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.model
;
import
jakarta.persistence.*
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
import
java.time.LocalDate
;
import
static
com
.
kaluwa
.
enterprises
.
babycarebackendservice
.
constants
.
TableNames
.
BABY_TABLE
;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table
(
name
=
BABY_TABLE
)
public
class
Baby
{
@Id
@GeneratedValue
(
strategy
=
GenerationType
.
AUTO
)
private
Long
babyId
;
private
String
babyName
;
private
String
babyGender
;
private
LocalDate
babyDob
;
private
String
babyWeight
;
@ManyToOne
(
fetch
=
FetchType
.
LAZY
)
@JoinColumn
(
name
=
"userId"
,
referencedColumnName
=
"userId"
,
nullable
=
false
)
private
User
user
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/model/User.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.model
;
import
jakarta.persistence.*
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
import
org.springframework.security.core.GrantedAuthority
;
import
org.springframework.security.core.authority.SimpleGrantedAuthority
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
java.util.Collection
;
import
java.util.List
;
import
static
com
.
kaluwa
.
enterprises
.
babycarebackendservice
.
constants
.
TableNames
.
USER_TABLE
;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table
(
name
=
USER_TABLE
)
public
class
User
implements
UserDetails
{
@Id
@GeneratedValue
(
strategy
=
GenerationType
.
AUTO
)
private
Long
userId
;
private
String
firstName
;
private
String
lastName
;
private
String
email
;
private
String
password
;
private
String
phone
;
private
String
role
;
private
String
status
;
@Override
public
Collection
<?
extends
GrantedAuthority
>
getAuthorities
()
{
return
List
.
of
(
new
SimpleGrantedAuthority
(
role
));
}
@Override
public
String
getUsername
()
{
return
email
;
}
@Override
public
boolean
isAccountNonExpired
()
{
return
true
;
}
@Override
public
boolean
isAccountNonLocked
()
{
return
true
;
}
@Override
public
boolean
isCredentialsNonExpired
()
{
return
true
;
}
@Override
public
boolean
isEnabled
()
{
return
true
;
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/AuthenticationController.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.rest
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.AuthenticationDto
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.LoginRequest
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.RegisterRequest
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.UserDto
;
import
com.kaluwa.enterprises.babycarebackendservice.model.User
;
import
com.kaluwa.enterprises.babycarebackendservice.service.UserService
;
import
jakarta.validation.Valid
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.web.bind.annotation.PostMapping
;
import
org.springframework.web.bind.annotation.RequestBody
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RestController
;
@Slf4j
@RestController
@RequestMapping
(
"/auth"
)
public
class
AuthenticationController
{
private
final
UserService
userService
;
public
AuthenticationController
(
UserService
userService
)
{
this
.
userService
=
userService
;
}
// login
@PostMapping
(
"/login"
)
public
ResponseEntity
<
AuthenticationDto
>
login
(
@RequestBody
@Valid
LoginRequest
loginRequest
)
{
log
.
info
(
"Inside authentication controller login method"
);
return
new
ResponseEntity
<>(
userService
.
login
(
loginRequest
),
HttpStatus
.
OK
);
}
// register
@PostMapping
(
"/register"
)
public
ResponseEntity
<
UserDto
>
register
(
@RequestBody
@Valid
RegisterRequest
registerRequest
)
{
log
.
info
(
"Inside authentication controller register method"
);
return
new
ResponseEntity
<>(
userService
.
register
(
registerRequest
),
HttpStatus
.
CREATED
);
}
// forgot password
// change password
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/BabyController.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.rest
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.BabyDto
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto
;
import
com.kaluwa.enterprises.babycarebackendservice.service.BabyService
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.web.bind.annotation.*
;
import
java.util.List
;
@RestController
@RequestMapping
(
"/baby"
)
@Slf4j
public
class
BabyController
{
private
final
BabyService
babyService
;
public
BabyController
(
BabyService
babyService
)
{
this
.
babyService
=
babyService
;
}
@PostMapping
()
public
ResponseEntity
<
BabyDto
>
createBaby
(
@RequestBody
BabyDto
babyDto
)
{
log
.
info
(
"Inside baby controller createBaby method"
);
return
new
ResponseEntity
<>(
babyService
.
createBaby
(
babyDto
),
HttpStatus
.
CREATED
);
}
@GetMapping
()
public
ResponseEntity
<
List
<
BabyDto
>>
getAllbabies
()
{
log
.
info
(
"Inside baby controller getAllbabies method"
);
return
ResponseEntity
.
ok
(
babyService
.
getAllBabies
());
}
@GetMapping
(
"/{id}"
)
public
ResponseEntity
<
BabyDto
>
getBabyById
(
@PathVariable
Long
babyId
)
{
log
.
info
(
"Inside baby controller getBabyById method"
);
return
ResponseEntity
.
ok
(
babyService
.
getBabyById
(
babyId
));
}
@PutMapping
(
"/{id}"
)
public
ResponseEntity
<
BabyDto
>
updateBaby
(
@PathVariable
Long
babyId
,
@RequestBody
BabyDto
babyDto
)
{
log
.
info
(
"Inside baby controller updateBaby method"
);
return
ResponseEntity
.
ok
(
babyService
.
updateBaby
(
babyId
,
babyDto
));
}
@DeleteMapping
(
"/{id}"
)
public
ResponseEntity
<
ResponseDto
>
deleteBaby
(
@PathVariable
Long
babyId
)
{
log
.
info
(
"Inside baby controller deleteBaby method"
);
return
ResponseEntity
.
ok
(
babyService
.
deleteBaby
(
babyId
));
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/EmotionalDetectionController.java
0 → 100644
View file @
6b62e55e
//package com.kaluwa.enterprises.babycarebackendservice.rest;
//
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.Map;
//
//@RestController
//@RequestMapping("/emotional")
//@CrossOrigin(origins = "*")
//@Slf4j
//public class EmotionalDetectionController {
//
// @PostMapping("/process-video")
// public Map<String, String> processVideo(@RequestBody String imageData) {
// // Send the image data to the Python FastAPI server for processing
// // Implement WebSocket or HTTP client to send data to FastAPI server
// log.info("Received video frame for processing");
// return Map.of("status", "Received video frame for processing");
// }
//
//}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/TestController.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.rest
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.web.bind.annotation.GetMapping
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RestController
;
@RestController
@RequestMapping
(
"/test"
)
@Slf4j
public
class
TestController
{
@GetMapping
public
ResponseEntity
<
String
>
test
()
{
log
.
info
(
"Inside test controller"
);
return
new
ResponseEntity
<>(
"Test OK!"
,
HttpStatus
.
OK
);
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/UserController.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.rest
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.UserDto
;
import
com.kaluwa.enterprises.babycarebackendservice.service.UserService
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.web.bind.annotation.*
;
import
java.util.List
;
@RestController
@RequestMapping
(
"/user"
)
@Slf4j
public
class
UserController
{
private
final
UserService
userService
;
public
UserController
(
UserService
userService
)
{
this
.
userService
=
userService
;
}
// get user by id
@GetMapping
(
"/{userId}"
)
public
ResponseEntity
<
UserDto
>
getUserById
(
@PathVariable
Long
userId
)
{
log
.
info
(
"Inside user controller get user by id method"
);
return
new
ResponseEntity
<>(
userService
.
getUserById
(
userId
),
HttpStatus
.
OK
);
}
// get all users
@GetMapping
(
"/all"
)
public
ResponseEntity
<
List
<
UserDto
>>
getAllUsers
()
{
log
.
info
(
"Inside user controller get all users method"
);
return
new
ResponseEntity
<>(
userService
.
getAllUsers
(),
HttpStatus
.
OK
);
}
// update user
@PutMapping
(
"/{userId}"
)
public
ResponseEntity
<
UserDto
>
updateUser
(
@PathVariable
Long
userId
,
@RequestBody
UserDto
userDto
)
{
log
.
info
(
"Inside user controller update user method"
);
return
new
ResponseEntity
<>(
userService
.
updateUser
(
userId
,
userDto
),
HttpStatus
.
OK
);
}
// delete user
@DeleteMapping
(
"/{userId}"
)
public
ResponseEntity
<
ResponseDto
>
deleteUser
(
@PathVariable
Long
userId
)
{
log
.
info
(
"Inside user controller delete user method"
);
return
new
ResponseEntity
<>(
userService
.
deleteUser
(
userId
),
HttpStatus
.
OK
);
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/service/BabyService.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.service
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.BabyDto
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto
;
import
java.util.List
;
public
interface
BabyService
{
BabyDto
createBaby
(
BabyDto
babyDto
);
List
<
BabyDto
>
getAllBabies
();
BabyDto
getBabyById
(
Long
babyId
);
BabyDto
updateBaby
(
Long
babyId
,
BabyDto
babyDto
);
ResponseDto
deleteBaby
(
Long
babyId
);
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/service/UserService.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.service
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.*
;
import
java.util.List
;
public
interface
UserService
{
AuthenticationDto
login
(
LoginRequest
loginRequest
);
UserDto
register
(
RegisterRequest
registerRequest
);
UserDto
getUserById
(
Long
userId
);
List
<
UserDto
>
getAllUsers
();
UserDto
updateUser
(
Long
userId
,
UserDto
userDto
);
ResponseDto
deleteUser
(
Long
userId
);
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/service/impl/BabyCareUserDetailsService.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.service.impl
;
import
com.kaluwa.enterprises.babycarebackendservice.dao.UserDao
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.core.userdetails.UserDetailsService
;
import
org.springframework.security.core.userdetails.UsernameNotFoundException
;
import
org.springframework.stereotype.Service
;
@Service
public
class
BabyCareUserDetailsService
implements
UserDetailsService
{
private
final
UserDao
userDao
;
public
BabyCareUserDetailsService
(
UserDao
userDao
)
{
this
.
userDao
=
userDao
;
}
@Override
public
UserDetails
loadUserByUsername
(
String
username
)
throws
UsernameNotFoundException
{
return
userDao
.
findByEmail
(
username
).
orElseThrow
();
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/service/impl/BabyServiceImpl.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.service.impl
;
import
com.kaluwa.enterprises.babycarebackendservice.dao.BabyDao
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.BabyDto
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto
;
import
com.kaluwa.enterprises.babycarebackendservice.error.BadRequestAlertException
;
import
com.kaluwa.enterprises.babycarebackendservice.mappers.BabyMapper
;
import
com.kaluwa.enterprises.babycarebackendservice.model.Baby
;
import
com.kaluwa.enterprises.babycarebackendservice.service.BabyService
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.stereotype.Service
;
import
java.util.List
;
import
java.util.Optional
;
@Service
public
class
BabyServiceImpl
implements
BabyService
{
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
BabyServiceImpl
.
class
);
private
final
BabyDao
babyDao
;
private
final
BabyMapper
babyMapper
;
public
BabyServiceImpl
(
BabyDao
babyDao
,
BabyMapper
babyMapper
)
{
this
.
babyDao
=
babyDao
;
this
.
babyMapper
=
babyMapper
;
}
@Override
public
BabyDto
createBaby
(
BabyDto
babyDto
)
{
log
.
info
(
"Inside baby service createBaby method"
);
try
{
return
babyMapper
.
toDto
(
babyDao
.
save
(
babyMapper
.
toEntity
(
babyDto
)));
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
throw
new
BadRequestAlertException
(
e
.
getMessage
(),
"baby"
,
"baby.error"
);
}
}
@Override
public
List
<
BabyDto
>
getAllBabies
()
{
log
.
info
(
"Inside baby service getAllBabies method"
);
try
{
return
babyMapper
.
toDtoList
(
babyDao
.
findAll
());
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
throw
new
BadRequestAlertException
(
e
.
getMessage
(),
"baby"
,
"baby.error"
);
}
}
@Override
public
BabyDto
getBabyById
(
Long
babyId
)
{
log
.
info
(
"Inside baby service getBabyById method"
);
try
{
Optional
<
Baby
>
babyOp
=
babyDao
.
findById
(
babyId
);
if
(
babyOp
.
isEmpty
())
{
throw
new
BadRequestAlertException
(
"Baby not found"
,
"baby"
,
"baby.error"
);
}
else
{
return
babyMapper
.
toDto
(
babyOp
.
get
());
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
throw
new
BadRequestAlertException
(
e
.
getMessage
(),
"baby"
,
"baby.error"
);
}
}
@Override
public
BabyDto
updateBaby
(
Long
babyId
,
BabyDto
babyDto
)
{
log
.
info
(
"Inside baby service updateBaby method"
);
try
{
Optional
<
Baby
>
babyOp
=
babyDao
.
findById
(
babyId
);
if
(
babyDto
.
getBabyId
()
==
null
)
{
throw
new
BadRequestAlertException
(
"Baby id is required"
,
"baby"
,
"baby.error"
);
}
else
if
(!
babyId
.
equals
(
babyDto
.
getBabyId
()))
{
throw
new
BadRequestAlertException
(
"Baby id mismatch"
,
"baby"
,
"baby.error"
);
}
else
if
(
babyOp
.
isEmpty
())
{
throw
new
BadRequestAlertException
(
"Baby not found"
,
"baby"
,
"baby.error"
);
}
else
{
return
babyMapper
.
toDto
(
babyDao
.
save
(
babyMapper
.
toEntity
(
babyDto
)));
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
throw
new
BadRequestAlertException
(
e
.
getMessage
(),
"baby"
,
"baby.error"
);
}
}
@Override
public
ResponseDto
deleteBaby
(
Long
babyId
)
{
log
.
info
(
"Inside baby service deleteBaby method"
);
try
{
Optional
<
Baby
>
babyOp
=
babyDao
.
findById
(
babyId
);
if
(
babyOp
.
isEmpty
())
{
throw
new
BadRequestAlertException
(
"Baby not found"
,
"baby"
,
"baby.error"
);
}
else
{
babyDao
.
deleteById
(
babyId
);
ResponseDto
responseDto
=
new
ResponseDto
();
responseDto
.
setId
(
babyId
);
responseDto
.
setMessage
(
"Baby deleted successfully"
);
return
responseDto
;
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
throw
new
BadRequestAlertException
(
e
.
getMessage
(),
"baby"
,
"baby.error"
);
}
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/service/impl/UserServiceImpl.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.service.impl
;
import
com.kaluwa.enterprises.babycarebackendservice.dao.UserDao
;
import
com.kaluwa.enterprises.babycarebackendservice.dto.*
;
import
com.kaluwa.enterprises.babycarebackendservice.error.BadRequestAlertException
;
import
com.kaluwa.enterprises.babycarebackendservice.mappers.UserMapper
;
import
com.kaluwa.enterprises.babycarebackendservice.model.User
;
import
com.kaluwa.enterprises.babycarebackendservice.service.UserService
;
import
com.kaluwa.enterprises.babycarebackendservice.utils.JWTUtils
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.security.authentication.AuthenticationManager
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
import
org.springframework.security.crypto.password.PasswordEncoder
;
import
org.springframework.stereotype.Service
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Optional
;
import
static
com
.
kaluwa
.
enterprises
.
babycarebackendservice
.
constants
.
Common
.
TOKEN_TYPE
;
import
static
com
.
kaluwa
.
enterprises
.
babycarebackendservice
.
constants
.
Status
.
STATUS_NEW
;
import
static
com
.
kaluwa
.
enterprises
.
babycarebackendservice
.
constants
.
UserRoles
.
USER
;
import
static
com
.
kaluwa
.
enterprises
.
babycarebackendservice
.
utils
.
JWTUtils
.
EXPIRATION_TIME
;
@Service
@Slf4j
public
class
UserServiceImpl
implements
UserService
{
private
final
UserDao
userDao
;
private
final
BabyCareUserDetailsService
userDetailsService
;
private
final
JWTUtils
jwtUtils
;
private
final
PasswordEncoder
passwordEncoder
;
private
final
AuthenticationManager
authenticationManager
;
private
final
UserMapper
userMapper
;
public
UserServiceImpl
(
UserDao
userDao
,
BabyCareUserDetailsService
userDetailsService
,
JWTUtils
jwtUtils
,
PasswordEncoder
passwordEncoder
,
AuthenticationManager
authenticationManager
,
UserMapper
userMapper
)
{
this
.
userDao
=
userDao
;
this
.
userDetailsService
=
userDetailsService
;
this
.
jwtUtils
=
jwtUtils
;
this
.
passwordEncoder
=
passwordEncoder
;
this
.
authenticationManager
=
authenticationManager
;
this
.
userMapper
=
userMapper
;
}
@Override
public
AuthenticationDto
login
(
LoginRequest
loginRequest
)
{
log
.
info
(
"Inside user service login method"
);
AuthenticationDto
authenticationDto
=
new
AuthenticationDto
();
try
{
authenticationManager
.
authenticate
(
new
UsernamePasswordAuthenticationToken
(
loginRequest
.
getEmail
(),
loginRequest
.
getPassword
()));
User
user
=
userDao
.
findByEmail
(
loginRequest
.
getEmail
()).
orElseThrow
();
String
jwt
=
jwtUtils
.
generateToken
(
user
);
String
refreshToken
=
jwtUtils
.
generateRefreshToken
(
new
HashMap
<>(),
user
);
authenticationDto
.
setUserId
(
user
.
getUserId
());
authenticationDto
.
setFirstName
(
user
.
getFirstName
());
authenticationDto
.
setLastName
(
user
.
getLastName
());
authenticationDto
.
setEmail
(
user
.
getEmail
());
authenticationDto
.
setPhone
(
user
.
getPhone
());
authenticationDto
.
setRole
(
user
.
getRole
());
authenticationDto
.
setStatus
(
user
.
getStatus
());
TokenDto
tokenDto
=
new
TokenDto
();
tokenDto
.
setTokenType
(
TOKEN_TYPE
);
tokenDto
.
setToken
(
jwt
);
tokenDto
.
setRefreshToken
(
refreshToken
);
tokenDto
.
setExpiresIn
(
EXPIRATION_TIME
);
authenticationDto
.
setTokenDto
(
tokenDto
);
return
authenticationDto
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
throw
new
BadRequestAlertException
(
e
.
getMessage
(),
"User"
,
"User login failed"
);
}
}
@Override
public
UserDto
register
(
RegisterRequest
registerRequest
)
{
log
.
info
(
"Inside user service register method"
);
UserDto
userDto
=
new
UserDto
();
try
{
// validation
if
(
userDao
.
existsByEmail
(
registerRequest
.
getEmail
()))
{
throw
new
BadRequestAlertException
(
"Email already exists"
,
"User"
,
"User registration failed"
);
}
userDto
.
setFirstName
(
registerRequest
.
getFirstName
());
userDto
.
setLastName
(
registerRequest
.
getLastName
());
userDto
.
setEmail
(
registerRequest
.
getEmail
());
userDto
.
setPhone
(
registerRequest
.
getPhone
());
userDto
.
setRole
(
USER
);
userDto
.
setStatus
(
STATUS_NEW
);
User
user
=
userMapper
.
toEntity
(
userDto
);
user
.
setPassword
(
passwordEncoder
.
encode
(
registerRequest
.
getPassword
()));
userDto
=
userMapper
.
toDto
(
userDao
.
save
(
user
));
return
userDto
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
throw
new
BadRequestAlertException
(
e
.
getMessage
(),
"User"
,
"User registration failed"
);
}
}
@Override
public
UserDto
getUserById
(
Long
userId
)
{
log
.
info
(
"Inside user service get user by id method"
);
try
{
Optional
<
User
>
userOp
=
userDao
.
findById
(
userId
);
if
(
userOp
.
isEmpty
())
{
throw
new
BadRequestAlertException
(
"User not found"
,
"User"
,
"User not found"
);
}
else
{
return
userMapper
.
toDto
(
userOp
.
get
());
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
throw
new
BadRequestAlertException
(
e
.
getMessage
(),
"User"
,
"User registration failed"
);
}
}
@Override
public
List
<
UserDto
>
getAllUsers
()
{
log
.
info
(
"Inside user service get all users method"
);
try
{
List
<
User
>
users
=
userDao
.
findAll
();
return
userMapper
.
listToDto
(
users
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
throw
new
BadRequestAlertException
(
e
.
getMessage
(),
"User"
,
"User registration failed"
);
}
}
@Override
public
UserDto
updateUser
(
Long
userId
,
UserDto
userDto
)
{
log
.
info
(
"Inside user service update user method"
);
try
{
Optional
<
User
>
userOp
=
userDao
.
findById
(
userId
);
if
(
userDto
.
getUserId
()
==
null
)
{
throw
new
BadRequestAlertException
(
"User id is required"
,
"User"
,
"User update failed"
);
}
else
if
(!
userId
.
equals
(
userDto
.
getUserId
()))
{
throw
new
BadRequestAlertException
(
"User id mismatch"
,
"User"
,
"User update failed"
);
}
else
if
(
userOp
.
isEmpty
())
{
throw
new
BadRequestAlertException
(
"User not found"
,
"User"
,
"User not found"
);
}
else
if
(
userDto
.
getPhone
()
==
null
||
userDto
.
getPhone
().
isEmpty
())
{
throw
new
BadRequestAlertException
(
"Phone number is required"
,
"User"
,
"User update failed"
);
}
else
if
(
userDto
.
getFirstName
()
==
null
||
userDto
.
getFirstName
().
isEmpty
())
{
throw
new
BadRequestAlertException
(
"First name is required"
,
"User"
,
"User update failed"
);
}
else
if
(
userDto
.
getLastName
()
==
null
||
userDto
.
getLastName
().
isEmpty
())
{
throw
new
BadRequestAlertException
(
"Last name is required"
,
"User"
,
"User update failed"
);
}
else
{
User
user
=
userOp
.
get
();
user
.
setFirstName
(
userDto
.
getFirstName
());
user
.
setLastName
(
userDto
.
getLastName
());
user
.
setPhone
(
userDto
.
getPhone
());
return
userMapper
.
toDto
(
userDao
.
save
(
user
));
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
throw
new
BadRequestAlertException
(
e
.
getMessage
(),
"User"
,
"User registration failed"
);
}
}
@Override
public
ResponseDto
deleteUser
(
Long
userId
)
{
log
.
info
(
"Inside user service delete user method"
);
try
{
Optional
<
User
>
userOp
=
userDao
.
findById
(
userId
);
if
(
userOp
.
isEmpty
())
{
throw
new
BadRequestAlertException
(
"User not found"
,
"User"
,
"User not found"
);
}
else
{
userDao
.
deleteById
(
userId
);
ResponseDto
responseDto
=
new
ResponseDto
();
responseDto
.
setId
(
userId
);
responseDto
.
setMessage
(
"User deleted successfully"
);
return
responseDto
;
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
throw
new
BadRequestAlertException
(
e
.
getMessage
(),
"User"
,
"User registration failed"
);
}
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/socketHandlers/BoundingBox.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.socketHandlers
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
BoundingBox
{
private
int
x
;
private
int
y
;
private
int
width
;
private
int
height
;
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/socketHandlers/EmotionPrediction.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.socketHandlers
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
EmotionPrediction
{
private
String
emotion
;
private
BoundingBox
bounding_box
;
}
\ No newline at end of file
src/main/java/com/kaluwa/enterprises/babycarebackendservice/socketHandlers/SendVideoHandler.java
0 → 100644
View file @
6b62e55e
//package com.kaluwa.enterprises.babycarebackendservice.socketHandlers;
//
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//import org.springframework.web.socket.BinaryMessage;
//import org.springframework.web.socket.TextMessage;
//import org.springframework.web.socket.WebSocketSession;
//import org.springframework.web.socket.handler.BinaryWebSocketHandler;
//
//@Component
//@Slf4j
//public
src/main/java/com/kaluwa/enterprises/babycarebackendservice/socketHandlers/VideoFrameHandler.java
0 → 100644
View file @
6b62e55e
//package com.kaluwa.enterprises.babycarebackendservice.socketHandlers;
//
//import com.kaluwa.enterprises.babycarebackendservice.config.WebSocketClient;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.stereotype.Component;
//import org.springframework.web.socket.BinaryMessage;
//import org.springframework.web.socket.TextMessage;
//import org.springframework.web.socket.WebSocketSession;
//import org.springframework.web.socket.handler.BinaryWebSocketHandler;
//
//@Component
//@Slf4j
//public
//
src/main/java/com/kaluwa/enterprises/babycarebackendservice/utils/JWTUtils.java
0 → 100644
View file @
6b62e55e
package
com.kaluwa.enterprises.babycarebackendservice.utils
;
import
io.jsonwebtoken.Claims
;
import
io.jsonwebtoken.Jwts
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.stereotype.Component
;
import
javax.crypto.SecretKey
;
import
javax.crypto.spec.SecretKeySpec
;
import
java.nio.charset.StandardCharsets
;
import
java.util.Base64
;
import
java.util.Date
;
import
java.util.HashMap
;
import
java.util.function.Function
;
@Component
public
class
JWTUtils
{
private
SecretKey
key
;
public
static
final
long
EXPIRATION_TIME
=
86400000
;
// 24 hours
public
JWTUtils
()
{
String
secretString
=
"65465454513515456489879874512132154987745372522283393725456679995342135446687687"
;
byte
[]
keyBytes
=
Base64
.
getDecoder
().
decode
(
secretString
.
getBytes
(
StandardCharsets
.
UTF_8
));
this
.
key
=
new
SecretKeySpec
(
keyBytes
,
"HmacSHA256"
);
}
public
String
generateToken
(
UserDetails
userDetails
)
{
return
Jwts
.
builder
()
.
setSubject
(
userDetails
.
getUsername
())
.
setIssuedAt
(
new
Date
(
System
.
currentTimeMillis
()))
.
setExpiration
(
new
Date
(
System
.
currentTimeMillis
()
+
EXPIRATION_TIME
))
.
signWith
(
key
)
.
compact
();
}
public
String
generateRefreshToken
(
HashMap
<
String
,
Object
>
claims
,
UserDetails
userDetails
)
{
return
Jwts
.
builder
()
.
setClaims
(
claims
)
.
setSubject
(
userDetails
.
getUsername
())
.
setIssuedAt
(
new
Date
(
System
.
currentTimeMillis
()))
.
setExpiration
(
new
Date
(
System
.
currentTimeMillis
()
+
EXPIRATION_TIME
))
.
signWith
(
key
)
.
compact
();
}
public
String
extractUsername
(
String
token
)
{
return
extractClaims
(
token
,
Claims:
:
getSubject
);
}
private
<
T
>
T
extractClaims
(
String
token
,
Function
<
Claims
,
T
>
claimsTFunction
)
{
return
claimsTFunction
.
apply
(
Jwts
.
parserBuilder
()
.
setSigningKey
(
key
)
.
build
()
.
parseClaimsJws
(
token
)
.
getBody
()
);
}
public
boolean
isTokenValid
(
String
token
,
UserDetails
userDetails
)
{
final
String
username
=
extractUsername
(
token
);
return
(
username
.
equals
(
userDetails
.
getUsername
())
&&
!
isTokenExpired
(
token
));
}
private
boolean
isTokenExpired
(
String
token
)
{
return
extractClaims
(
token
,
Claims:
:
getExpiration
).
before
(
new
Date
());
}
}
src/main/resources/application.yaml
View file @
6b62e55e
spring
:
application
:
name
:
baby-care-backend-service
security
:
user
:
name
:
user
password
:
password
datasource
:
url
:
jdbc:mysql://localhost:3306/baby_care_db?useSSL=false&serverTimezone=UTC
username
:
root
password
:
root
driver-class-name
:
com.mysql.cj.jdbc.Driver
jpa
:
hibernate
:
ddl-auto
:
update
show-sql
:
false
properties
:
hibernate
:
format_sql
:
true
server
:
port
:
8080
...
...
src/test/java/com/kaluwa/enterprises/babycarebackendservice/BabyCareBackendServiceApplicationTests.java
View file @
6b62e55e
...
...
@@ -2,8 +2,10 @@ package com.kaluwa.enterprises.babycarebackendservice;
import
org.junit.jupiter.api.Test
;
import
org.springframework.boot.test.context.SpringBootTest
;
import
org.springframework.test.context.web.WebAppConfiguration
;
@SpringBootTest
@WebAppConfiguration
class
BabyCareBackendServiceApplicationTests
{
@Test
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment