Commit c896b352 authored by Tharuka Dilshan's avatar Tharuka Dilshan

Merge branch 'master' into Dilshan-P.G.T-DEV

parents 784286fe 270dbbfa
This diff is collapsed.
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
This diff is collapsed.
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.4.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-record-webcam": "^0.0.18",
"react-router-dom": "^6.14.1",
"react-scripts": "5.0.1",
"react-webcam": "^7.0.1",
"recordrtc": "^5.6.2",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@300&display=swap" rel="stylesheet">
<link href="../src/styles/common.css" rel="stylesheet">
<title>Shrasthra - ශ්‍රස්ත්‍ර</title>
</head>
<body class="">
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
\ No newline at end of file
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import SideNavBar from './components/SideNavBar';
import Footer from './components/Footer';
import './styles/main.css';
import './styles/sidenav.css';
import './styles/videoToSign.css';
import VideoToSign from './pages/VideoToSign';
import Login from './pages/Login';
import Register from './pages/Register';
import { useEffect, useState } from 'react';
import Test from './pages/Test';
function App() {
const[isLogged, setIsLogged] = useState(sessionStorage.getItem("isLogged"));
const[token, setToken] = useState(sessionStorage.getItem("token"));
const[username, setUserName] = useState(sessionStorage.getItem("username"));
const[userId, setUserId] = useState(sessionStorage.getItem("userId"));
return (
<div class="container-fluid bg" >
<div className='row'>
{isLogged ?
<Router>
<SideNavBar />
<div className="col-lg-10 p-5" style={{height:'100vh'}}>
<div className='content-div'>
<Routes>
{/* <Route path='*' element={<VideoToSign/>}/> */}
<Route exact path='/sign-detection' element={<VideoToSign/>}/>
</Routes>
</div>
</div>
</Router>
:
<Router>
<div className="col-lg-12 p-5" style={{height:'100vh'}}>
<div className='content-div'>
<Routes>
<Route exact path='*' element={<Login/>}/>
<Route exact path='/test' element={<Test/>}/>
<Route exact path='/login' element={<Login/>}/>
<Route exact path='/register' element={<Register/>}/>
</Routes>
</div>
</div>
</Router>
}
{/* */}
</div>
</div>
);
}
export default App;
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
import React,{useEffect, useState} from "react";
function Footer() {
return (
<div className="row" style={{backgroundColor:'blue', height:'10vh'}}>
© Copyright 2017 Alvaro Trigo
</div>
);
}
export default Footer;
\ No newline at end of file
import React,{useEffect, useState} from "react";
import { NavLink } from 'react-router-dom';
import { useLocation } from 'react-router';
function SideNavBar() {
const[isLogged, setIsLogged] = useState(sessionStorage.getItem("isLogged"));
const[token, setToken] = useState(sessionStorage.getItem("token"));
const[username, setUserName] = useState(sessionStorage.getItem("username"));
const[name, setName] = useState(sessionStorage.getItem("name"));
const[userId, setUserId] = useState(sessionStorage.getItem("userId"));
function handleLogout() {
sessionStorage.clear();
window.location.href = '/login';
}
const location = useLocation();
return (
<div className="col-lg-2" style={{backgroundColor:'', height:'100vh', }}>
<div className="row pr-5 pl-5 pt-2 d-flex justify-content-center" style={{height:'20%'}}>
<a className="logo-title navbar-brand" href="/" style={{color:'white'}}>Y%ia;%</a>
</div>
<div className="" style={{height:'60%', backgroundColor:'',}}>
<div className="d-flex justify-content-center align-items-center" style={{marginLeft:'5%'}}>
<nav class="nav flex-column mt-5">
{/* අධ්‍යයනය */}
<NavLink exact to="/" className="nav-link main-nav-link" activeClassName="active-link">wOHhkh</NavLink>
{/* සංඥා ශබ්දකෝෂය */}
<NavLink exact to="/about" className="nav-link main-nav-link" activeClassName="active-link">ix&#123;d YíofldaIh</NavLink>
{/* ශබ්ද පරිවර්ථකය */}
<NavLink exact to="/contact" className="nav-link main-nav-link" activeClassName="active-link">Yío mßj¾:lh</NavLink>
{/* සංඥා හඳුනාගැනීම */}
<NavLink exact to="/sign-detection" className="nav-link main-nav-link " activeClassName="active-link">ix&#123;d y÷kd.ekSu</NavLink>
{/* වාචික පුහුණුව */}
<NavLink exact to="/services" className="nav-link main-nav-link" activeClassName="active-link">jdÑl mqyqKqj</NavLink>
</nav>
</div>
</div>
<div style={{height:'20%' }} className="d-flex justify-content-center align-items-center">
<div class="btn-group">
<button type="button" class=" nav-link user-btn dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{name}
</button>
<div class="dropdown-menu dropdown-menu-right">
<button class="dropdown-item" type="button">View Profile</button>
<button class="dropdown-item" type="button" onClick={handleLogout}>Logout</button>
</div>
</div>
</div>
</div>
);
}
export default SideNavBar;
\ No newline at end of file
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>
\ No newline at end of file
import React,{useEffect, useRef, useState} from "react";
import RestService from "../services/RestService";
import bg from '../images/bg-2.png'
import '../styles/auth.css';
function Login() {
const[username, setUsername] = useState();
const[password, setPassword] = useState();
function handleAuthenticate(){
RestService.authenticateUser(username, password).then((res)=>{
console.log(res.data)
if(res.data.token != null){
sessionStorage.setItem("token", res.data.token);
sessionStorage.setItem("isLogged", true);
sessionStorage.setItem("name", res.data.userDto.name);
sessionStorage.setItem("email", res.data.userDto.email);
sessionStorage.setItem("role", res.data.userDto.userRole);
sessionStorage.setItem("username", res.data.userDto.username);
sessionStorage.setItem("userId", res.data.userDto.userId);
window.location.href = '/';
} else {
alert('Failed Login')
}
}).catch((err)=>{
console.log(err);
})
}
return (
<div className="d-flex align-items-center justify-content-center" style={{ height: '100%' }} >
<div className="col-lg-6 p-2 " style={{ height: '92%', width: '50%'}} >
<div className="row d-flex align-items-center justify-content-center">
<h1 className="site-title">Y%ia;%</h1>
<h5 className="site-slogan">Unlocking Sign Language Proficiency with Shrasthra</h5>
<img src={bg} style={{width:'60%'}} />
</div>
</div>
<div className="login-card col-lg-6 p-5 " style={{ height: '92%' }} >
<div className="d-flex align-items-center justify-content-center ">
<h2>LOGIN</h2>
</div>
<div className="" style={{ margin: '0', backgroundColor: '' }} >
<div className="form-group">
<label>Username</label>
<input type="text" className="form-control" onChange={(e)=>setUsername(e.target.value)} />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" className="form-control" onChange={(e)=>setPassword(e.target.value)} />
</div>
<div className=" d-flex align-items-center justify-content-center" style={{ height: '100px' }}>
<button className="btn btn-login" onClick={handleAuthenticate}>LOGIN</button>
</div>
<div className="d-flex align-items-center justify-content-center custom-text">
<i>Don't have an account?</i>
<a className="ml-2" href="/register">Register Now</a>
</div>
</div>
</div>
</div>
);
}
export default Login;
\ No newline at end of file
import React,{useEffect, useRef, useState} from "react";
import { useRecordWebcam } from 'react-record-webcam'
function RecordVideo(props) {
const recordWebcam = useRecordWebcam({ frameRate: 60 });
useEffect(() => {
recordWebcam.open()
}, []);
const saveFile = async () => {
const blob = await recordWebcam.getRecording();
};
return (
<div>
<p>Camera status: {recordWebcam.status}</p>
<button onClick={recordWebcam.open}>Open camera</button>
<button onClick={recordWebcam.start}>Start recording</button>
<button onClick={recordWebcam.stop}>Stop recording</button>
<button onClick={recordWebcam.retake}>Retake recording</button>
<button onClick={recordWebcam.download}>Download recording</button>
<button onClick={saveFile}>Save file to server</button>
<video ref={recordWebcam.webcamRef} autoPlay muted />
<video ref={recordWebcam.previewRef} autoPlay muted loop />
</div>
)
}
export default RecordVideo;
\ No newline at end of file
import React,{useEffect, useRef, useState} from "react";
import { useRecordWebcam } from 'react-record-webcam'
import RestService from "../services/RestService";
import bg from '../images/bg-2.png'
import '../styles/auth.css';
function Register() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [username, setUsername] = useState("");
useEffect(() => {
}, []);
function handleRegister(){
if(name === "" || email === "" || username === "" || password === ""){
alert("Input fields can't be empty");
return;
}
const userDto = {
email:email,
name:name,
username:username,
password:password,
userRole:1
}
RestService.register(userDto).then((res)=>{
if(res.data.userId != null){
alert('Registered Successfully')
window.location.href = '/login';
} else {
alert('Failed to register')
}
}).catch((err)=>{
console.log(err);
})
}
return (
<div className="d-flex align-items-center justify-content-center" style={{ height: '100%' }} >
<div className="col-lg-6 p-2 " style={{ height: '92%', width: '50%'}} >
<div className="row d-flex align-items-center justify-content-center">
<h1 className="site-title">Y%ia;%</h1>
<h5 className="site-slogan">Unlocking Sign Language Proficiency with Shrasthra</h5>
<img src={bg} style={{width:'60%'}} />
</div>
</div>
<div className="login-card col-lg-6 p-5 " style={{ height: '92%' }} >
{/* <h1 className="main-title">Y%ia;%</h1> */}
<div className="d-flex align-items-center justify-content-center ">
<h2>- REGISTER -</h2>
</div>
<div>
<div className="row" >
<div className="form-group col-lg-6">
<label>Name</label>
<input type="text" className="form-control" onChange={(e)=>setName(e.target.value)} />
</div>
<div className="form-group col-lg-6">
<label>Email</label>
<input type="text" className="form-control" onChange={(e)=>setEmail(e.target.value)} />
</div>
</div>
<div className="row">
<div className="form-group col-lg-6">
<label>Username</label>
<input type="text" className="form-control" onChange={(e)=>setUsername(e.target.value)} />
</div>
<div className="form-group col-lg-6">
<label>Password</label>
<input type="password" className="form-control" onChange={(e)=>setPassword(e.target.value)} />
</div>
</div>
<div className="d-flex align-items-center justify-content-center" style={{ height: '100px' }}>
<button className="btn btn-login" onClick={handleRegister}>REGISTER</button>
</div>
<div className="d-flex align-items-center justify-content-center custom-text">
<i>Already have an account?</i>
<a className="ml-2" href="/login">Login Now</a>
</div>
</div>
</div>
</div>
);
}
export default Register;
\ No newline at end of file
import React,{useEffect, useRef, useState} from "react";
import axios from 'axios';
function Test() {
const [selectedImage, setSelectedImage] = useState(null);
const handleImageChange = (e) => {
const file = e.target.files[0];
setSelectedImage(file);
};
const handleUpload = () => {
// console.log(selectedImage)
fetch("https://cdn.discordapp.com/attachments/1070777983108919526/1137609428267450398/187.jpg")
.then((response) => response.blob())
.then((imageBlob) => {
const file = new File([imageBlob], 'Test.jpg', { type: imageBlob.type });
const formData = new FormData();
formData.append('fileData', file);
axios.post('http://localhost:2500/api/data',formData).then((res)=>{
console.log(res);
}).catch((err)=>{
console.log(err)
})
})
.catch((error) => {
// Handle errors if the image fetch fails.
});
};
useEffect(() => {
handleUpload()
}, []);
return (
<div>
<input type="file" accept="image/*" onChange={handleImageChange} />
<button onClick={handleUpload}>Upload Image</button>
</div>
);
}
export default Test;
\ No newline at end of file
import React,{useEffect, useRef, useState} from "react";
import { useRecordWebcam } from 'react-record-webcam'
import RestService from "../services/RestService";
import bg from '../images/Wood.png'
function VideoToSign() {
const[isLogged, setIsLogged] = useState(sessionStorage.getItem("isLogged"));
const[token, setToken] = useState(sessionStorage.getItem("token"));
const[username, setUserName] = useState(sessionStorage.getItem("username"));
const[userId, setUserId] = useState(sessionStorage.getItem("userId"));
const [recordedVideo, setRecordedVideo] = useState([]);
const [count, setCount] = useState(null);
const [endCount, setEndCount] = useState(0);
const [status, setStatus] = useState('OPEN');
const [meaning, setMeaning] = useState('Sample Text');
const recordWebcam = useRecordWebcam({ frameRate: 60 });
useEffect(() => {
recordWebcam.open();
}, []);
useEffect(() => {
if(count > 0){
const interval = setInterval(() => {
setCount(count - 1);
}, 1000);
return () => {
clearInterval(interval);
};
}
}, [count]);
function handleDetection(){
setMeaning('')
let retakePromise = new Promise(function(resolve, reject){
resolve(recordWebcam.retake());
})
let stoppedPromise = new Promise(function(resolve, reject) {
setTimeout(()=>{
resolve(recordWebcam.stop())
},5000)
});
retakePromise.then(()=>{
setEndCount(0)
recordWebcam.start();
}).then(()=>{
stoppedPromise.then(()=>{
setStatus("PREVIEW")
setCount(null)
detectSign();
})
})
}
async function detectSign() {
const blob = await recordWebcam.getRecording();
const file = new File([blob], 'Test.mp4', { type: blob.type });
const fileData = new FormData();
fileData.append('file', file);
RestService.detectSign(token,fileData).then((res)=>{
setMeaning(res.data.signMap.value);
console.log(res);
}).catch((err)=>{
console.log(err);
})
}
async function downloadFile(){
const blob = await recordWebcam.getRecording();
const file = new File([blob], 'Test.mkv', { type: blob.type });
// Create a download link
const downloadLink = document.createElement('a');
downloadLink.href = URL.createObjectURL(file);
downloadLink.download = file.name;
// Programmatically click the link to initiate the download
downloadLink.click();
// Clean up the URL object
URL.revokeObjectURL(downloadLink.href);
}
return (
<div style={{height:'100%'}} >
<div className="content-title d-flex justify-content-center align-items-center">
<h2> - ix&#123;d y÷kd.ekSu -</h2>
</div>
<div className="mt-3" style={{height:'92%'}} >
<div className="row" style={{margin:'0'}} >
<div className="col col-lg-8 ">
<div className="d-flex align-items-center justify-content-center">
<video ref={recordWebcam.webcamRef} autoPlay muted className="video-box" />
</div>
<hr className="line"></hr>
<div className="small-card p-2">
<div className="row d-flex justify-content-center">
{recordWebcam.status == "RECORDING" ? <h5>Detection has started.</h5> : <h5>Sign detection will start in {count == null ? 5 : count} </h5>}
</div>
<div className="row d-flex justify-content-center">
<button className="btn video-btn" onClick={()=>{setTimeout(handleDetection,5000);setCount(5)}}>Start Detect</button>
</div>
</div>
<hr className="line"></hr>
</div>
<div className="col d-flex align-items-center justify-content-center custom-card " >
<div>
<video ref={recordWebcam.previewRef} autoPlay muted loop className="video-box-small mt-3 "/>
<h5 className="row d-flex justify-content-center pt-2">Preview</h5>
<hr className="line-light"></hr>
<div className="small-card p-2 ">
<h3 className="mt-4" style={{fontFamily:'FMAbayaBld'}}>w¾:h ( </h3>
<div className=" ">
<h1 className="d-flex align-items-center justify-content-center" >{meaning}</h1>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default VideoToSign;
\ No newline at end of file
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;
import axios from 'axios';
const BASE_URL = "http://127.0.0.1:5000/";
const BACKEND_URL = "http://localhost:8885/ShrasthraBackendService/";
class RestService {
register(userDto) {
return axios.post(BACKEND_URL + 'register',userDto)
}
authenticateUser(username, password) {
return axios.post(BACKEND_URL + 'authenticate',{username:username, password:password})
}
detectSign(token, formData) {
const config = {
headers: {
'Access-Control-Allow-Origin': "*",
'Authorization': 'Bearer ' + token
}
}
return axios.post(BACKEND_URL + 'sign/detectDynamicSign',formData, config)
}
// detectSign(formData) {
// return axios.post(BASE_URL + 'api/data',formData)
// }
// authenticateUser(username, password) {
// return axios.post(USER_BASE_URL + 'api/user/login',{username:username, password:password})
// }
// getAllUsers(token) {
// const config = {
// headers: {
// 'Access-Control-Allow-Origin': "*",
// 'Authorization': 'Bearer ' + token
// }
// }
// return axios.get(USER_BASE_URL + 'api/user/getAll', config)
// }
}
export default new RestService();
\ No newline at end of file
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
.site-title {
font-family: 'SARA-SETH';
color: #c93200;
font-size: 8.5rem;
text-align: center;
text-shadow: 5px 5px #000000;
}
.site-slogan {
font-weight: 500;
color: #c93200;
font-size: 1.2rem;
text-align: center;
border-bottom: #c93200 ;
border-bottom: 2px;
border-bottom-style: solid;
padding-bottom: 3%;
padding-top: 1%;
}
.form-control {
border-radius: 20px;
}
.form-group {
margin-top: 2vh;
}
.form-group label {
font-size: larger;
font-weight: bold;
color: white;
}
.login-card {
background-color: #c93200;
border-radius: 30px;
}
.login-card h2 {
color: white;
font-size: 3rem;
font-weight: lighter;
}
.btn-login {
width: 120px;
border-radius: 30px;
font-weight: bold;
font-size: larger;
color: #c93200;
}
.btn-login:hover {
background-color: #c93200;
color: white;
border: 2px solid white;
}
.custom-text {
color: white;
}
.custom-text a {
color: aliceblue;
font-weight: bold;
}
.main-title {
font-family: 'SARA-SETH';
color: white;
font-size: 5rem;
text-align: center;
}
\ No newline at end of file
.bg {
background-image: url('../images/Background.jpg');
background-repeat: no-repeat;
background-size: cover;
/* background-color: #ff5b22; */
}
.card-bg {
background-color: #ff5b22;
}
.content-div {
background-color: white;
width: 100%;
height: 100%;
border-radius: 30px;
padding: 2%;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.103), 0 6px 20px 0 rgba(0, 0, 0, 0.082);
/* background-image: url('https://t4.ftcdn.net/jpg/04/70/55/73/360_F_470557375_GW11DOIa8jCOKzoVqNZsBgVo164ftq8R.jpg'); */
background-image: url('../images/Skulls.jpg');
background-color: rgb(253, 235, 214);
}
.content-title {
font-family: 'FMAbayaBld';
font-size: 2.5vw;
color: #ffffff;
background-color: #af2c00;
border-radius: 2vw;
height: 10%;
margin: 0;
}
.sinhala-font {
font-family: 'SQ';
font-size: 1.5vw;
color: #af2c00;
}
@font-face {
font-family: "SARA-SETH";
src: url(../fonts/SARA_SETH.ttf) format('truetype');
}
@font-face {
font-family: "FMAbayaBld";
src: url(../fonts/FMAbayaBld.TTF) format('truetype');
}
@font-face {
font-family: "SQ";
src: url(../fonts/SQ.ttf) format('truetype');
}
.logo-title {
font-family: 'SARA-SETH';
font-size: 6vw;
border-style: none;
text-decoration: none;
text-align: center;
align-items: center;
width: 100%;
text-shadow: 5px 5px #000000;
}
.main-nav-link {
color: white;
margin: 4% 0;
font-size: 1.5vw;
font-weight: 700;
font-family: 'FMAbayaBld';
border-style: solid;
border-color: aliceblue;
border-radius: 30px;
background-color: #c93200;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.552), 0 10px 10px 0 rgba(0, 0, 0, 0.338);
}
.main-nav-link:hover {
background-color: #631900;
color: white;
border-radius: 30px;
}
.main-nav-link:focus {
background-color: #631900;
color: white;
border-radius: 30px;
}
.main-nav-link:active {
background-color: #631900;
color: white;
border-radius: 30px;
}
.active{
background-color: #631900;
color: white;
border-radius: 30px;
}
.user-btn {
color: white;
margin: 4% 0;
font-weight: bold;
border-style: solid;
border-color: aliceblue;
border-radius: 30px;
background-color: #c9320077;
}
.video-box {
border-width: 2px;
border-color:#af2c00;
border-style: solid;
border-radius: 2vw;
/* box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.552), 0 10px 10px 0 rgba(0, 0, 0, 0.338); */
/* box-shadow: 0 1px 10px 0 rgba(66, 66, 66, 0.336), 0 6px 20px 0 rgba(100, 100, 100, 0.082); */
/* width: 40vw; */
height: 50vh;
background-color: black;
background-image: url('../images/Skulls.jpg');
}
.video-box-small {
border-width: 2px;
border-color:#af2c00;
border-style: solid;
border-radius: 2vw;
/* box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.552), 0 10px 10px 0 rgba(0, 0, 0, 0.338); */
/* box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.336), 0 6px 20px 0 rgba(0, 0, 0, 0.082); */
/* box-shadow: 0 1px 10px 0 rgba(66, 66, 66, 0.336), 0 6px 20px 0 rgba(100, 100, 100, 0.082); */
height: 15vw;
width: 20vw;
background-image: url('../images/Skulls.jpg');
background-color: black;
}
.video-btn {
background-color: #ff835a;
color: aliceblue;
border-radius: 30px;
width: 10vw;
font-size: 1.3vw;
font-family: Arial, Helvetica, sans-serif;
/* font-weight: bold; */
}
.video-btn:hover {
background-color: #af2c00;
}
.line {
border: 1px solid #af2c00;
border-radius: 5px;
width: 70%;
}
.line-light {
border: 1px solid white;
border-radius: 5px;
width: 70%;
}
/* .small-card {
background-color: aliceblue;
border-radius: 30px;
box-shadow: 0 1px 10px 0 rgba(66, 66, 66, 0.336), 0 6px 20px 0 rgba(100, 100, 100, 0.082)
} */
.result {
/* background-image: url('../images/Wood.png'); */
position: relative;
text-align: center;
color: white;
}
.center-text-custom {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.custom-card {
/* border: 2px solid #af2c00; */
background-color: #af2c00;
border-radius: 30px;
/* height: 9vh; */
height: 95%;
color: aliceblue;
/* box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.552), 0 10px 10px 0 rgba(0, 0, 0, 0.338); */
}
\ No newline at end of file
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
This diff is collapsed.
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>shrasthra.backend</groupId>
<artifactId>ShrasthraBackend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>ShrasthraBackend</name>
<description>Research</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package shrasthra.backend;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ShrasthraBackendApplication.class);
}
}
package shrasthra.backend;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ShrasthraBackendApplication {
public static void main(String[] args) {
SpringApplication.run(ShrasthraBackendApplication.class, args);
}
}
package shrasthra.backend.config;
import java.io.IOException;
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
private static final long serialVersionUID = -7858869558953243875L;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
package shrasthra.backend.config;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
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 io.jsonwebtoken.ExpiredJwtException;
import shrasthra.backend.service.impl.JwtUserDetailsService;
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
@Autowired
private JwtUserDetailsService jwtUserDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String jwtToken = null;
// JWT Token is in the form "Bearer token". Remove Bearer word and get only the Token
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
System.out.println("JWT Token has expired");
}
} else {
logger.warn("JWT Token does not begin with Bearer String");
}
//Once we get the token validate it.
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);
// if token is valid configure Spring Security to manually set authentication
if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// After setting the Authentication in the context, we specify
// that the current user is authenticated. So it passes the Spring Security Configurations successfully.
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
}
package shrasthra.backend.config;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Component
public class JwtTokenUtil implements Serializable {
private static final long serialVersionUID = -2550185165626007488L;
public static final long JWT_TOKEN_VALIDITY = 5*60*60;
@Value("${jwt.secret}")
private String secret;
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getIssuedAtDateFromToken(String token) {
return getClaimFromToken(token, Claims::getIssuedAt);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
private Boolean ignoreTokenExpiration(String token) {
// here you specify tokens, for that the expiration is ignored
return false;
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, userDetails.getUsername());
}
private String doGenerateToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY*1000)).signWith(SignatureAlgorithm.HS512, secret).compact();
}
public Boolean canTokenBeRefreshed(String token) {
return (!isTokenExpired(token) || ignoreTokenExpiration(token));
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
}
package shrasthra.backend.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private UserDetailsService jwtUserDetailsService;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// configure AuthenticationManager so that it knows from where to load
// user for matching credentials
// Use BCryptPasswordEncoder
auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// We don't need CSRF for this example
httpSecurity.csrf().disable()
// dont authenticate this particular request
.authorizeRequests().antMatchers("/authenticate", "/register").permitAll().
// all other requests need to be authenticated
anyRequest().authenticated().and().
// make sure we use stateless session; session won't be used to
// store user's state.
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
httpSecurity.cors().and();
}
}
package shrasthra.backend.controller;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import shrasthra.backend.config.JwtTokenUtil;
import shrasthra.backend.dao.dto.AppUserDto;
import shrasthra.backend.dao.dto.JwtRequest;
import shrasthra.backend.dao.dto.JwtResponse;
import shrasthra.backend.service.impl.JwtUserDetailsService;
@RestController
@CrossOrigin
public class JwtAuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserDetailsService jwtInMemoryUserDetailsService;
@Autowired
private JwtUserDetailsService userDetailsService;
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest)
throws Exception {
authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
final UserDetails userDetails = jwtInMemoryUserDetailsService
.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
AppUserDto userDto = userDetailsService.findUserByUsername(authenticationRequest.getUsername());
return ResponseEntity.ok(new JwtResponse(token, userDto));
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity<?> saveUser(@RequestBody AppUserDto user) throws Exception {
return ResponseEntity.ok(userDetailsService.save(user));
}
private void authenticate(String username, String password) throws Exception {
Objects.requireNonNull(username);
Objects.requireNonNull(password);
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) {
throw new Exception("USER_DISABLED", e);
} catch (BadCredentialsException e) {
throw new Exception("INVALID_CREDENTIALS", e);
}
}
}
package shrasthra.backend.controller;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import shrasthra.backend.dao.dto.ProcessRequestDto;
import shrasthra.backend.dao.dto.ProcessResponseDto;
import shrasthra.backend.service.i.ShrasthraBackendService;
import shrasthra.backend.util.common.REST_CONTROLLER_URL;
@RestController
@CrossOrigin
public class ShrasthraBackendController {
@Autowired
ShrasthraBackendService backendService;
@RequestMapping(value = REST_CONTROLLER_URL.DETECT_DYNAMIC_SIGN, method = RequestMethod.POST)
public @ResponseBody ProcessResponseDto saveQuotation(@RequestParam("file") MultipartFile file, HttpServletRequest request){
ProcessResponseDto responseDto = new ProcessResponseDto();
responseDto = backendService.detectDynamicSign(file);
return responseDto;
}
// @RequestMapping(value = REST_CONTROLLER_URL.DETECT_DYNAMIC_SIGN, method = RequestMethod.POST)
// public @ResponseBody ProcessResponseDto saveQuotation(@RequestParam("file") MultipartFile file, HttpServletRequest request){
// ProcessResponseDto responseDto = new ProcessResponseDto();
//
// // Check if the file is not empty and process it
// if (!file.isEmpty()) {
// try {
// // Convert the file to bytes
// byte[] fileBytes = file.getBytes();
//
//
// RestTemplate restTemplate = new RestTemplate();
//
// // Set the URL of your Python Flask API
// String url = "http://127.0.0.1:5000/api/data";
//
// // Create headers and set content type as multipart/form-data
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//
// // Create the request body with the file as a part
// MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
// requestBody.add("fileData", new ByteArrayResource(fileBytes) {
// @Override
// public String getFilename() {
// return file.getOriginalFilename();
// }
// });
//
// // Create the request entity with headers and body
// HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
//
// // Make the POST request to the second API
// ResponseEntity<ProcessResponseDto> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, ProcessResponseDto.class);
//
// // Retrieve the response body
// ProcessResponseDto responseBody = response.getBody();
//
// // Print the response
// System.out.println(responseBody.getSign());
//
//
// } catch (Exception e) {
//// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to process the video file.");
// }
// } else {
//// return ResponseEntity.badRequest().body("No video file provided.");
// }
//
// return responseDto;
// }
}
package shrasthra.backend.dao.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import static javax.persistence.GenerationType.IDENTITY;
@Entity
@Table(name = "app_user", catalog = "shrasthra")
public class AppUser {
private Integer userId;
private String username;
private String name;
private String email;
private Integer userRole;
private String password;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "user_role")
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
@Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package shrasthra.backend.dao.domain;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
@Data
@Entity
@Table(name = "app_user", catalog = "shrasthra")
public class McqWord {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
private String label;
private String value;
private String opt1;
private String opt2;
private String opt3;
private String opt4;
}
package shrasthra.backend.dao.domain;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "sign_map", catalog = "shrasthra")
public class SignMap {
private Integer id;
private String label;
private String value;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "label")
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
@Column(name = "value")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
package shrasthra.backend.dao.dto;
import lombok.Data;
@Data
public class AppUserDto {
private Integer userId;
private String username;
private String name;
private String email;
private Integer userRole;
private String password;
}
package shrasthra.backend.dao.dto;
import java.io.Serializable;
public class JwtRequest implements Serializable {
private static final long serialVersionUID = 5926468583005150707L;
private String username;
private String password;
//need default constructor for JSON Parsing
public JwtRequest()
{
}
public JwtRequest(String username, String password) {
this.setUsername(username);
this.setPassword(password);
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
\ No newline at end of file
package shrasthra.backend.dao.dto;
import java.io.Serializable;
public class JwtResponse implements Serializable {
private static final long serialVersionUID = -8091879091924046844L;
private final String jwttoken;
private final AppUserDto userDto;
public JwtResponse(String jwttoken, AppUserDto userDto) {
this.jwttoken = jwttoken;
this.userDto = userDto;
}
public String getToken() {
return this.jwttoken;
}
public AppUserDto getUserDto() {
return userDto;
}
}
\ No newline at end of file
package shrasthra.backend.dao.dto;
import lombok.Data;
@Data
public class ProcessRequestDto {
private byte[] video;
}
package shrasthra.backend.dao.dto;
import lombok.Data;
import shrasthra.backend.dao.domain.SignMap;
@Data
public class ProcessResponseDto {
private boolean isSuccess;
private String message;
private String sign;
private SignMap signMap;
}
package shrasthra.backend.repository;
//package sliit.csse.backend.repository;
//
//import java.util.List;
//
//import javax.transaction.Transactional;
//
//import org.springframework.data.jpa.repository.JpaRepository;
//import org.springframework.data.jpa.repository.Modifying;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.query.Param;
//
//import sliit.csse.backend.dao.domain.AppUser;
//
//
//
//
//public interface AppUserRepository extends JpaRepository<AppUser, Integer> {
//
// public AppUser findByUsername(String username);
//
// @Query("SELECT a FROM AppUser a")
// public List<AppUser> getAllUsers();
//
//
//
// @Query("SELECT a FROM AppUser a WHERE a.username=:username")
// public AppUser getUserByUserName(@Param("username") String username);
//
// @Transactional
// @Query("UPDATE AppUser a SET a.username=:username WHERE a.userId=:userId ")
// @Modifying(clearAutomatically = true)
// public int updateUsername(@Param("userId") Integer userId, @Param("username") String username);
//
// @Query("SELECT a FROM AppUser a WHERE a.userId=:userId")
// public AppUser findUserById(@Param("userId") Integer userId);
//
// @Transactional
// @Query("UPDATE AppUser a SET a.userRole=:userRole WHERE a.userId=:userId ")
// @Modifying(clearAutomatically = true)
// public int updateUserRole(@Param("userId") Integer userId, @Param("userRole") Integer userRole);
//
// @Transactional
// @Query("UPDATE AppUser a SET a.firstName=:firstName, a.lastName=:lastName, a.email=:email, a.mobile=:mobile WHERE a.userId=:userId")
// @Modifying(clearAutomatically = true)
// public int updateProfile(@Param("userId") Integer userId, @Param("firstName") String firstName, @Param("lastName") String lastName, @Param("email") String email, @Param("mobile") String mobile);
//
//
//}
package shrasthra.backend.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import shrasthra.backend.dao.domain.AppUser;
public interface JwtUserRepository extends JpaRepository<shrasthra.backend.dao.domain.AppUser, Integer>{
public AppUser findByUsername(String username);
}
package shrasthra.backend.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import shrasthra.backend.dao.domain.McqWord;
public interface McqWordRepository extends JpaRepository<McqWord, Integer>{
}
package shrasthra.backend.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import shrasthra.backend.dao.domain.SignMap;
public interface SignMapRepository extends JpaRepository<SignMap, Integer>{
@Query("SELECT s FROM SignMap s WHERE s.label=:label")
public SignMap findSignMapByLabel(@Param("label") String label);
}
package shrasthra.backend.service.i;
import org.springframework.web.multipart.MultipartFile;
import shrasthra.backend.dao.dto.ProcessRequestDto;
import shrasthra.backend.dao.dto.ProcessResponseDto;
public interface ShrasthraBackendService {
public ProcessResponseDto detectDynamicSign(MultipartFile file);
}
package shrasthra.backend.service.impl;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import shrasthra.backend.dao.domain.AppUser;
import shrasthra.backend.dao.dto.AppUserDto;
import shrasthra.backend.repository.JwtUserRepository;
@Service
public class JwtUserDetailsService implements UserDetailsService {
@Autowired
private JwtUserRepository jwtUserRepository;
@Autowired
private PasswordEncoder bcryptEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
AppUser user = jwtUserRepository.findByUsername(username);
// if ("javainuse".equals(username)) {
// return new User("javainuse", "$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6",
// new ArrayList<>());
// } else {
// throw new UsernameNotFoundException("User not found with username: " + username);
// }
if (user == null) {
throw new UsernameNotFoundException("User not found with username: " + username);
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
new ArrayList<>());
}
public AppUser save(AppUserDto user) {
AppUser newUser = new AppUser();
newUser.setUsername(user.getUsername());
newUser.setName(user.getName());
newUser.setUserRole(user.getUserRole());
newUser.setEmail(user.getEmail());
newUser.setPassword(bcryptEncoder.encode(user.getPassword()));
return jwtUserRepository.save(newUser);
}
public AppUserDto findUserByUsername(String username) {
AppUser user = jwtUserRepository.findByUsername(username);
AppUserDto userDto = new AppUserDto();
userDto.setUserId(user.getUserId());
userDto.setName(user.getName());
userDto.setUsername(user.getName());
userDto.setEmail(user.getEmail());
userDto.setUserRole(user.getUserRole());
// userDto.setPassword(user.getPassword());
return userDto;
}
}
\ No newline at end of file
package shrasthra.backend.service.impl;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import shrasthra.backend.dao.domain.SignMap;
import shrasthra.backend.dao.dto.ProcessRequestDto;
import shrasthra.backend.dao.dto.ProcessResponseDto;
import shrasthra.backend.repository.JwtUserRepository;
import shrasthra.backend.repository.SignMapRepository;
import shrasthra.backend.service.i.ShrasthraBackendService;
@Service
public class ShrasthraBackendServiceImpl implements ShrasthraBackendService{
private static final String Date = null;
@Autowired
private JwtUserRepository jwtUserRepository;
@Autowired
private SignMapRepository signMapRepository;
@Autowired
private PasswordEncoder bcryptEncoder;
public ProcessResponseDto detectDynamicSign(MultipartFile file) {
ProcessResponseDto responseDto = new ProcessResponseDto();
try {
if (!file.isEmpty()) {
// Convert the file to bytes
byte[] fileBytes = file.getBytes();
RestTemplate restTemplate = new RestTemplate();
// Set the URL of your Python Flask API
String url = "http://127.0.0.1:8050/api/data";
// Create headers and set content type as multipart/form-data
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// Create the request body with the file as a part
MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
requestBody.add("fileData", new ByteArrayResource(fileBytes) {
@Override
public String getFilename() {
return file.getOriginalFilename();
}
});
// Create the request entity with headers and body
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
// Make the POST request to the second API
ResponseEntity<ProcessResponseDto> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,
ProcessResponseDto.class);
// Retrieve the response body
ProcessResponseDto responseBody = response.getBody();
// Print the response
if(responseBody.getSign() != null) {
SignMap signMap = signMapRepository.findSignMapByLabel(responseBody.getSign());
if(signMap != null) {
responseDto.setSignMap(signMap);
responseDto.setSuccess(true);
}
}
}
} catch (Exception e) {
responseDto.setSuccess(false);
System.out.println("detectDynamicSign : " + e);
}
return responseDto;
}
}
package shrasthra.backend.util.common;
public class REST_CONTROLLER_URL {
public static final String USER_REGISTRATION = "/user/userRegistration";
public static final String DETECT_DYNAMIC_SIGN = "/sign/detectDynamicSign";
}
jwt.secret=javainuse
jwt.get.token.uri=/authenticate
spring.datasource.url = jdbc:mysql://localhost:3306/shrasthra?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false&useSSL=false
spring.jpa.database-platform = org.hibernate.dialect.MySQL8Dialect
#spring.datasource.url = jdbc:mysql://localhost:3306/ecare?useSSL=false
spring.datasource.username = root
spring.datasource.password = password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
server.servlet.context-path=/ShrasthraBackendService
server.port = 8885
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
\ No newline at end of file
//package sliit.ecarebackend;
//
//import static org.junit.Assert.assertNotNull;
//import static org.junit.Assert.assertThat;
//import static org.junit.jupiter.api.Assertions.assertEquals;
//
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//
//import org.junit.jupiter.api.Test;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.security.crypto.password.PasswordEncoder;
//
//
//import shrasthra.backend.repository.JwtUserRepository;
//import shrasthra.backend.repository.MaterialRepository;
//import shrasthra.backend.repository.ReceiptRepository;
//import shrasthra.backend.repository.SiteRepository;
//
//@SpringBootTest
//class ECareBackendApplicationTests {
//
//
// @Autowired
// MaterialRepository materialRepo;
//
// @Autowired
// ReceiptRepository receiptRepo;
//
// @Autowired
// SiteRepository siteRepo;
//
// @Autowired
// private JwtUserRepository jwtUserRepository;
//
// @Autowired
// private PasswordEncoder bcryptEncoder;
//
//
//
//
// @Test
// void contextLoads() {
// }
//
//
//
//
//}
package sliit.spm.ecare.backend;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ECareBackendApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment