├── .github
└── workflows
│ └── deploy.yml
├── .gitignore
├── frontend
├── .gitignore
├── .vscode
│ └── settings.json
├── README.md
├── package-lock.json
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
├── src
│ ├── api
│ │ └── apiCalls.js
│ ├── assets
│ │ ├── hoaxify.png
│ │ └── profile.png
│ ├── bootstrap-override.scss
│ ├── components
│ │ ├── AutoUploadImage.css
│ │ ├── AutoUploadImage.js
│ │ ├── ButtonWithProgress.js
│ │ ├── HoaxFeed.js
│ │ ├── HoaxSubmit.js
│ │ ├── HoaxView.js
│ │ ├── Input.js
│ │ ├── LanguageSelector.js
│ │ ├── Modal.js
│ │ ├── ProfileCard.js
│ │ ├── ProfileImageWithDefault.js
│ │ ├── Spinner.js
│ │ ├── TopBar.js
│ │ ├── UserList.js
│ │ └── UserListItem.js
│ ├── container
│ │ └── App.js
│ ├── i18n.js
│ ├── index.css
│ ├── index.js
│ ├── pages
│ │ ├── HomePage.js
│ │ ├── LoginPage.js
│ │ ├── UserPage.js
│ │ └── UserSignupPage.js
│ ├── redux
│ │ ├── Constants.js
│ │ ├── authActions.js
│ │ ├── authReducer.js
│ │ └── configureStore.js
│ ├── serviceWorker.js
│ ├── setupTests.js
│ └── shared
│ │ └── ApiProgress.js
└── yarn.lock
├── readme.md
└── ws
├── .gitignore
├── .mvn
└── wrapper
│ ├── MavenWrapperDownloader.java
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── hoaxify
│ │ └── ws
│ │ ├── WsApplication.java
│ │ ├── auth
│ │ ├── AuthController.java
│ │ ├── AuthException.java
│ │ ├── AuthResponse.java
│ │ ├── AuthService.java
│ │ ├── Credentials.java
│ │ ├── Token.java
│ │ └── TokenRepository.java
│ │ ├── configuration
│ │ ├── AppConfiguration.java
│ │ ├── AuthEntryPoint.java
│ │ ├── SecurityConfiguration.java
│ │ ├── TokenFilter.java
│ │ └── WebConfiguration.java
│ │ ├── error
│ │ ├── ApiError.java
│ │ ├── ErrorHandler.java
│ │ └── NotFoundException.java
│ │ ├── file
│ │ ├── FileAttachment.java
│ │ ├── FileAttachmentRepository.java
│ │ ├── FileController.java
│ │ ├── FileService.java
│ │ └── vm
│ │ │ └── FileAttachmentVM.java
│ │ ├── hoax
│ │ ├── Hoax.java
│ │ ├── HoaxController.java
│ │ ├── HoaxRepository.java
│ │ ├── HoaxSecurityService.java
│ │ ├── HoaxService.java
│ │ └── vm
│ │ │ ├── HoaxSubmitVM.java
│ │ │ └── HoaxVM.java
│ │ ├── shared
│ │ ├── CurrentUser.java
│ │ ├── FileType.java
│ │ ├── FileTypeValidator.java
│ │ └── GenericResponse.java
│ │ └── user
│ │ ├── UniqueUsername.java
│ │ ├── UniqueUsernameValidator.java
│ │ ├── User.java
│ │ ├── UserController.java
│ │ ├── UserRepository.java
│ │ ├── UserService.java
│ │ └── vm
│ │ ├── UserUpdateVM.java
│ │ └── UserVM.java
└── resources
│ ├── ValidationMessages.properties
│ ├── ValidationMessages_tr.properties
│ └── application.yaml
└── test
└── java
└── com
└── hoaxify
└── ws
└── WsApplicationTests.java
/.github/workflows/deploy.yml:
--------------------------------------------------------------------------------
1 | name: Hoaxify Deploy
2 |
3 | on:
4 | push:
5 | branches: [ master ]
6 |
7 | jobs:
8 | build:
9 |
10 | runs-on: ubuntu-latest
11 |
12 | steps:
13 | - uses: actions/checkout@v2
14 | - name: Use Node.js 12.x
15 | uses: actions/setup-node@v1
16 | with:
17 | node-version: 12.x
18 | - name: Setup Java JDK
19 | uses: actions/setup-java@v1.4.3
20 | with:
21 | # The Java version to make available on the path. Takes a whole or semver Java version, or 1.x syntax (e.g. 1.8 => Java 8.x). Early access versions can be specified in the form of e.g. 14-ea, 14.0.0-ea, or 14.0.0-ea.28
22 | java-version: 1.8
23 | - run: npm ci
24 | working-directory: ./frontend
25 | - run: npm run build --if-present
26 | working-directory: ./frontend
27 |
28 | - name: copy react to spring static resources
29 | run: |
30 | mkdir -p ws/src/main/resources/static
31 | cp -a frontend/build/. ws/src/main/resources/static/
32 |
33 | - name: Build spring
34 | run: mvn -B package --file pom.xml
35 | working-directory: ./ws
36 |
37 | - name: SFTP Deploy
38 | uses: wlixcc/SFTP-Deploy-Action@v1.0
39 | with:
40 | username: ${{secrets.USERNAME}}
41 | server: ${{secrets.IP}}
42 | ssh_private_key: ${{secrets.SSH}}
43 | local_path: ws/target/ws-0.0.1-SNAPSHOT.jar
44 | remote_path: /home/basarbk
45 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ws/picture-storage
2 | ws/storage-*
--------------------------------------------------------------------------------
/frontend/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/frontend/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "git.decorations.enabled": false,
3 | "scm.diffDecorations": "none",
4 | "files.exclude": {
5 | ".vscode": true,
6 | "node_modules": true,
7 | "package-lock.json": true,
8 | "yarn.lock": true,
9 | ".gitignore": true,
10 | "README.md": true,
11 | ".prettierrc": true
12 | },
13 | "editor.formatOnType": true,
14 | "breadcrumbs.filePath": "off",
15 | "breadcrumbs.symbolPath": "off",
16 | "breadcrumbs.enabled": false,
17 | "workbench.statusBar.visible": false,
18 | "editor.wordBasedSuggestions": false,
19 | "editor.suggest.snippetsPreventQuickSuggestions": false,
20 | "editor.suggest.filterGraceful": false,
21 | "editor.lineNumbers": "off",
22 | "problems.decorations.enabled": false,
23 | "workbench.activityBar.visible": false,
24 | "editor.formatOnPaste": true,
25 | "editor.formatOnSave": true,
26 | "zenMode.centerLayout": false,
27 | "editor.find.addExtraSpaceOnTop": false,
28 | "debug.showInlineBreakpointCandidates": false,
29 | "editor.glyphMargin": false
30 | }
31 |
--------------------------------------------------------------------------------
/frontend/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 |
7 | ### `yarn start`
8 |
9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11 |
12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console.
14 |
15 | ### `yarn test`
16 |
17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19 |
20 | ### `yarn build`
21 |
22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance.
24 |
25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed!
27 |
28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29 |
30 | ### `yarn eject`
31 |
32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33 |
34 | 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.
35 |
36 | 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.
37 |
38 | 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.
39 |
40 | ## Learn More
41 |
42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43 |
44 | To learn React, check out the [React documentation](https://reactjs.org/).
45 |
46 | ### Code Splitting
47 |
48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
49 |
50 | ### Analyzing the Bundle Size
51 |
52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
53 |
54 | ### Making a Progressive Web App
55 |
56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
57 |
58 | ### Advanced Configuration
59 |
60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
61 |
62 | ### Deployment
63 |
64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
65 |
66 | ### `yarn build` fails to minify
67 |
68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
69 |
--------------------------------------------------------------------------------
/frontend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "frontend",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^4.2.4",
7 | "@testing-library/react": "^9.3.2",
8 | "@testing-library/user-event": "^7.1.2",
9 | "axios": "^0.19.2",
10 | "bootstrap": "^4.4.1",
11 | "i18next": "^19.1.0",
12 | "node-sass": "^4.13.1",
13 | "react": "^16.12.0",
14 | "react-dom": "^16.12.0",
15 | "react-i18next": "^11.3.2",
16 | "react-redux": "^7.2.0",
17 | "react-router-dom": "^5.1.2",
18 | "react-scripts": "3.4.0",
19 | "redux": "^4.0.5",
20 | "redux-thunk": "^2.3.0",
21 | "secure-ls": "^1.2.6",
22 | "timeago.js": "^4.0.2"
23 | },
24 | "scripts": {
25 | "start": "react-scripts start",
26 | "build": "react-scripts build",
27 | "test": "react-scripts test",
28 | "eject": "react-scripts eject"
29 | },
30 | "eslintConfig": {
31 | "extends": "react-app"
32 | },
33 | "browserslist": {
34 | "production": [
35 | ">0.2%",
36 | "not dead",
37 | "not op_mini all"
38 | ],
39 | "development": [
40 | "last 1 chrome version",
41 | "last 1 firefox version",
42 | "last 1 safari version"
43 | ]
44 | },
45 | "proxy": "http://localhost:8080"
46 | }
47 |
--------------------------------------------------------------------------------
/frontend/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/basarbk/spring-react-tr-course/f1004a8314d41498d1a7321ca3f83faab44ab91c/frontend/public/favicon.ico
--------------------------------------------------------------------------------
/frontend/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
14 |
15 |
24 |
25 | React App
26 |
27 |
28 |
29 |
30 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/frontend/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/basarbk/spring-react-tr-course/f1004a8314d41498d1a7321ca3f83faab44ab91c/frontend/public/logo192.png
--------------------------------------------------------------------------------
/frontend/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/basarbk/spring-react-tr-course/f1004a8314d41498d1a7321ca3f83faab44ab91c/frontend/public/logo512.png
--------------------------------------------------------------------------------
/frontend/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/frontend/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/frontend/src/api/apiCalls.js:
--------------------------------------------------------------------------------
1 | import axios from 'axios';
2 |
3 | export const signup = body => {
4 | return axios.post('/api/1.0/users', body);
5 | };
6 |
7 | export const login = creds => {
8 | return axios.post('/api/1.0/auth', creds);
9 | };
10 |
11 | export const logout = () => {
12 | return axios.post('/api/1.0/logout');
13 | }
14 |
15 | export const changeLanguage = language => {
16 | axios.defaults.headers['accept-language'] = language;
17 | };
18 |
19 | export const getUsers = (page = 0, size = 3) => {
20 | return axios.get(`/api/1.0/users?page=${page}&size=${size}`);
21 | };
22 |
23 | export const setAuthorizationHeader = ({ isLoggedIn, token }) => {
24 | if (isLoggedIn) {
25 | const authorizationHeaderValue = `Bearer ${token}`;
26 | axios.defaults.headers['Authorization'] = authorizationHeaderValue;
27 | } else {
28 | delete axios.defaults.headers['Authorization'];
29 | }
30 | };
31 |
32 | export const getUser = username => {
33 | return axios.get(`/api/1.0/users/${username}`);
34 | };
35 |
36 | export const updateUser = (username, body) => {
37 | return axios.put(`/api/1.0/users/${username}`, body);
38 | };
39 |
40 | export const postHoax = hoax => {
41 | return axios.post('/api/1.0/hoaxes', hoax);
42 | };
43 |
44 | export const getHoaxes = (username, page = 0) => {
45 | const path = username ? `/api/1.0/users/${username}/hoaxes?page=` : '/api/1.0/hoaxes?page=';
46 | return axios.get(path + page);
47 | };
48 |
49 | export const getOldHoaxes = (id, username) => {
50 | const path = username ? `/api/1.0/users/${username}/hoaxes/${id}` : `/api/1.0/hoaxes/${id}`;
51 | return axios.get(path);
52 | };
53 |
54 | export const getNewHoaxCount = (id, username) => {
55 | const path = username ? `/api/1.0/users/${username}/hoaxes/${id}?count=true` : `/api/1.0/hoaxes/${id}?count=true`;
56 | return axios.get(path);
57 | };
58 |
59 | export const getNewHoaxes = (id, username) => {
60 | const path = username ? `/api/1.0/users/${username}/hoaxes/${id}?direction=after` : `/api/1.0/hoaxes/${id}?direction=after`;
61 | return axios.get(path);
62 | };
63 |
64 | export const postHoaxAttachment = attachment => {
65 | return axios.post('/api/1.0/hoax-attachments', attachment);
66 | };
67 |
68 | export const deleteHoax = id => {
69 | return axios.delete(`/api/1.0/hoaxes/${id}`);
70 | };
71 |
72 | export const deleteUser = username => {
73 | return axios.delete(`/api/1.0/users/${username}`);
74 | };
75 |
--------------------------------------------------------------------------------
/frontend/src/assets/hoaxify.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/basarbk/spring-react-tr-course/f1004a8314d41498d1a7321ca3f83faab44ab91c/frontend/src/assets/hoaxify.png
--------------------------------------------------------------------------------
/frontend/src/assets/profile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/basarbk/spring-react-tr-course/f1004a8314d41498d1a7321ca3f83faab44ab91c/frontend/src/assets/profile.png
--------------------------------------------------------------------------------
/frontend/src/bootstrap-override.scss:
--------------------------------------------------------------------------------
1 | $primary: #818;
2 |
3 | @import '~bootstrap/scss/bootstrap.scss';
4 |
5 | .btn-delete-link {
6 | color: $gray-400;
7 | padding: 0;
8 | }
9 |
10 | .btn-delete-link:hover {
11 | color: $danger;
12 | }
13 |
--------------------------------------------------------------------------------
/frontend/src/components/AutoUploadImage.css:
--------------------------------------------------------------------------------
1 | .overlay {
2 | position: absolute;
3 | top: 0;
4 | bottom: 0;
5 | left: 0;
6 | right: 0;
7 | height: 100%;
8 | width: 100%;
9 | opacity: 0;
10 | transition: 0.5s ease;
11 | background-color: #00000099;
12 | }
13 |
--------------------------------------------------------------------------------
/frontend/src/components/AutoUploadImage.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import './AutoUploadImage.css';
3 |
4 | const AutoUploadImage = ({ image, uploading }) => {
5 | return (
6 |
7 |

8 |
9 |
10 |
11 | Loading...
12 |
13 |
14 |
15 |
16 | );
17 | };
18 |
19 | export default AutoUploadImage;
20 |
--------------------------------------------------------------------------------
/frontend/src/components/ButtonWithProgress.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | const ButtonWithProgress = props => {
4 | const { onClick, pendingApiCall, disabled, text, className } = props;
5 |
6 | return (
7 |
10 | );
11 | };
12 |
13 | export default ButtonWithProgress;
14 |
--------------------------------------------------------------------------------
/frontend/src/components/HoaxFeed.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import { getHoaxes, getOldHoaxes, getNewHoaxCount, getNewHoaxes } from '../api/apiCalls';
3 | import { useTranslation } from 'react-i18next';
4 | import HoaxView from './HoaxView';
5 | import { useApiProgress } from '../shared/ApiProgress';
6 | import Spinner from './Spinner';
7 | import { useParams } from 'react-router-dom';
8 |
9 | const HoaxFeed = () => {
10 | const [hoaxPage, setHoaxPage] = useState({ content: [], last: true, number: 0 });
11 | const [newHoaxCount, setNewHoaxCount] = useState(0);
12 | const { t } = useTranslation();
13 | const { username } = useParams();
14 |
15 | const path = username ? `/api/1.0/users/${username}/hoaxes?page=` : '/api/1.0/hoaxes?page=';
16 | const initialHoaxLoadProgress = useApiProgress('get', path);
17 |
18 | let lastHoaxId = 0;
19 | let firstHoaxId = 0;
20 | if (hoaxPage.content.length > 0) {
21 | firstHoaxId = hoaxPage.content[0].id;
22 |
23 | const lastHoaxIndex = hoaxPage.content.length - 1;
24 | lastHoaxId = hoaxPage.content[lastHoaxIndex].id;
25 | }
26 | const oldHoaxPath = username ? `/api/1.0/users/${username}/hoaxes/${lastHoaxId}` : `/api/1.0/hoaxes/${lastHoaxId}`;
27 | const loadOldHoaxesProgress = useApiProgress('get', oldHoaxPath, true);
28 |
29 | const newHoaxPath = username
30 | ? `/api/1.0/users/${username}/hoaxes/${firstHoaxId}?direction=after`
31 | : `/api/1.0/hoaxes/${firstHoaxId}?direction=after`;
32 |
33 | const loadNewHoaxesProgress = useApiProgress('get', newHoaxPath, true);
34 |
35 | useEffect(() => {
36 | const getCount = async () => {
37 | const response = await getNewHoaxCount(firstHoaxId, username);
38 | setNewHoaxCount(response.data.count);
39 | };
40 | let looper = setInterval(getCount, 5000);
41 | return function cleanup() {
42 | clearInterval(looper);
43 | };
44 | }, [firstHoaxId, username]);
45 |
46 | useEffect(() => {
47 | const loadHoaxes = async page => {
48 | try {
49 | const response = await getHoaxes(username, page);
50 | setHoaxPage(previousHoaxPage => ({
51 | ...response.data,
52 | content: [...previousHoaxPage.content, ...response.data.content]
53 | }));
54 | } catch (error) {}
55 | };
56 | loadHoaxes();
57 | }, [username]);
58 |
59 | const loadOldHoaxes = async () => {
60 | const response = await getOldHoaxes(lastHoaxId, username);
61 | setHoaxPage(previousHoaxPage => ({
62 | ...response.data,
63 | content: [...previousHoaxPage.content, ...response.data.content]
64 | }));
65 | };
66 |
67 | const loadNewHoaxes = async () => {
68 | const response = await getNewHoaxes(firstHoaxId, username);
69 | setHoaxPage(previousHoaxPage => ({
70 | ...previousHoaxPage,
71 | content: [...response.data, ...previousHoaxPage.content]
72 | }));
73 | setNewHoaxCount(0);
74 | };
75 |
76 | const onDeleteHoaxSuccess = id => {
77 | setHoaxPage(previousHoaxPage => ({
78 | ...previousHoaxPage,
79 | content: previousHoaxPage.content.filter(hoax => hoax.id !== id)
80 | }));
81 | };
82 |
83 | const { content, last } = hoaxPage;
84 |
85 | if (content.length === 0) {
86 | return {initialHoaxLoadProgress ? : t('There are no hoaxes')}
;
87 | }
88 |
89 | return (
90 |
91 | {newHoaxCount > 0 && (
92 |
{} : loadNewHoaxes}
96 | >
97 | {loadNewHoaxesProgress ? : t('There are new hoaxes')}
98 |
99 | )}
100 | {content.map(hoax => {
101 | return
;
102 | })}
103 | {!last && (
104 |
{} : loadOldHoaxes}
108 | >
109 | {loadOldHoaxesProgress ? : t('Load old hoaxes')}
110 |
111 | )}
112 |
113 | );
114 | };
115 |
116 | export default HoaxFeed;
117 |
--------------------------------------------------------------------------------
/frontend/src/components/HoaxSubmit.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import { useSelector } from 'react-redux';
3 | import ProfileImageWithDefault from './ProfileImageWithDefault';
4 | import { useTranslation } from 'react-i18next';
5 | import { postHoax, postHoaxAttachment } from '../api/apiCalls';
6 | import { useApiProgress } from '../shared/ApiProgress';
7 | import ButtonWithProgress from './ButtonWithProgress';
8 | import Input from './Input';
9 | import AutoUploadImage from './AutoUploadImage';
10 |
11 | const HoaxSubmit = () => {
12 | const { image } = useSelector(store => ({ image: store.image }));
13 | const [focused, setFocused] = useState(false);
14 | const [hoax, setHoax] = useState('');
15 | const [errors, setErrors] = useState({});
16 | const [newImage, setNewImage] = useState();
17 | const [attachmentId, setAttachmentId] = useState();
18 | const { t } = useTranslation();
19 |
20 | useEffect(() => {
21 | if (!focused) {
22 | setHoax('');
23 | setErrors({});
24 | setNewImage();
25 | setAttachmentId();
26 | }
27 | }, [focused]);
28 |
29 | useEffect(() => {
30 | setErrors({});
31 | }, [hoax]);
32 |
33 | const pendingApiCall = useApiProgress('post', '/api/1.0/hoaxes', true);
34 | const pendingFileUpload = useApiProgress('post', '/api/1.0/hoax-attachments', true);
35 |
36 | const onClickHoaxify = async () => {
37 | const body = {
38 | content: hoax,
39 | attachmentId: attachmentId
40 | };
41 |
42 | try {
43 | await postHoax(body);
44 | setFocused(false);
45 | } catch (error) {
46 | if (error.response.data.validationErrors) {
47 | setErrors(error.response.data.validationErrors);
48 | }
49 | }
50 | };
51 |
52 | const onChangeFile = event => {
53 | if (event.target.files.length < 1) {
54 | return;
55 | }
56 | const file = event.target.files[0];
57 | const fileReader = new FileReader();
58 | fileReader.onloadend = () => {
59 | setNewImage(fileReader.result);
60 | uploadFile(file);
61 | };
62 | fileReader.readAsDataURL(file);
63 | };
64 |
65 | const uploadFile = async file => {
66 | const attachment = new FormData();
67 | attachment.append('file', file);
68 | const response = await postHoaxAttachment(attachment);
69 | setAttachmentId(response.data.id);
70 | };
71 |
72 | let textAreaClass = 'form-control';
73 | if (errors.content) {
74 | textAreaClass += ' is-invalid';
75 | }
76 |
77 | return (
78 |
110 | );
111 | };
112 |
113 | export default HoaxSubmit;
114 |
--------------------------------------------------------------------------------
/frontend/src/components/HoaxView.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import ProfileImageWithDefault from './ProfileImageWithDefault';
3 | import { Link } from 'react-router-dom';
4 | import { format } from 'timeago.js';
5 | import { useTranslation } from 'react-i18next';
6 | import { useSelector } from 'react-redux';
7 | import { deleteHoax } from '../api/apiCalls';
8 | import Modal from './Modal';
9 | import { useApiProgress } from '../shared/ApiProgress';
10 |
11 | const HoaxView = props => {
12 | const loggedInUser = useSelector(store => store.username);
13 | const { hoax, onDeleteHoax } = props;
14 | const { user, content, timestamp, fileAttachment, id } = hoax;
15 | const { username, displayName, image } = user;
16 | const [modalVisible, setModalVisible] = useState(false);
17 |
18 | const pendingApiCall = useApiProgress('delete', `/api/1.0/hoaxes/${id}`, true);
19 |
20 | const { t, i18n } = useTranslation();
21 |
22 | const onClickDelete = async () => {
23 | await deleteHoax(id);
24 | onDeleteHoax(id);
25 | };
26 |
27 | const onClickCancel = () => {
28 | setModalVisible(false);
29 | };
30 |
31 | const formatted = format(timestamp, i18n.language);
32 |
33 | const ownedByLoggedInUser = loggedInUser === username;
34 |
35 | return (
36 | <>
37 |
38 |
39 |
40 |
41 |
42 |
43 | {displayName}@{username}
44 |
45 | -
46 | {formatted}
47 |
48 |
49 | {ownedByLoggedInUser && (
50 |
53 | )}
54 |
55 |
{content}
56 | {fileAttachment && (
57 |
58 | {fileAttachment.fileType.startsWith('image') && (
59 |

60 | )}
61 | {!fileAttachment.fileType.startsWith('image') &&
Hoax has unknown attachment}
62 |
63 | )}
64 |
65 |
72 |
73 | {t('Are you sure to delete hoax?')}
74 |
75 | {content}
76 |
77 | }
78 | pendingApiCall={pendingApiCall}
79 | okButton={t('Delete Hoax')}
80 | />
81 | >
82 | );
83 | };
84 |
85 | export default HoaxView;
86 |
--------------------------------------------------------------------------------
/frontend/src/components/Input.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | const Input = props => {
4 | const { label, error, name, onChange, type, defaultValue } = props;
5 | let className = 'form-control';
6 |
7 | if (type === 'file') {
8 | className += '-file';
9 | }
10 |
11 | if (error !== undefined) {
12 | className += ' is-invalid';
13 | }
14 |
15 | return (
16 |
17 |
18 |
19 |
{props.error}
20 |
21 | );
22 | };
23 |
24 | export default Input;
25 |
--------------------------------------------------------------------------------
/frontend/src/components/LanguageSelector.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { useTranslation } from 'react-i18next';
3 | import { changeLanguage } from '../api/apiCalls';
4 |
5 | const LanguageSelector = props => {
6 | const { i18n } = useTranslation();
7 |
8 | const onChangeLanguage = language => {
9 | i18n.changeLanguage(language);
10 | changeLanguage(language);
11 | };
12 |
13 | return (
14 |
15 |

onChangeLanguage('tr')}
19 | style={{ cursor: 'pointer' }}
20 | >
21 |

onChangeLanguage('en')} style={{ cursor: 'pointer' }}>
22 |
23 | );
24 | };
25 |
26 | export default LanguageSelector;
27 |
--------------------------------------------------------------------------------
/frontend/src/components/Modal.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { useTranslation } from 'react-i18next';
3 | import ButtonWithProgress from './ButtonWithProgress';
4 |
5 | const Modal = props => {
6 | const { visible, onClickCancel, message, onClickOk, pendingApiCall, title, okButton } = props;
7 | const { t } = useTranslation();
8 |
9 | let className = 'modal fade';
10 | if (visible) {
11 | className += ' show d-block';
12 | }
13 |
14 | return (
15 |
16 |
17 |
18 |
19 |
{title}
20 |
21 |
{message}
22 |
23 |
26 |
33 |
34 |
35 |
36 |
37 | );
38 | };
39 |
40 | export default Modal;
41 |
--------------------------------------------------------------------------------
/frontend/src/components/ProfileCard.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import { useParams, useHistory } from 'react-router-dom';
3 | import { useSelector, useDispatch } from 'react-redux';
4 | import ProfileImageWithDefault from './ProfileImageWithDefault';
5 | import { useTranslation } from 'react-i18next';
6 | import Input from './Input';
7 | import { updateUser, deleteUser } from '../api/apiCalls';
8 | import { useApiProgress } from '../shared/ApiProgress';
9 | import ButtonWithProgress from './ButtonWithProgress';
10 | import { updateSuccess, logoutSuccess } from '../redux/authActions';
11 | import Modal from './Modal';
12 |
13 | const ProfileCard = props => {
14 | const [inEditMode, setInEditMode] = useState(false);
15 | const [updatedDisplayName, setUpdatedDisplayName] = useState();
16 | const { username: loggedInUsername } = useSelector(store => ({ username: store.username }));
17 | const routeParams = useParams();
18 | const pathUsername = routeParams.username;
19 | const [user, setUser] = useState({});
20 | const [editable, setEditable] = useState(false);
21 | const [newImage, setNewImage] = useState();
22 | const [validationErrors, setValidationErrors] = useState({});
23 | const [modalVisible, setModalVisible] = useState(false);
24 | const dispatch = useDispatch();
25 | const history = useHistory();
26 |
27 | useEffect(() => {
28 | setUser(props.user);
29 | }, [props.user]);
30 |
31 | useEffect(() => {
32 | setEditable(pathUsername === loggedInUsername);
33 | }, [pathUsername, loggedInUsername]);
34 |
35 | useEffect(() => {
36 | setValidationErrors(previousValidationErrors => ({
37 | ...previousValidationErrors,
38 | displayName: undefined
39 | }));
40 | }, [updatedDisplayName]);
41 |
42 | useEffect(() => {
43 | setValidationErrors(previousValidationErrors => ({
44 | ...previousValidationErrors,
45 | image: undefined
46 | }));
47 | }, [newImage]);
48 |
49 | const { username, displayName, image } = user;
50 |
51 | const pendingApiCallDeleteUser = useApiProgress('delete', `/api/1.0/users/${username}`, true);
52 |
53 | const { t } = useTranslation();
54 |
55 | useEffect(() => {
56 | if (!inEditMode) {
57 | setUpdatedDisplayName(undefined);
58 | setNewImage(undefined);
59 | } else {
60 | setUpdatedDisplayName(displayName);
61 | }
62 | }, [inEditMode, displayName]);
63 |
64 | const onClickSave = async () => {
65 | let image;
66 | if (newImage) {
67 | image = newImage.split(',')[1];
68 | }
69 |
70 | const body = {
71 | displayName: updatedDisplayName,
72 | image
73 | };
74 | try {
75 | const response = await updateUser(username, body);
76 | setInEditMode(false);
77 | setUser(response.data);
78 | dispatch(updateSuccess(response.data));
79 | } catch (error) {
80 | setValidationErrors(error.response.data.validationErrors);
81 | }
82 | };
83 |
84 | const onChangeFile = event => {
85 | if (event.target.files.length < 1) {
86 | return;
87 | }
88 | const file = event.target.files[0];
89 | const fileReader = new FileReader();
90 | fileReader.onloadend = () => {
91 | setNewImage(fileReader.result);
92 | };
93 | fileReader.readAsDataURL(file);
94 | };
95 |
96 | const onClickCancel = () => {
97 | setModalVisible(false);
98 | };
99 |
100 | const onClickDeleteUser = async () => {
101 | await deleteUser(username);
102 | setModalVisible(false);
103 | dispatch(logoutSuccess());
104 | history.push('/');
105 | };
106 | const pendingApiCall = useApiProgress('put', '/api/1.0/users/' + username);
107 |
108 | const { displayName: displayNameError, image: imageError } = validationErrors;
109 |
110 | return (
111 |
112 |
122 |
123 | {!inEditMode && (
124 | <>
125 |
126 | {displayName}@{username}
127 |
128 | {editable && (
129 | <>
130 |
134 |
135 |
139 |
140 | >
141 | )}
142 | >
143 | )}
144 | {inEditMode && (
145 |
174 | )}
175 |
176 |
185 |
186 | );
187 | };
188 |
189 | export default ProfileCard;
190 |
--------------------------------------------------------------------------------
/frontend/src/components/ProfileImageWithDefault.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import defaultPicture from '../assets/profile.png';
3 |
4 | const ProfileImageWithDefault = props => {
5 | const { image, tempimage } = props;
6 |
7 | let imageSource = defaultPicture;
8 | if (image) {
9 | imageSource = 'images/profile/' + image;
10 | }
11 | return (
12 |
{
17 | event.target.src = defaultPicture;
18 | }}
19 | />
20 | );
21 | };
22 |
23 | export default ProfileImageWithDefault;
24 |
--------------------------------------------------------------------------------
/frontend/src/components/Spinner.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | const Spinner = () => {
4 | return (
5 |
6 |
7 | Loading...
8 |
9 |
10 | );
11 | };
12 |
13 | export default Spinner;
14 |
--------------------------------------------------------------------------------
/frontend/src/components/TopBar.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect, useRef } from 'react';
2 | import logo from '../assets/hoaxify.png';
3 | import { Link } from 'react-router-dom';
4 | import { useTranslation } from 'react-i18next';
5 | import { useDispatch, useSelector } from 'react-redux';
6 | import { logoutSuccess } from '../redux/authActions';
7 | import ProfileImageWithDefault from './ProfileImageWithDefault';
8 |
9 | const TopBar = props => {
10 | const { t } = useTranslation();
11 |
12 | const { username, isLoggedIn, displayName, image } = useSelector(store => ({
13 | isLoggedIn: store.isLoggedIn,
14 | username: store.username,
15 | displayName: store.displayName,
16 | image: store.image
17 | }));
18 |
19 | const menuArea = useRef(null);
20 |
21 | const [menuVisible, setMenuVisible] = useState(false);
22 |
23 | useEffect(() => {
24 | document.addEventListener('click', menuClickTracker);
25 | return () => {
26 | document.removeEventListener('click', menuClickTracker);
27 | };
28 | }, [isLoggedIn]);
29 |
30 | const menuClickTracker = event => {
31 | if (menuArea.current === null || !menuArea.current.contains(event.target)) {
32 | setMenuVisible(false);
33 | }
34 | };
35 |
36 | const dispatch = useDispatch();
37 |
38 | const onLogoutSuccess = () => {
39 | dispatch(logoutSuccess());
40 | };
41 |
42 | let links = (
43 |
44 | -
45 |
46 | {t('Login')}
47 |
48 |
49 | -
50 |
51 | {t('Sign Up')}
52 |
53 |
54 |
55 | );
56 | if (isLoggedIn) {
57 | let dropDownClass = 'dropdown-menu p-0 shadow';
58 | if (menuVisible) {
59 | dropDownClass += ' show';
60 | }
61 |
62 | links = (
63 |
81 | );
82 | }
83 |
84 | return (
85 |
86 |
93 |
94 | );
95 | };
96 |
97 | export default TopBar;
98 |
--------------------------------------------------------------------------------
/frontend/src/components/UserList.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import { getUsers } from '../api/apiCalls';
3 | import { useTranslation } from 'react-i18next';
4 | import UserListItem from './UserListItem';
5 | import { useApiProgress } from '../shared/ApiProgress';
6 | import Spinner from './Spinner';
7 |
8 | const UserList = () => {
9 | const [page, setPage] = useState({
10 | content: [],
11 | size: 3,
12 | number: 0
13 | });
14 |
15 | const [loadFailure, setLoadFailure] = useState(false);
16 |
17 | const pendingApiCall = useApiProgress('get', '/api/1.0/users?page');
18 |
19 | useEffect(() => {
20 | loadUsers();
21 | }, []);
22 |
23 | const onClickNext = () => {
24 | const nextPage = page.number + 1;
25 | loadUsers(nextPage);
26 | };
27 |
28 | const onClickPrevious = () => {
29 | const previousPage = page.number - 1;
30 | loadUsers(previousPage);
31 | };
32 |
33 | const loadUsers = async page => {
34 | setLoadFailure(false);
35 | try {
36 | const response = await getUsers(page);
37 | setPage(response.data);
38 | } catch (error) {
39 | setLoadFailure(true);
40 | }
41 | };
42 |
43 | const { t } = useTranslation();
44 | const { content: users, last, first } = page;
45 |
46 | let actionDiv = (
47 |
48 | {first === false && (
49 |
52 | )}
53 | {last === false && (
54 |
57 | )}
58 |
59 | );
60 |
61 | if (pendingApiCall) {
62 | actionDiv = ;
63 | }
64 |
65 | return (
66 |
67 |
{t('Users')}
68 |
69 | {users.map(user => (
70 |
71 | ))}
72 |
73 | {actionDiv}
74 | {loadFailure &&
{t('Load Failure')}
}
75 |
76 | );
77 | };
78 |
79 | export default UserList;
80 |
--------------------------------------------------------------------------------
/frontend/src/components/UserListItem.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Link } from 'react-router-dom';
3 | import ProfileImageWithDefault from './ProfileImageWithDefault';
4 |
5 | const UserListItem = props => {
6 | const { user } = props;
7 | const { username, displayName, image } = user;
8 |
9 | return (
10 |
11 |
12 |
13 | {displayName}@{username}
14 |
15 |
16 | );
17 | };
18 |
19 | export default UserListItem;
20 |
--------------------------------------------------------------------------------
/frontend/src/container/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import UserSignupPage from '../pages/UserSignupPage';
3 | import LoginPage from '../pages/LoginPage';
4 | import LanguageSelector from '../components/LanguageSelector';
5 | import HomePage from '../pages/HomePage';
6 | import UserPage from '../pages/UserPage';
7 | import { HashRouter as Router, Route, Redirect, Switch } from 'react-router-dom';
8 | import TopBar from '../components/TopBar';
9 | import { useSelector } from 'react-redux';
10 |
11 | const App = () => {
12 | const { isLoggedIn } = useSelector(store => ({
13 | isLoggedIn: store.isLoggedIn
14 | }));
15 |
16 | return (
17 |
18 |
19 |
20 |
21 |
22 | {!isLoggedIn && }
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | );
31 | };
32 |
33 | export default App;
34 |
--------------------------------------------------------------------------------
/frontend/src/i18n.js:
--------------------------------------------------------------------------------
1 | import i18n from 'i18next';
2 | import { initReactI18next } from 'react-i18next';
3 | import { register } from 'timeago.js';
4 |
5 | i18n.use(initReactI18next).init({
6 | resources: {
7 | en: {
8 | translations: {
9 | 'Sign Up': 'Sign Up',
10 | 'Password mismatch': 'Password mismatch',
11 | Username: 'Username',
12 | 'Display Name': 'Display Name',
13 | Password: 'Password',
14 | 'Password Repeat': 'Password Repeat',
15 | Login: 'Login',
16 | Logout: 'Logout',
17 | Users: 'Users',
18 | Next: 'next >',
19 | Previous: '< previous',
20 | 'Load Failure': 'Load Failure',
21 | 'User not found': 'User not found',
22 | Edit: 'Edit',
23 | 'Change Display Name': 'Change Display Name',
24 | Save: 'Save',
25 | Cancel: 'Cancel',
26 | 'My Profile': 'My Profile',
27 | 'There are no hoaxes': 'There are no hoaxes',
28 | 'Load old hoaxes': 'Load old hoaxes',
29 | 'There are new hoaxes': 'There are new hoaxes',
30 | 'Delete Hoax': 'Delete Hoax',
31 | 'Are you sure to delete hoax?': 'Are you sure to delete hoax?',
32 | 'Delete My Account': 'Delete My Account',
33 | 'Are you sure to delete your account?': 'Are you sure to delete your account?'
34 | }
35 | },
36 | tr: {
37 | translations: {
38 | 'Sign Up': 'Kayıt Ol',
39 | 'Password mismatch': 'Aynı şifreyi giriniz',
40 | Username: 'Kullanıcı Adı',
41 | 'Display Name': 'Tercih Edilen İsim',
42 | Password: 'Şifre',
43 | 'Password Repeat': 'Şifreyi Tekrarla',
44 | Login: 'Sisteme Gir',
45 | Logout: 'Çık',
46 | Users: 'Kullanıcılar',
47 | Next: 'sonraki >',
48 | Previous: '< önceki',
49 | 'Load Failure': 'Liste alınamadı',
50 | 'User not found': 'Kullanıcı bulunamadı',
51 | Edit: 'Düzenle',
52 | 'Change Display Name': 'Görünür İsminizi Değiştirin',
53 | Save: 'Kaydet',
54 | Cancel: 'İptal Et',
55 | 'My Profile': 'Hesabım',
56 | 'There are no hoaxes': 'Hoax bulunamadı',
57 | 'Load old hoaxes': 'Geçmiş Hoaxları getir',
58 | 'There are new hoaxes': 'Yeni Hoaxlar var',
59 | 'Delete Hoax': `Hoax'u sil`,
60 | 'Are you sure to delete hoax?': `Hoax'u silmek istedğinizden emin misiniz?`,
61 | 'Delete My Account': 'Hesabımı Sil',
62 | 'Are you sure to delete your account?': 'Hesabınızı silmek istediğinizden emin misiniz?'
63 | }
64 | }
65 | },
66 | fallbackLng: 'en',
67 | ns: ['translations'],
68 | defaultNS: 'translations',
69 | keySeparator: false,
70 | interpolation: {
71 | escapeValue: false,
72 | formatSeparator: ','
73 | },
74 | react: {
75 | wait: true
76 | }
77 | });
78 |
79 | const timeageTR = (number, index) => {
80 | return [
81 | ['az önce', 'şimdi'],
82 | ['%s saniye önce', '%s saniye içinde'],
83 | ['1 dakika önce', '1 dakika içinde'],
84 | ['%s dakika önce', '%s dakika içinde'],
85 | ['1 saat önce', '1 saat içinde'],
86 | ['%s saat önce', '%s saat içinde'],
87 | ['1 gün önce', '1 gün içinde'],
88 | ['%s gün önce', '%s gün içinde'],
89 | ['1 hafta önce', '1 hafta içinde'],
90 | ['%s hafta önce', '%s hafta içinde'],
91 | ['1 ay önce', '1 ay içinde'],
92 | ['%s ay önce', '%s ay içinde'],
93 | ['1 yıl önce', '1 yıl içinde'],
94 | ['%s yıl önce', '%s yıl içinde']
95 | ][index];
96 | };
97 | register('tr', timeageTR);
98 |
99 | export default i18n;
100 |
--------------------------------------------------------------------------------
/frontend/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/frontend/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import './bootstrap-override.scss';
5 | import * as serviceWorker from './serviceWorker';
6 | import './i18n';
7 | import App from './container/App';
8 | import { Provider } from 'react-redux';
9 | import configureStore from './redux/configureStore';
10 |
11 | const store = configureStore();
12 |
13 | ReactDOM.render(
14 |
15 |
16 | ,
17 | document.getElementById('root')
18 | );
19 |
20 | // If you want your app to work offline and load faster, you can change
21 | // unregister() to register() below. Note this comes with some pitfalls.
22 | // Learn more about service workers: https://bit.ly/CRA-PWA
23 | serviceWorker.unregister();
24 |
--------------------------------------------------------------------------------
/frontend/src/pages/HomePage.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import UserList from '../components/UserList';
3 | import HoaxSubmit from '../components/HoaxSubmit';
4 | import { useSelector } from 'react-redux';
5 | import HoaxFeed from '../components/HoaxFeed';
6 |
7 | const HomePage = () => {
8 | const { isLoggedIn } = useSelector(store => ({ isLoggedIn: store.isLoggedIn }));
9 | return (
10 |
11 |
12 |
13 | {isLoggedIn && (
14 |
15 |
16 |
17 | )}
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | );
26 | };
27 |
28 | export default HomePage;
29 |
--------------------------------------------------------------------------------
/frontend/src/pages/LoginPage.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import Input from '../components/Input';
3 | import { useTranslation } from 'react-i18next';
4 | import ButtonWithProgress from '../components/ButtonWithProgress';
5 | import { useApiProgress } from '../shared/ApiProgress';
6 | import { useDispatch } from 'react-redux';
7 | import { loginHandler } from '../redux/authActions';
8 |
9 | const LoginPage = props => {
10 | const [username, setUsername] = useState();
11 | const [password, setPassword] = useState();
12 | const [error, setError] = useState();
13 |
14 | const dispatch = useDispatch();
15 |
16 | useEffect(() => {
17 | setError(undefined);
18 | }, [username, password]);
19 |
20 | const onClickLogin = async event => {
21 | event.preventDefault();
22 | const creds = {
23 | username,
24 | password
25 | };
26 |
27 | const { history } = props;
28 | const { push } = history;
29 |
30 | setError(undefined);
31 | try {
32 | await dispatch(loginHandler(creds));
33 | push('/');
34 | } catch (apiError) {
35 | setError(apiError.response.data.message);
36 | }
37 | };
38 |
39 | const { t } = useTranslation();
40 |
41 | const pendingApiCall = useApiProgress('post', '/api/1.0/auth');
42 |
43 | const buttonEnabled = username && password;
44 |
45 | return (
46 |
57 | );
58 | };
59 |
60 | export default LoginPage;
61 |
--------------------------------------------------------------------------------
/frontend/src/pages/UserPage.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import ProfileCard from '../components/ProfileCard';
3 | import { getUser } from '../api/apiCalls';
4 | import { useParams } from 'react-router-dom';
5 | import { useTranslation } from 'react-i18next';
6 | import { useApiProgress } from '../shared/ApiProgress';
7 | import Spinner from '../components/Spinner';
8 | import HoaxFeed from '../components/HoaxFeed';
9 |
10 | const UserPage = () => {
11 | const [user, setUser] = useState({});
12 | const [notFound, setNotFound] = useState(false);
13 |
14 | const { username } = useParams();
15 |
16 | const { t } = useTranslation();
17 |
18 | const pendingApiCall = useApiProgress('get', '/api/1.0/users/' + username, true);
19 |
20 | useEffect(() => {
21 | setNotFound(false);
22 | }, [user]);
23 |
24 | useEffect(() => {
25 | const loadUser = async () => {
26 | try {
27 | const response = await getUser(username);
28 | setUser(response.data);
29 | } catch (error) {
30 | setNotFound(true);
31 | }
32 | };
33 | loadUser();
34 | }, [username]);
35 |
36 | if (notFound) {
37 | return (
38 |
39 |
40 |
41 |
42 | error
43 |
44 |
45 | {t('User not found')}
46 |
47 |
48 | );
49 | }
50 |
51 | if (pendingApiCall || user.username !== username) {
52 | return ;
53 | }
54 |
55 | return (
56 |
66 | );
67 | };
68 |
69 | export default UserPage;
70 |
--------------------------------------------------------------------------------
/frontend/src/pages/UserSignupPage.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import Input from '../components/Input';
3 | import { useTranslation } from 'react-i18next';
4 | import ButtonWithProgress from '../components/ButtonWithProgress';
5 | import { useApiProgress } from '../shared/ApiProgress';
6 | import { useDispatch } from 'react-redux';
7 | import { signupHandler } from '../redux/authActions';
8 |
9 | const UserSignupPage = (props) => {
10 | const [form, setForm] = useState({
11 | username: null,
12 | displayName: null,
13 | password: null,
14 | passwordRepeat: null,
15 | });
16 | const [errors, setErrors] = useState({});
17 |
18 | const dispatch = useDispatch();
19 |
20 | const onChange = (event) => {
21 | const { name, value } = event.target;
22 |
23 | setErrors((previousErrors) => ({ ...previousErrors, [name]: undefined }));
24 | setForm((previousForm) => ({ ...previousForm, [name]: value }));
25 | };
26 |
27 | const onClickSignup = async (event) => {
28 | event.preventDefault();
29 |
30 | const { history } = props;
31 | const { push } = history;
32 |
33 | const { username, displayName, password } = form;
34 |
35 | const body = {
36 | username,
37 | displayName,
38 | password,
39 | };
40 |
41 | try {
42 | await dispatch(signupHandler(body));
43 | push('/');
44 | } catch (error) {
45 | if (error.response.data.validationErrors) {
46 | setErrors(error.response.data.validationErrors);
47 | }
48 | }
49 | };
50 |
51 | const { t } = useTranslation();
52 |
53 | const { username: usernameError, displayName: displayNameError, password: passwordError } = errors;
54 | const pendingApiCallSignup = useApiProgress('post', '/api/1.0/users');
55 | const pendingApiCallLogin = useApiProgress('post', '/api/1.0/auth');
56 |
57 | const pendingApiCall = pendingApiCallSignup || pendingApiCallLogin;
58 |
59 | let passwordRepeatError;
60 | if (form.password !== form.passwordRepeat) {
61 | passwordRepeatError = t('Password mismatch');
62 | }
63 |
64 | return (
65 |
82 | );
83 | };
84 |
85 | export default UserSignupPage;
86 |
--------------------------------------------------------------------------------
/frontend/src/redux/Constants.js:
--------------------------------------------------------------------------------
1 | export const LOGOUT_SUCCESS = 'logout-success';
2 | export const LOGIN_SUCCESS = 'login-success';
3 | export const UPDATE_SUCCESS = 'update-success';
4 |
--------------------------------------------------------------------------------
/frontend/src/redux/authActions.js:
--------------------------------------------------------------------------------
1 | import * as ACTIONS from './Constants';
2 | import { login, signup, logout } from '../api/apiCalls';
3 |
4 | export const logoutSuccess = () => {
5 | return async function(dispatch){
6 | try {
7 | await logout();
8 | } catch (err){
9 |
10 | }
11 | dispatch({
12 | type: ACTIONS.LOGOUT_SUCCESS
13 | })
14 | }
15 | };
16 |
17 | export const loginSuccess = authState => {
18 | return {
19 | type: ACTIONS.LOGIN_SUCCESS,
20 | payload: authState
21 | };
22 | };
23 |
24 | export const updateSuccess = ({ displayName, image }) => {
25 | return {
26 | type: ACTIONS.UPDATE_SUCCESS,
27 | payload: {
28 | displayName,
29 | image
30 | }
31 | };
32 | };
33 |
34 | export const loginHandler = credentials => {
35 | return async function(dispatch) {
36 | const response = await login(credentials);
37 | const authState = {
38 | ...response.data.user,
39 | password: credentials.password,
40 | token: response.data.token
41 | };
42 | dispatch(loginSuccess(authState));
43 | return response;
44 | };
45 | };
46 |
47 | export const signupHandler = user => {
48 | return async function(dispatch) {
49 | const response = await signup(user);
50 | await dispatch(loginHandler(user));
51 | return response;
52 | };
53 | };
54 |
--------------------------------------------------------------------------------
/frontend/src/redux/authReducer.js:
--------------------------------------------------------------------------------
1 | import * as ACTIONS from './Constants';
2 |
3 | const defaultState = {
4 | isLoggedIn: false,
5 | username: undefined,
6 | displayName: undefined,
7 | image: undefined,
8 | password: undefined
9 | };
10 |
11 | const authReducer = (state = { ...defaultState }, action) => {
12 | if (action.type === ACTIONS.LOGOUT_SUCCESS) {
13 | return defaultState;
14 | } else if (action.type === ACTIONS.LOGIN_SUCCESS) {
15 | return {
16 | ...action.payload,
17 | isLoggedIn: true
18 | };
19 | } else if (action.type === ACTIONS.UPDATE_SUCCESS) {
20 | return {
21 | ...state,
22 | ...action.payload
23 | };
24 | }
25 | return state;
26 | };
27 |
28 | export default authReducer;
29 |
--------------------------------------------------------------------------------
/frontend/src/redux/configureStore.js:
--------------------------------------------------------------------------------
1 | import { createStore, applyMiddleware, compose } from 'redux';
2 | import thunk from 'redux-thunk';
3 | import authReducer from './authReducer';
4 | import SecureLS from 'secure-ls';
5 | import { setAuthorizationHeader } from '../api/apiCalls';
6 |
7 | const secureLs = new SecureLS();
8 |
9 | const getStateFromStorage = () => {
10 | const hoaxAuth = secureLs.get('hoax-auth');
11 |
12 | let stateInLocalStorage = {
13 | isLoggedIn: false,
14 | username: undefined,
15 | displayName: undefined,
16 | image: undefined,
17 | password: undefined
18 | };
19 |
20 | if (hoaxAuth) {
21 | return hoaxAuth;
22 | }
23 | return stateInLocalStorage;
24 | };
25 |
26 | const updateStateInStorage = newState => {
27 | secureLs.set('hoax-auth', newState);
28 | };
29 |
30 | const configureStore = () => {
31 | const initialState = getStateFromStorage();
32 | setAuthorizationHeader(initialState);
33 | const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
34 | const store = createStore(authReducer, initialState, composeEnhancers(applyMiddleware(thunk)));
35 |
36 | store.subscribe(() => {
37 | updateStateInStorage(store.getState());
38 | setAuthorizationHeader(store.getState());
39 | });
40 |
41 | return store;
42 | };
43 |
44 | export default configureStore;
45 |
--------------------------------------------------------------------------------
/frontend/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' }
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/frontend/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom/extend-expect';
6 |
--------------------------------------------------------------------------------
/frontend/src/shared/ApiProgress.js:
--------------------------------------------------------------------------------
1 | import { useState, useEffect } from 'react';
2 | import axios from 'axios';
3 |
4 | export const useApiProgress = (apiMethod, apiPath, strictPath) => {
5 | const [pendingApiCall, setPendingApiCall] = useState(false);
6 |
7 | useEffect(() => {
8 | let requestInterceptor, responseInterceptor;
9 |
10 | const updateApiCallFor = (method, url, inProgress) => {
11 | if (method !== apiMethod) {
12 | return;
13 | }
14 | if (strictPath && url === apiPath) {
15 | setPendingApiCall(inProgress);
16 | } else if (!strictPath && url.startsWith(apiPath)) {
17 | setPendingApiCall(inProgress);
18 | }
19 | };
20 |
21 | const registerInterceptors = () => {
22 | requestInterceptor = axios.interceptors.request.use(request => {
23 | const { url, method } = request;
24 | updateApiCallFor(method, url, true);
25 | return request;
26 | });
27 |
28 | responseInterceptor = axios.interceptors.response.use(
29 | response => {
30 | const { url, method } = response.config;
31 | updateApiCallFor(method, url, false);
32 | return response;
33 | },
34 | error => {
35 | const { url, method } = error.config;
36 | updateApiCallFor(method, url, false);
37 | throw error;
38 | }
39 | );
40 | };
41 |
42 | const unregisterInterceptors = () => {
43 | axios.interceptors.request.eject(requestInterceptor);
44 | axios.interceptors.response.eject(responseInterceptor);
45 | };
46 |
47 | registerInterceptors();
48 |
49 | return function unmount() {
50 | unregisterInterceptors();
51 | };
52 | }, [apiPath, apiMethod, strictPath]);
53 |
54 | return pendingApiCall;
55 | };
56 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # Spring ve React ile Web Uygulamasi Gelistirmek
2 |
3 | Bu projede, Spring Boot ve React ile bir sosyal paylasim platformu yapilmistir. Adim adim bu uygulamanin nasil yapildigina, Udemy'de, [Spring ve React ile Web Uygulamasi Gelistirmek](https://www.udemy.com/course/spring-ve-react-ile-web-uygulamas-gelistirmek/?referralCode=B4C2DCBE6BF974A25296) kursundan erisebilirsiniz.
4 |
--------------------------------------------------------------------------------
/ws/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**
5 | !**/src/test/**
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 |
30 | ### VS Code ###
31 | .vscode/
32 | devdb*
33 |
--------------------------------------------------------------------------------
/ws/.mvn/wrapper/MavenWrapperDownloader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2007-present the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | import java.net.*;
17 | import java.io.*;
18 | import java.nio.channels.*;
19 | import java.util.Properties;
20 |
21 | public class MavenWrapperDownloader {
22 |
23 | private static final String WRAPPER_VERSION = "0.5.6";
24 | /**
25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
26 | */
27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
29 |
30 | /**
31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
32 | * use instead of the default one.
33 | */
34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
35 | ".mvn/wrapper/maven-wrapper.properties";
36 |
37 | /**
38 | * Path where the maven-wrapper.jar will be saved to.
39 | */
40 | private static final String MAVEN_WRAPPER_JAR_PATH =
41 | ".mvn/wrapper/maven-wrapper.jar";
42 |
43 | /**
44 | * Name of the property which should be used to override the default download url for the wrapper.
45 | */
46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
47 |
48 | public static void main(String args[]) {
49 | System.out.println("- Downloader started");
50 | File baseDirectory = new File(args[0]);
51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
52 |
53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom
54 | // wrapperUrl parameter.
55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
56 | String url = DEFAULT_DOWNLOAD_URL;
57 | if(mavenWrapperPropertyFile.exists()) {
58 | FileInputStream mavenWrapperPropertyFileInputStream = null;
59 | try {
60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
61 | Properties mavenWrapperProperties = new Properties();
62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
64 | } catch (IOException e) {
65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
66 | } finally {
67 | try {
68 | if(mavenWrapperPropertyFileInputStream != null) {
69 | mavenWrapperPropertyFileInputStream.close();
70 | }
71 | } catch (IOException e) {
72 | // Ignore ...
73 | }
74 | }
75 | }
76 | System.out.println("- Downloading from: " + url);
77 |
78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
79 | if(!outputFile.getParentFile().exists()) {
80 | if(!outputFile.getParentFile().mkdirs()) {
81 | System.out.println(
82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
83 | }
84 | }
85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
86 | try {
87 | downloadFileFromURL(url, outputFile);
88 | System.out.println("Done");
89 | System.exit(0);
90 | } catch (Throwable e) {
91 | System.out.println("- Error downloading");
92 | e.printStackTrace();
93 | System.exit(1);
94 | }
95 | }
96 |
97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception {
98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
99 | String username = System.getenv("MVNW_USERNAME");
100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
101 | Authenticator.setDefault(new Authenticator() {
102 | @Override
103 | protected PasswordAuthentication getPasswordAuthentication() {
104 | return new PasswordAuthentication(username, password);
105 | }
106 | });
107 | }
108 | URL website = new URL(urlString);
109 | ReadableByteChannel rbc;
110 | rbc = Channels.newChannel(website.openStream());
111 | FileOutputStream fos = new FileOutputStream(destination);
112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
113 | fos.close();
114 | rbc.close();
115 | }
116 |
117 | }
118 |
--------------------------------------------------------------------------------
/ws/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/basarbk/spring-react-tr-course/f1004a8314d41498d1a7321ca3f83faab44ab91c/ws/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/ws/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
3 |
--------------------------------------------------------------------------------
/ws/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # https://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Mingw, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | fi
118 |
119 | if [ -z "$JAVA_HOME" ]; then
120 | javaExecutable="`which javac`"
121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
122 | # readlink(1) is not available as standard on Solaris 10.
123 | readLink=`which readlink`
124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
125 | if $darwin ; then
126 | javaHome="`dirname \"$javaExecutable\"`"
127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
128 | else
129 | javaExecutable="`readlink -f \"$javaExecutable\"`"
130 | fi
131 | javaHome="`dirname \"$javaExecutable\"`"
132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
133 | JAVA_HOME="$javaHome"
134 | export JAVA_HOME
135 | fi
136 | fi
137 | fi
138 |
139 | if [ -z "$JAVACMD" ] ; then
140 | if [ -n "$JAVA_HOME" ] ; then
141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
142 | # IBM's JDK on AIX uses strange locations for the executables
143 | JAVACMD="$JAVA_HOME/jre/sh/java"
144 | else
145 | JAVACMD="$JAVA_HOME/bin/java"
146 | fi
147 | else
148 | JAVACMD="`which java`"
149 | fi
150 | fi
151 |
152 | if [ ! -x "$JAVACMD" ] ; then
153 | echo "Error: JAVA_HOME is not defined correctly." >&2
154 | echo " We cannot execute $JAVACMD" >&2
155 | exit 1
156 | fi
157 |
158 | if [ -z "$JAVA_HOME" ] ; then
159 | echo "Warning: JAVA_HOME environment variable is not set."
160 | fi
161 |
162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
163 |
164 | # traverses directory structure from process work directory to filesystem root
165 | # first directory with .mvn subdirectory is considered project base directory
166 | find_maven_basedir() {
167 |
168 | if [ -z "$1" ]
169 | then
170 | echo "Path not specified to find_maven_basedir"
171 | return 1
172 | fi
173 |
174 | basedir="$1"
175 | wdir="$1"
176 | while [ "$wdir" != '/' ] ; do
177 | if [ -d "$wdir"/.mvn ] ; then
178 | basedir=$wdir
179 | break
180 | fi
181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
182 | if [ -d "${wdir}" ]; then
183 | wdir=`cd "$wdir/.."; pwd`
184 | fi
185 | # end of workaround
186 | done
187 | echo "${basedir}"
188 | }
189 |
190 | # concatenates all lines of a file
191 | concat_lines() {
192 | if [ -f "$1" ]; then
193 | echo "$(tr -s '\n' ' ' < "$1")"
194 | fi
195 | }
196 |
197 | BASE_DIR=`find_maven_basedir "$(pwd)"`
198 | if [ -z "$BASE_DIR" ]; then
199 | exit 1;
200 | fi
201 |
202 | ##########################################################################################
203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
204 | # This allows using the maven wrapper in projects that prohibit checking in binary data.
205 | ##########################################################################################
206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
207 | if [ "$MVNW_VERBOSE" = true ]; then
208 | echo "Found .mvn/wrapper/maven-wrapper.jar"
209 | fi
210 | else
211 | if [ "$MVNW_VERBOSE" = true ]; then
212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
213 | fi
214 | if [ -n "$MVNW_REPOURL" ]; then
215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
216 | else
217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
218 | fi
219 | while IFS="=" read key value; do
220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
221 | esac
222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
223 | if [ "$MVNW_VERBOSE" = true ]; then
224 | echo "Downloading from: $jarUrl"
225 | fi
226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
227 | if $cygwin; then
228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
229 | fi
230 |
231 | if command -v wget > /dev/null; then
232 | if [ "$MVNW_VERBOSE" = true ]; then
233 | echo "Found wget ... using wget"
234 | fi
235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
236 | wget "$jarUrl" -O "$wrapperJarPath"
237 | else
238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
239 | fi
240 | elif command -v curl > /dev/null; then
241 | if [ "$MVNW_VERBOSE" = true ]; then
242 | echo "Found curl ... using curl"
243 | fi
244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
245 | curl -o "$wrapperJarPath" "$jarUrl" -f
246 | else
247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
248 | fi
249 |
250 | else
251 | if [ "$MVNW_VERBOSE" = true ]; then
252 | echo "Falling back to using Java to download"
253 | fi
254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
255 | # For Cygwin, switch paths to Windows format before running javac
256 | if $cygwin; then
257 | javaClass=`cygpath --path --windows "$javaClass"`
258 | fi
259 | if [ -e "$javaClass" ]; then
260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
261 | if [ "$MVNW_VERBOSE" = true ]; then
262 | echo " - Compiling MavenWrapperDownloader.java ..."
263 | fi
264 | # Compiling the Java class
265 | ("$JAVA_HOME/bin/javac" "$javaClass")
266 | fi
267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
268 | # Running the downloader
269 | if [ "$MVNW_VERBOSE" = true ]; then
270 | echo " - Running MavenWrapperDownloader.java ..."
271 | fi
272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
273 | fi
274 | fi
275 | fi
276 | fi
277 | ##########################################################################################
278 | # End of extension
279 | ##########################################################################################
280 |
281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
282 | if [ "$MVNW_VERBOSE" = true ]; then
283 | echo $MAVEN_PROJECTBASEDIR
284 | fi
285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
286 |
287 | # For Cygwin, switch paths to Windows format before running java
288 | if $cygwin; then
289 | [ -n "$M2_HOME" ] &&
290 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
291 | [ -n "$JAVA_HOME" ] &&
292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
293 | [ -n "$CLASSPATH" ] &&
294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
295 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
297 | fi
298 |
299 | # Provide a "standardized" way to retrieve the CLI args that will
300 | # work with both Windows and non-Windows executions.
301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
302 | export MAVEN_CMD_LINE_ARGS
303 |
304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
305 |
306 | exec "$JAVACMD" \
307 | $MAVEN_OPTS \
308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
311 |
--------------------------------------------------------------------------------
/ws/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM https://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM set title of command window
39 | title %0
40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
42 |
43 | @REM set %HOME% to equivalent of $HOME
44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
45 |
46 | @REM Execute a user defined script before this one
47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
51 | :skipRcPre
52 |
53 | @setlocal
54 |
55 | set ERROR_CODE=0
56 |
57 | @REM To isolate internal variables from possible post scripts, we use another setlocal
58 | @setlocal
59 |
60 | @REM ==== START VALIDATION ====
61 | if not "%JAVA_HOME%" == "" goto OkJHome
62 |
63 | echo.
64 | echo Error: JAVA_HOME not found in your environment. >&2
65 | echo Please set the JAVA_HOME variable in your environment to match the >&2
66 | echo location of your Java installation. >&2
67 | echo.
68 | goto error
69 |
70 | :OkJHome
71 | if exist "%JAVA_HOME%\bin\java.exe" goto init
72 |
73 | echo.
74 | echo Error: JAVA_HOME is set to an invalid directory. >&2
75 | echo JAVA_HOME = "%JAVA_HOME%" >&2
76 | echo Please set the JAVA_HOME variable in your environment to match the >&2
77 | echo location of your Java installation. >&2
78 | echo.
79 | goto error
80 |
81 | @REM ==== END VALIDATION ====
82 |
83 | :init
84 |
85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
86 | @REM Fallback to current working directory if not found.
87 |
88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
90 |
91 | set EXEC_DIR=%CD%
92 | set WDIR=%EXEC_DIR%
93 | :findBaseDir
94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
95 | cd ..
96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
97 | set WDIR=%CD%
98 | goto findBaseDir
99 |
100 | :baseDirFound
101 | set MAVEN_PROJECTBASEDIR=%WDIR%
102 | cd "%EXEC_DIR%"
103 | goto endDetectBaseDir
104 |
105 | :baseDirNotFound
106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
107 | cd "%EXEC_DIR%"
108 |
109 | :endDetectBaseDir
110 |
111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
112 |
113 | @setlocal EnableExtensions EnableDelayedExpansion
114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
116 |
117 | :endReadAdditionalConfig
118 |
119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
122 |
123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
124 |
125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
127 | )
128 |
129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
131 | if exist %WRAPPER_JAR% (
132 | if "%MVNW_VERBOSE%" == "true" (
133 | echo Found %WRAPPER_JAR%
134 | )
135 | ) else (
136 | if not "%MVNW_REPOURL%" == "" (
137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
138 | )
139 | if "%MVNW_VERBOSE%" == "true" (
140 | echo Couldn't find %WRAPPER_JAR%, downloading it ...
141 | echo Downloading from: %DOWNLOAD_URL%
142 | )
143 |
144 | powershell -Command "&{"^
145 | "$webclient = new-object System.Net.WebClient;"^
146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
148 | "}"^
149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
150 | "}"
151 | if "%MVNW_VERBOSE%" == "true" (
152 | echo Finished downloading %WRAPPER_JAR%
153 | )
154 | )
155 | @REM End of extension
156 |
157 | @REM Provide a "standardized" way to retrieve the CLI args that will
158 | @REM work with both Windows and non-Windows executions.
159 | set MAVEN_CMD_LINE_ARGS=%*
160 |
161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
162 | if ERRORLEVEL 1 goto error
163 | goto end
164 |
165 | :error
166 | set ERROR_CODE=1
167 |
168 | :end
169 | @endlocal & set ERROR_CODE=%ERROR_CODE%
170 |
171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
175 | :skipRcPost
176 |
177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
179 |
180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
181 |
182 | exit /B %ERROR_CODE%
183 |
--------------------------------------------------------------------------------
/ws/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 2.3.4.RELEASE
9 |
10 |
11 | com.hoaxify
12 | ws
13 | 0.0.1-SNAPSHOT
14 | ws
15 | Demo project for Spring Boot
16 |
17 |
18 | 1.8
19 |
20 |
21 |
22 |
23 | org.springframework.boot
24 | spring-boot-starter-data-jpa
25 |
26 |
27 | org.springframework.boot
28 | spring-boot-starter-security
29 |
30 |
31 | org.springframework.boot
32 | spring-boot-starter-web
33 |
34 |
35 | org.springframework.boot
36 | spring-boot-starter-validation
37 |
38 |
39 | org.springframework.boot
40 | spring-boot-devtools
41 | runtime
42 | true
43 |
44 |
45 | com.h2database
46 | h2
47 | runtime
48 |
49 |
50 | org.projectlombok
51 | lombok
52 | true
53 |
54 |
55 | org.springframework.boot
56 | spring-boot-starter-test
57 | test
58 |
59 |
60 | org.junit.vintage
61 | junit-vintage-engine
62 |
63 |
64 |
65 |
66 | org.springframework.security
67 | spring-security-test
68 | test
69 |
70 |
71 | org.springframework.boot
72 | spring-boot-configuration-processor
73 | true
74 |
75 |
76 | org.apache.tika
77 | tika-core
78 | 1.23
79 |
80 |
81 |
82 |
83 |
84 |
85 | org.springframework.boot
86 | spring-boot-maven-plugin
87 |
88 |
89 |
90 |
91 |
92 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/WsApplication.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws;
2 |
3 | import org.springframework.boot.CommandLineRunner;
4 | import org.springframework.boot.SpringApplication;
5 | import org.springframework.boot.autoconfigure.SpringBootApplication;
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.context.annotation.Profile;
8 |
9 | import com.hoaxify.ws.hoax.HoaxService;
10 | import com.hoaxify.ws.hoax.vm.HoaxSubmitVM;
11 | import com.hoaxify.ws.user.User;
12 | import com.hoaxify.ws.user.UserService;
13 |
14 | @SpringBootApplication
15 | public class WsApplication {
16 |
17 | public static void main(String[] args) {
18 | SpringApplication.run(WsApplication.class, args);
19 | }
20 |
21 | @Bean
22 | @Profile("dev")
23 | CommandLineRunner createInitialUsers(UserService userService, HoaxService hoaxService) {
24 | return (args) -> {
25 | try {
26 | userService.getByUsername("user1");
27 | } catch (Exception e) {
28 | for(int i = 1; i<=25;i++) {
29 | User user = new User();
30 | user.setUsername("user"+i);
31 | user.setDisplayName("display"+i);
32 | user.setPassword("P4ssword");
33 | userService.save(user);
34 | for(int j = 1;j<=20;j++) {
35 | HoaxSubmitVM hoax = new HoaxSubmitVM();
36 | hoax.setContent("hoax (" +j + ") from user ("+i+")");
37 | hoaxService.save(hoax, user);
38 | }
39 | }
40 | }
41 | };
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/auth/AuthController.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.auth;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.web.bind.annotation.PostMapping;
5 | import org.springframework.web.bind.annotation.RequestBody;
6 | import org.springframework.web.bind.annotation.RequestHeader;
7 | import org.springframework.web.bind.annotation.RestController;
8 |
9 | import com.hoaxify.ws.shared.GenericResponse;
10 |
11 | @RestController
12 | public class AuthController {
13 |
14 | @Autowired
15 | AuthService authService;
16 |
17 | @PostMapping("/api/1.0/auth")
18 | AuthResponse handleAuthentication(@RequestBody Credentials credentials) {
19 | return authService.authenticate(credentials);
20 | }
21 |
22 | @PostMapping("/api/1.0/logout")
23 | GenericResponse handleLogout(@RequestHeader(name = "Authorization") String authorization) {
24 | String token = authorization.substring(7);
25 | authService.clearToken(token);
26 | return new GenericResponse("Logout success");
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/auth/AuthException.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.auth;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.web.bind.annotation.ResponseStatus;
5 |
6 | @ResponseStatus(HttpStatus.UNAUTHORIZED)
7 | public class AuthException extends RuntimeException {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/auth/AuthResponse.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.auth;
2 |
3 | import com.hoaxify.ws.user.vm.UserVM;
4 |
5 | import lombok.Data;
6 |
7 | @Data
8 | public class AuthResponse {
9 |
10 | private String token;
11 |
12 | private UserVM user;
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/auth/AuthService.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.auth;
2 |
3 | import java.util.Optional;
4 | import java.util.UUID;
5 |
6 | import javax.transaction.Transactional;
7 |
8 | import org.springframework.security.core.userdetails.UserDetails;
9 | import org.springframework.security.crypto.password.PasswordEncoder;
10 | import org.springframework.stereotype.Service;
11 |
12 | import com.hoaxify.ws.user.User;
13 | import com.hoaxify.ws.user.UserRepository;
14 | import com.hoaxify.ws.user.vm.UserVM;
15 |
16 | @Service
17 | public class AuthService {
18 |
19 | UserRepository userRepository;
20 |
21 | PasswordEncoder passwordEncoder;
22 |
23 | TokenRepository tokenRepository;
24 |
25 | public AuthService(UserRepository userRepository, PasswordEncoder passwordEncoder, TokenRepository tokenRepository) {
26 | super();
27 | this.userRepository = userRepository;
28 | this.passwordEncoder = passwordEncoder;
29 | this.tokenRepository = tokenRepository;
30 | }
31 |
32 | public AuthResponse authenticate(Credentials credentials) {
33 | User inDB = userRepository.findByUsername(credentials.getUsername());
34 | if(inDB == null) {
35 | throw new AuthException();
36 | }
37 | boolean matches = passwordEncoder.matches(credentials.getPassword(), inDB.getPassword());
38 | if(!matches) {
39 | throw new AuthException();
40 | }
41 | UserVM userVM = new UserVM(inDB);
42 | String token = generateRandomToken();
43 |
44 | Token tokenEntity = new Token();
45 | tokenEntity.setToken(token);
46 | tokenEntity.setUser(inDB);
47 | tokenRepository.save(tokenEntity);
48 | AuthResponse response = new AuthResponse();
49 | response.setUser(userVM);
50 | response.setToken(token);
51 | return response;
52 | }
53 |
54 | @Transactional
55 | public UserDetails getUserDetails(String token) {
56 | Optional optionalToken = tokenRepository.findById(token);
57 | if(!optionalToken.isPresent()) {
58 | return null;
59 | }
60 | return optionalToken.get().getUser();
61 | }
62 |
63 | public String generateRandomToken() {
64 | return UUID.randomUUID().toString().replaceAll("-", "");
65 | }
66 |
67 | public void clearToken(String token) {
68 | tokenRepository.deleteById(token);
69 |
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/auth/Credentials.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.auth;
2 |
3 | import lombok.Data;
4 |
5 | @Data
6 | public class Credentials {
7 |
8 | private String username;
9 |
10 | private String password;
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/auth/Token.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.auth;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.Id;
5 | import javax.persistence.ManyToOne;
6 |
7 | import com.hoaxify.ws.user.User;
8 |
9 | import lombok.Data;
10 |
11 | @Entity
12 | @Data
13 | public class Token {
14 |
15 | @Id
16 | private String token;
17 |
18 | @ManyToOne
19 | private User user;
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/auth/TokenRepository.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.auth;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 |
5 | public interface TokenRepository extends JpaRepository{
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/configuration/AppConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.configuration;
2 |
3 | import org.springframework.boot.context.properties.ConfigurationProperties;
4 | import org.springframework.context.annotation.Configuration;
5 |
6 | import lombok.Data;
7 |
8 | @Data
9 | @Configuration
10 | @ConfigurationProperties(prefix = "hoaxify")
11 | public class AppConfiguration {
12 |
13 | private String uploadPath;
14 |
15 | private String profileStorage = "profile";
16 |
17 | private String attachmentStorage = "attachments";
18 |
19 | public String getProfileStoragePath() {
20 | return uploadPath + "/" + profileStorage;
21 | }
22 |
23 | public String getAttachmentStoragePath() {
24 | return uploadPath + "/" + attachmentStorage;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/configuration/AuthEntryPoint.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.configuration;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.ServletException;
6 | import javax.servlet.http.HttpServletRequest;
7 | import javax.servlet.http.HttpServletResponse;
8 |
9 | import org.springframework.http.HttpStatus;
10 | import org.springframework.security.core.AuthenticationException;
11 | import org.springframework.security.web.AuthenticationEntryPoint;
12 |
13 | public class AuthEntryPoint implements AuthenticationEntryPoint{
14 |
15 | @Override
16 | public void commence(HttpServletRequest request, HttpServletResponse response,
17 | AuthenticationException authException) throws IOException, ServletException {
18 | response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
19 |
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/configuration/SecurityConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.configuration;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.http.HttpMethod;
5 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
8 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
9 | import org.springframework.security.config.http.SessionCreationPolicy;
10 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
11 | import org.springframework.security.crypto.password.PasswordEncoder;
12 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
13 |
14 | @EnableWebSecurity
15 | @EnableGlobalMethodSecurity(prePostEnabled = true)
16 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
17 |
18 | @Override
19 | protected void configure(HttpSecurity http) throws Exception {
20 | http.csrf().disable();
21 | http.exceptionHandling().authenticationEntryPoint(new AuthEntryPoint());
22 |
23 | http.headers().frameOptions().disable();
24 |
25 | http
26 | .authorizeRequests()
27 | .antMatchers(HttpMethod.PUT, "/api/1.0/users/{username}").authenticated()
28 | .antMatchers(HttpMethod.POST, "/api/1.0/hoaxes").authenticated()
29 | .antMatchers(HttpMethod.POST, "/api/1.0/hoax-attachments").authenticated()
30 | .antMatchers(HttpMethod.POST, "/api/1.0/logout").authenticated()
31 | .and()
32 | .authorizeRequests().anyRequest().permitAll();
33 |
34 | http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
35 |
36 | http.addFilterBefore(tokenFilter(), UsernamePasswordAuthenticationFilter.class);
37 | }
38 |
39 | @Bean
40 | PasswordEncoder passwordEncoder() {
41 | return new BCryptPasswordEncoder();
42 | }
43 |
44 | @Bean
45 | TokenFilter tokenFilter() {
46 | return new TokenFilter();
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/configuration/TokenFilter.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.configuration;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.FilterChain;
6 | import javax.servlet.ServletException;
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 |
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
12 | import org.springframework.security.core.context.SecurityContextHolder;
13 | import org.springframework.security.core.userdetails.UserDetails;
14 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
15 | import org.springframework.web.filter.OncePerRequestFilter;
16 |
17 | import com.hoaxify.ws.auth.AuthService;
18 |
19 | public class TokenFilter extends OncePerRequestFilter {
20 |
21 | @Autowired
22 | AuthService authService;
23 |
24 | @Override
25 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
26 | throws ServletException, IOException {
27 |
28 | String authorization = request.getHeader("Authorization");
29 | if(authorization != null) {
30 | String token = authorization.substring(7);
31 |
32 | UserDetails user = authService.getUserDetails(token);
33 | if(user != null) {
34 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
35 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
36 | SecurityContextHolder.getContext().setAuthentication(authentication);
37 | }
38 | }
39 |
40 | filterChain.doFilter(request, response);
41 |
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/configuration/WebConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.configuration;
2 |
3 | import java.io.File;
4 | import java.util.concurrent.TimeUnit;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.boot.CommandLineRunner;
8 | import org.springframework.context.annotation.Bean;
9 | import org.springframework.context.annotation.Configuration;
10 | import org.springframework.http.CacheControl;
11 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
12 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
13 |
14 | @Configuration
15 | public class WebConfiguration implements WebMvcConfigurer{
16 |
17 | @Autowired
18 | AppConfiguration appConfiguration;
19 |
20 | @Override
21 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
22 | registry.addResourceHandler("/images/**")
23 | .addResourceLocations("file:./"+appConfiguration.getUploadPath()+"/")
24 | .setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS));
25 | }
26 |
27 | @Bean
28 | CommandLineRunner createStorageDirectories() {
29 | return (args) -> {
30 | createFolder(appConfiguration.getUploadPath());
31 | createFolder(appConfiguration.getProfileStoragePath());
32 | createFolder(appConfiguration.getAttachmentStoragePath());
33 | };
34 | }
35 |
36 | private void createFolder(String path) {
37 | File folder = new File(path);
38 | boolean folderExist = folder.exists() && folder.isDirectory();
39 | if(!folderExist) {
40 | folder.mkdir();
41 | }
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/error/ApiError.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.error;
2 |
3 | import java.util.Date;
4 | import java.util.Map;
5 |
6 | import com.fasterxml.jackson.annotation.JsonInclude;
7 |
8 | import lombok.Data;
9 |
10 | @Data
11 | @JsonInclude(JsonInclude.Include.NON_NULL)
12 | public class ApiError {
13 |
14 | private int status;
15 |
16 | private String message;
17 |
18 | private String path;
19 |
20 | private long timestamp = new Date().getTime();
21 |
22 | private Map validationErrors;
23 |
24 | public ApiError(int status, String message, String path) {
25 | this.status = status;
26 | this.message = message;
27 | this.path = path;
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/error/ErrorHandler.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.error;
2 |
3 | import java.util.HashMap;
4 | import java.util.List;
5 | import java.util.Map;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.web.error.ErrorAttributeOptions;
9 | import org.springframework.boot.web.error.ErrorAttributeOptions.Include;
10 | import org.springframework.boot.web.servlet.error.ErrorAttributes;
11 | import org.springframework.boot.web.servlet.error.ErrorController;
12 | import org.springframework.validation.FieldError;
13 | import org.springframework.web.bind.annotation.RequestMapping;
14 | import org.springframework.web.bind.annotation.RestController;
15 | import org.springframework.web.context.request.WebRequest;
16 |
17 | @RestController
18 | public class ErrorHandler implements ErrorController {
19 |
20 | @Autowired
21 | private ErrorAttributes errorAttributes;
22 |
23 | @RequestMapping("/error")
24 | ApiError handleError(WebRequest webRequest) {
25 | Map attributes = this.errorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.of(Include.MESSAGE, Include.BINDING_ERRORS));
26 | String message = (String)attributes.get("message");
27 | String path = (String) attributes.get("path");
28 | int status = (Integer) attributes.get("status");
29 | ApiError error = new ApiError(status, message, path);
30 | if(attributes.containsKey("errors")) {
31 | @SuppressWarnings("unchecked")
32 | List fieldErrors = (List)attributes.get("errors");
33 | Map validationErrors = new HashMap<>();
34 | for(FieldError fieldError: fieldErrors) {
35 | validationErrors.put(fieldError.getField(), fieldError.getDefaultMessage());
36 | }
37 | error.setValidationErrors(validationErrors);
38 | }
39 | return error;
40 | }
41 |
42 |
43 | @Override
44 | public String getErrorPath() {
45 | return "/error";
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/error/NotFoundException.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.error;
2 |
3 | import org.springframework.http.HttpStatus;
4 |
5 | import org.springframework.web.bind.annotation.ResponseStatus;
6 |
7 | @ResponseStatus(HttpStatus.NOT_FOUND)
8 | public class NotFoundException extends RuntimeException{
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/file/FileAttachment.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.file;
2 |
3 | import java.util.Date;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.GenerationType;
8 | import javax.persistence.Id;
9 | import javax.persistence.OneToOne;
10 | import javax.persistence.Temporal;
11 | import javax.persistence.TemporalType;
12 |
13 | import com.hoaxify.ws.hoax.Hoax;
14 |
15 | import lombok.Data;
16 |
17 | @Data
18 | @Entity
19 | public class FileAttachment {
20 |
21 | @Id
22 | @GeneratedValue(strategy = GenerationType.IDENTITY)
23 | private long id;
24 |
25 | private String name;
26 |
27 | private String fileType;
28 |
29 | @Temporal(TemporalType.TIMESTAMP)
30 | private Date date;
31 |
32 | @OneToOne
33 | private Hoax hoax;
34 | }
35 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/file/FileAttachmentRepository.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.file;
2 |
3 | import java.util.Date;
4 | import java.util.List;
5 |
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 |
8 | import com.hoaxify.ws.user.User;
9 |
10 | public interface FileAttachmentRepository extends JpaRepository{
11 |
12 | List findByDateBeforeAndHoaxIsNull(Date date);
13 |
14 | List findByHoaxUser(User user);
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/file/FileController.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.file;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.web.bind.annotation.PostMapping;
5 | import org.springframework.web.bind.annotation.RestController;
6 | import org.springframework.web.multipart.MultipartFile;
7 |
8 | @RestController
9 | public class FileController {
10 |
11 | @Autowired
12 | FileService fileService;
13 |
14 | @PostMapping("/api/1.0/hoax-attachments")
15 | FileAttachment saveHoaxAttachment(MultipartFile file) {
16 | return fileService.saveHoaxAttachment(file);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/file/FileService.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.file;
2 |
3 | import java.io.File;
4 | import java.io.FileOutputStream;
5 | import java.io.IOException;
6 | import java.io.OutputStream;
7 | import java.nio.file.Files;
8 | import java.nio.file.Path;
9 | import java.nio.file.Paths;
10 | import java.util.Base64;
11 | import java.util.Date;
12 | import java.util.List;
13 | import java.util.UUID;
14 |
15 | import org.apache.tika.Tika;
16 | import org.springframework.scheduling.annotation.EnableScheduling;
17 | import org.springframework.scheduling.annotation.Scheduled;
18 | import org.springframework.stereotype.Service;
19 | import org.springframework.web.multipart.MultipartFile;
20 |
21 | import com.hoaxify.ws.configuration.AppConfiguration;
22 | import com.hoaxify.ws.user.User;
23 |
24 | @Service
25 | @EnableScheduling
26 | public class FileService {
27 |
28 | AppConfiguration appConfiguration;
29 |
30 | Tika tika;
31 |
32 | FileAttachmentRepository fileAttachmentRepository;
33 |
34 | public FileService(AppConfiguration appConfiguration, FileAttachmentRepository fileAttachmentRepository) {
35 | super();
36 | this.appConfiguration = appConfiguration;
37 | this.tika = new Tika();
38 | this.fileAttachmentRepository = fileAttachmentRepository;
39 | }
40 |
41 | public String writeBase64EncodedStringToFile(String image) throws IOException {
42 | String fileName = generateRandomName();
43 | File target = new File(appConfiguration.getProfileStoragePath() + "/" + fileName);
44 | OutputStream outputStream = new FileOutputStream(target);
45 |
46 | byte[] base64encoded = Base64.getDecoder().decode(image);
47 |
48 | outputStream.write(base64encoded);
49 | outputStream.close();
50 | return fileName;
51 | }
52 |
53 | public String generateRandomName() {
54 | return UUID.randomUUID().toString().replaceAll("-", "");
55 | }
56 |
57 | public void deleteProfileImage(String oldImageName) {
58 | if(oldImageName == null) {
59 | return;
60 | }
61 | deleteFile(Paths.get(appConfiguration.getProfileStoragePath(), oldImageName));
62 | }
63 |
64 | public void deleteAttachmentFile(String oldImageName) {
65 | if(oldImageName == null) {
66 | return;
67 | }
68 | deleteFile(Paths.get(appConfiguration.getAttachmentStoragePath(), oldImageName));
69 | }
70 |
71 | private void deleteFile(Path path) {
72 | try {
73 | Files.deleteIfExists(path);
74 | } catch (IOException e) {
75 | e.printStackTrace();
76 | }
77 | }
78 |
79 | public String detectType(String base64) {
80 | byte[] base64encoded = Base64.getDecoder().decode(base64);
81 | return detectType(base64encoded);
82 | }
83 |
84 | public String detectType(byte[] arr) {
85 | return tika.detect(arr);
86 | }
87 |
88 | public FileAttachment saveHoaxAttachment(MultipartFile multipartFile) {
89 | String fileName = generateRandomName();
90 | File target = new File(appConfiguration.getAttachmentStoragePath() + "/" + fileName);
91 | String fileType = null;
92 | try {
93 | byte[] arr = multipartFile.getBytes();
94 | OutputStream outputStream = new FileOutputStream(target);
95 | outputStream.write(arr);
96 | outputStream.close();
97 | fileType = detectType(arr);
98 | } catch (IOException e) {
99 | e.printStackTrace();
100 | }
101 | FileAttachment attachment = new FileAttachment();
102 | attachment.setName(fileName);
103 | attachment.setDate(new Date());
104 | attachment.setFileType(fileType);
105 | return fileAttachmentRepository.save(attachment);
106 | }
107 |
108 | @Scheduled(fixedRate = 24 * 60 * 60 * 1000)
109 | public void cleanupStorage() {
110 | Date twentyFourHoursAgo = new Date(System.currentTimeMillis() - (24 * 60 * 60 * 1000));
111 | List filesToBeDeleted = fileAttachmentRepository.findByDateBeforeAndHoaxIsNull(twentyFourHoursAgo);
112 | for(FileAttachment file : filesToBeDeleted) {
113 | deleteAttachmentFile(file.getName());
114 | fileAttachmentRepository.deleteById(file.getId());
115 | }
116 |
117 | }
118 |
119 | public void deleteAllStoredFilesForUser(User inDB) {
120 | deleteProfileImage(inDB.getImage());
121 | List filesToBeRemoved = fileAttachmentRepository.findByHoaxUser(inDB);
122 | for(FileAttachment file: filesToBeRemoved) {
123 | deleteAttachmentFile(file.getName());
124 | }
125 |
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/file/vm/FileAttachmentVM.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.file.vm;
2 |
3 | import com.hoaxify.ws.file.FileAttachment;
4 |
5 | import lombok.Data;
6 |
7 | @Data
8 | public class FileAttachmentVM {
9 |
10 | private String name;
11 |
12 | private String fileType;
13 |
14 | public FileAttachmentVM(FileAttachment fileAttachment) {
15 | this.setName(fileAttachment.getName());
16 | this.fileType = fileAttachment.getFileType();
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/hoax/Hoax.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.hoax;
2 |
3 | import java.util.Date;
4 |
5 | import javax.persistence.CascadeType;
6 | import javax.persistence.Column;
7 | import javax.persistence.Entity;
8 | import javax.persistence.GeneratedValue;
9 | import javax.persistence.GenerationType;
10 | import javax.persistence.Id;
11 | import javax.persistence.ManyToOne;
12 | import javax.persistence.OneToOne;
13 | import javax.persistence.Temporal;
14 | import javax.persistence.TemporalType;
15 |
16 | import com.hoaxify.ws.file.FileAttachment;
17 | import com.hoaxify.ws.user.User;
18 |
19 | import lombok.Data;
20 |
21 | @Data
22 | @Entity
23 | public class Hoax {
24 |
25 | @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
26 | private long id;
27 |
28 | @Column(length = 1000)
29 | private String content;
30 |
31 | @Temporal(TemporalType.TIMESTAMP)
32 | private Date timestamp;
33 |
34 | @ManyToOne
35 | private User user;
36 |
37 | @OneToOne(mappedBy = "hoax", cascade = CascadeType.REMOVE)
38 | private FileAttachment fileAttachment;
39 | }
40 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/hoax/HoaxController.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.hoax;
2 |
3 | import java.util.HashMap;
4 | import java.util.List;
5 | import java.util.Map;
6 | import java.util.stream.Collectors;
7 |
8 | import javax.validation.Valid;
9 |
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.data.domain.Page;
12 | import org.springframework.data.domain.Pageable;
13 | import org.springframework.data.domain.Sort.Direction;
14 | import org.springframework.data.web.PageableDefault;
15 | import org.springframework.http.ResponseEntity;
16 | import org.springframework.security.access.prepost.PreAuthorize;
17 | import org.springframework.web.bind.annotation.DeleteMapping;
18 | import org.springframework.web.bind.annotation.GetMapping;
19 | import org.springframework.web.bind.annotation.PathVariable;
20 | import org.springframework.web.bind.annotation.PostMapping;
21 | import org.springframework.web.bind.annotation.RequestBody;
22 | import org.springframework.web.bind.annotation.RequestMapping;
23 | import org.springframework.web.bind.annotation.RequestParam;
24 | import org.springframework.web.bind.annotation.RestController;
25 |
26 | import com.hoaxify.ws.hoax.vm.HoaxSubmitVM;
27 | import com.hoaxify.ws.hoax.vm.HoaxVM;
28 | import com.hoaxify.ws.shared.CurrentUser;
29 | import com.hoaxify.ws.shared.GenericResponse;
30 | import com.hoaxify.ws.user.User;
31 |
32 | @RestController
33 | @RequestMapping("/api/1.0")
34 | public class HoaxController {
35 |
36 | @Autowired
37 | HoaxService hoaxService;
38 |
39 | @PostMapping("/hoaxes")
40 | GenericResponse saveHoax(@Valid @RequestBody HoaxSubmitVM hoax, @CurrentUser User user) {
41 | hoaxService.save(hoax, user);
42 | return new GenericResponse("Hoax is saved");
43 | }
44 |
45 | @GetMapping("/hoaxes")
46 | Page getHoaxes(@PageableDefault(sort = "id", direction = Direction.DESC) Pageable page){
47 | return hoaxService.getHoaxes(page).map(HoaxVM::new);
48 | }
49 |
50 | @GetMapping({"/hoaxes/{id:[0-9]+}", "/users/{username}/hoaxes/{id:[0-9]+}"})
51 | ResponseEntity> getHoaxesRelative(@PageableDefault(sort = "id", direction = Direction.DESC) Pageable page,
52 | @PathVariable long id,
53 | @PathVariable(required=false) String username,
54 | @RequestParam(name="count", required = false, defaultValue = "false") boolean count,
55 | @RequestParam(name="direction", defaultValue = "before") String direction){
56 | if(count) {
57 | long newHoaxCount = hoaxService.getNewHoaxesCount(id, username);
58 | Map response = new HashMap<>();
59 | response.put("count", newHoaxCount);
60 | return ResponseEntity.ok(response);
61 | }
62 | if(direction.equals("after")) {
63 | List newHoaxes = hoaxService.getNewHoaxes(id, username, page.getSort())
64 | .stream().map(HoaxVM::new).collect(Collectors.toList());
65 | return ResponseEntity.ok(newHoaxes);
66 | }
67 |
68 | return ResponseEntity.ok(hoaxService.getOldHoaxes(id, username, page).map(HoaxVM::new));
69 | }
70 |
71 | @GetMapping("/users/{username}/hoaxes")
72 | Page getUserHoaxes(@PathVariable String username, @PageableDefault(sort = "id", direction = Direction.DESC) Pageable page){
73 | return hoaxService.getHoaxesOfUser(username, page).map(HoaxVM::new);
74 | }
75 |
76 | @DeleteMapping("/hoaxes/{id:[0-9]+}")
77 | @PreAuthorize("@hoaxSecurity.isAllowedToDelete(#id, principal)")
78 | GenericResponse deleteHoax(@PathVariable long id) {
79 | hoaxService.delete(id);
80 | return new GenericResponse("Hoax removed");
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/hoax/HoaxRepository.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.hoax;
2 |
3 | import org.springframework.data.domain.Page;
4 | import org.springframework.data.domain.Pageable;
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
7 |
8 | import com.hoaxify.ws.user.User;
9 |
10 | public interface HoaxRepository extends JpaRepository, JpaSpecificationExecutor{
11 |
12 | Page findByUser(User user, Pageable page);
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/hoax/HoaxSecurityService.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.hoax;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.hoaxify.ws.user.User;
9 |
10 | @Service(value = "hoaxSecurity")
11 | public class HoaxSecurityService {
12 |
13 | @Autowired
14 | HoaxRepository hoaxRepository;
15 |
16 | public boolean isAllowedToDelete(long id, User loggedInUser) {
17 | Optional optionalHoax = hoaxRepository.findById(id);
18 | if(!optionalHoax.isPresent()) {
19 | return false;
20 | }
21 |
22 | Hoax hoax = optionalHoax.get();
23 | if(hoax.getUser().getId() != loggedInUser.getId()) {
24 | return false;
25 | }
26 |
27 | return true;
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/hoax/HoaxService.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.hoax;
2 |
3 | import java.util.Date;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import org.springframework.data.domain.Page;
8 | import org.springframework.data.domain.Pageable;
9 | import org.springframework.data.domain.Sort;
10 | import org.springframework.data.jpa.domain.Specification;
11 | import org.springframework.stereotype.Service;
12 |
13 | import com.hoaxify.ws.file.FileAttachment;
14 | import com.hoaxify.ws.file.FileAttachmentRepository;
15 | import com.hoaxify.ws.file.FileService;
16 | import com.hoaxify.ws.hoax.vm.HoaxSubmitVM;
17 | import com.hoaxify.ws.user.User;
18 | import com.hoaxify.ws.user.UserService;
19 |
20 | @Service
21 | public class HoaxService {
22 |
23 | HoaxRepository hoaxRepository;
24 |
25 | UserService userService;
26 |
27 | FileAttachmentRepository fileAttachmentRepository;
28 |
29 | FileService fileService;
30 |
31 | public HoaxService(HoaxRepository hoaxRepository, UserService userService, FileAttachmentRepository fileAttachmentRepository
32 | ,FileService fileService) {
33 | super();
34 | this.hoaxRepository = hoaxRepository;
35 | this.fileAttachmentRepository = fileAttachmentRepository;
36 | this.fileService = fileService;
37 | this.userService = userService;
38 | }
39 |
40 | public void save(HoaxSubmitVM hoaxSubmitVM, User user) {
41 | Hoax hoax = new Hoax();
42 | hoax.setContent(hoaxSubmitVM.getContent());
43 | hoax.setTimestamp(new Date());
44 | hoax.setUser(user);
45 | hoaxRepository.save(hoax);
46 | Optional optionalFileAttachment = fileAttachmentRepository.findById(hoaxSubmitVM.getAttachmentId());
47 | if(optionalFileAttachment.isPresent()) {
48 | FileAttachment fileAttachment = optionalFileAttachment.get();
49 | fileAttachment.setHoax(hoax);
50 | fileAttachmentRepository.save(fileAttachment);
51 | }
52 | }
53 |
54 | public Page getHoaxes(Pageable page) {
55 | return hoaxRepository.findAll(page);
56 | }
57 |
58 | public Page getHoaxesOfUser(String username, Pageable page) {
59 | User inDB = userService.getByUsername(username);
60 | return hoaxRepository.findByUser(inDB, page);
61 | }
62 |
63 | public Page getOldHoaxes(long id, String username, Pageable page) {
64 | Specification specification = idLessThan(id);
65 | if(username != null) {
66 | User inDB = userService.getByUsername(username);
67 | specification = specification.and(userIs(inDB));
68 | }
69 | return hoaxRepository.findAll(specification, page);
70 | }
71 |
72 | public long getNewHoaxesCount(long id, String username) {
73 | Specification specification = idGreaterThan(id);
74 | if(username != null) {
75 | User inDB = userService.getByUsername(username);
76 | specification = specification.and(userIs(inDB));
77 | }
78 | return hoaxRepository.count(specification);
79 | }
80 |
81 | public List getNewHoaxes(long id, String username, Sort sort) {
82 | Specification specification = idGreaterThan(id);
83 | if(username != null) {
84 | User inDB = userService.getByUsername(username);
85 | specification = specification.and(userIs(inDB));
86 | }
87 | return hoaxRepository.findAll(specification, sort);
88 | }
89 |
90 |
91 | Specification idLessThan(long id){
92 | return (root, query, criteriaBuilder) -> {
93 | return criteriaBuilder.lessThan(root.get("id"), id);
94 | };
95 | }
96 |
97 | Specification userIs(User user){
98 | return (root, query, criteriaBuilder) -> {
99 | return criteriaBuilder.equal(root.get("user"), user);
100 | };
101 | }
102 |
103 | Specification idGreaterThan(long id){
104 | return (root, query, criteriaBuilder) -> {
105 | return criteriaBuilder.greaterThan(root.get("id"), id);
106 | };
107 | }
108 |
109 | public void delete(long id) {
110 | Hoax inDB = hoaxRepository.getOne(id);
111 | if(inDB.getFileAttachment() != null) {
112 | String fileName = inDB.getFileAttachment().getName();
113 | fileService.deleteAttachmentFile(fileName);
114 | }
115 | hoaxRepository.deleteById(id);
116 | }
117 |
118 | }
119 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/hoax/vm/HoaxSubmitVM.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.hoax.vm;
2 |
3 | import javax.validation.constraints.Size;
4 |
5 | import lombok.Data;
6 |
7 | @Data
8 | public class HoaxSubmitVM {
9 |
10 | @Size(min=1, max=1000)
11 | private String content;
12 |
13 | private long attachmentId;
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/hoax/vm/HoaxVM.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.hoax.vm;
2 |
3 | import com.hoaxify.ws.file.vm.FileAttachmentVM;
4 | import com.hoaxify.ws.hoax.Hoax;
5 | import com.hoaxify.ws.user.vm.UserVM;
6 |
7 | import lombok.Data;
8 |
9 | @Data
10 | public class HoaxVM {
11 |
12 | private long id;
13 |
14 | private String content;
15 |
16 | private long timestamp;
17 |
18 | private UserVM user;
19 |
20 | private FileAttachmentVM fileAttachment;
21 |
22 | public HoaxVM(Hoax hoax) {
23 | this.setId(hoax.getId());
24 | this.setContent(hoax.getContent());
25 | this.setTimestamp(hoax.getTimestamp().getTime());
26 | this.setUser(new UserVM(hoax.getUser()));
27 | if(hoax.getFileAttachment() != null) {
28 | this.fileAttachment = new FileAttachmentVM(hoax.getFileAttachment());
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/shared/CurrentUser.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.shared;
2 |
3 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
4 |
5 | import java.lang.annotation.ElementType;
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.Target;
8 |
9 | import org.springframework.security.core.annotation.AuthenticationPrincipal;
10 |
11 | @Target({ ElementType.PARAMETER })
12 | @Retention(RUNTIME)
13 | @AuthenticationPrincipal
14 | public @interface CurrentUser {
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/shared/FileType.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.shared;
2 |
3 | import static java.lang.annotation.ElementType.FIELD;
4 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
5 |
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.Target;
8 |
9 | import javax.validation.Constraint;
10 | import javax.validation.Payload;
11 |
12 | @Target({ FIELD })
13 | @Retention(RUNTIME)
14 | @Constraint(validatedBy = { FileTypeValidator.class })
15 | public @interface FileType {
16 |
17 | String message() default "{hoaxify.constraint.FileType.message}";
18 |
19 | Class>[] groups() default { };
20 |
21 | Class extends Payload>[] payload() default { };
22 |
23 | String[] types();
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/shared/FileTypeValidator.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.shared;
2 |
3 | import java.util.Arrays;
4 | import java.util.stream.Collectors;
5 |
6 | import javax.validation.ConstraintValidator;
7 | import javax.validation.ConstraintValidatorContext;
8 |
9 | import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 |
12 | import com.hoaxify.ws.file.FileService;
13 |
14 | public class FileTypeValidator implements ConstraintValidator{
15 |
16 | @Autowired
17 | FileService fileService;
18 |
19 | String[] types;
20 |
21 | @Override
22 | public void initialize(FileType constraintAnnotation) {
23 | this.types = constraintAnnotation.types();
24 | }
25 |
26 |
27 | @Override
28 | public boolean isValid(String value, ConstraintValidatorContext context) {
29 | if(value == null || value.isEmpty()) {
30 | return true;
31 | }
32 | String fileType = fileService.detectType(value);
33 | for(String supportedType: this.types) {
34 | if(fileType.contains(supportedType)) {
35 | return true;
36 | }
37 | }
38 | String supportedTypes = Arrays.stream(this.types).collect(Collectors.joining(", "));
39 |
40 | context.disableDefaultConstraintViolation();
41 | HibernateConstraintValidatorContext hibernateConstraintValidatorContext = context.unwrap(HibernateConstraintValidatorContext.class);
42 | hibernateConstraintValidatorContext.addMessageParameter("types", supportedTypes);
43 | hibernateConstraintValidatorContext.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addConstraintViolation();
44 | return false;
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/shared/GenericResponse.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.shared;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 |
6 | @Data
7 | @AllArgsConstructor
8 | public class GenericResponse {
9 |
10 | private String message;
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/user/UniqueUsername.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.user;
2 |
3 | import static java.lang.annotation.ElementType.FIELD;
4 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
5 |
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.Target;
8 |
9 | import javax.validation.Constraint;
10 | import javax.validation.Payload;
11 |
12 | @Target({ FIELD })
13 | @Retention(RUNTIME)
14 | @Constraint(validatedBy = { UniqueUsernameValidator.class })
15 | public @interface UniqueUsername {
16 |
17 | String message() default "{hoaxify.constraint.username.UniqueUsername.message}";
18 |
19 | Class>[] groups() default { };
20 |
21 | Class extends Payload>[] payload() default { };
22 | }
23 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/user/UniqueUsernameValidator.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.user;
2 |
3 | import javax.validation.ConstraintValidator;
4 | import javax.validation.ConstraintValidatorContext;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 |
8 | public class UniqueUsernameValidator implements ConstraintValidator{
9 |
10 | @Autowired
11 | UserRepository userRepository;
12 |
13 | @Override
14 | public boolean isValid(String username, ConstraintValidatorContext context) {
15 | User user = userRepository.findByUsername(username);
16 | if(user != null) {
17 | return false;
18 | }
19 | return true;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/user/User.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.user;
2 |
3 | import java.util.Collection;
4 | import java.util.List;
5 |
6 | import javax.persistence.CascadeType;
7 | import javax.persistence.Entity;
8 | import javax.persistence.GeneratedValue;
9 | import javax.persistence.GenerationType;
10 | import javax.persistence.Id;
11 | import javax.persistence.OneToMany;
12 | import javax.validation.constraints.NotNull;
13 | import javax.validation.constraints.Pattern;
14 | import javax.validation.constraints.Size;
15 |
16 | import org.springframework.security.core.GrantedAuthority;
17 | import org.springframework.security.core.authority.AuthorityUtils;
18 | import org.springframework.security.core.userdetails.UserDetails;
19 |
20 | import com.hoaxify.ws.auth.Token;
21 | import com.hoaxify.ws.hoax.Hoax;
22 |
23 | import lombok.Data;
24 |
25 | @Data
26 | @Entity
27 | public class User implements UserDetails{
28 |
29 | /**
30 | *
31 | */
32 | private static final long serialVersionUID = -8421768845853099274L;
33 |
34 | @Id
35 | @GeneratedValue(strategy = GenerationType.IDENTITY)
36 | private long id;
37 |
38 | @NotNull(message="{hoaxify.constraint.username.NotNull.message}")
39 | @Size(min = 4, max=255)
40 | @UniqueUsername
41 | private String username;
42 |
43 | @NotNull
44 | @Size(min = 4, max=255)
45 | private String displayName;
46 |
47 | @NotNull
48 | @Size(min = 8, max=255)
49 | @Pattern(regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).*$", message="{hoaxify.constrain.password.Pattern.message}")
50 | private String password;
51 |
52 | private String image;
53 |
54 | @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE)
55 | private List hoaxes;
56 |
57 | @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE)
58 | private List tokens;
59 |
60 | @Override
61 | public Collection extends GrantedAuthority> getAuthorities() {
62 | return AuthorityUtils.createAuthorityList("Role_user");
63 | }
64 |
65 | @Override
66 | public boolean isAccountNonExpired() {
67 | return true;
68 | }
69 |
70 | @Override
71 | public boolean isAccountNonLocked() {
72 | return true;
73 | }
74 |
75 | @Override
76 | public boolean isCredentialsNonExpired() {
77 | return true;
78 | }
79 |
80 | @Override
81 | public boolean isEnabled() {
82 | return true;
83 | }
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/user/UserController.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.user;
2 |
3 | import javax.validation.Valid;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.data.domain.Page;
7 | import org.springframework.data.domain.Pageable;
8 | import org.springframework.security.access.prepost.PreAuthorize;
9 | import org.springframework.web.bind.annotation.DeleteMapping;
10 | import org.springframework.web.bind.annotation.GetMapping;
11 | import org.springframework.web.bind.annotation.PathVariable;
12 | import org.springframework.web.bind.annotation.PostMapping;
13 | import org.springframework.web.bind.annotation.PutMapping;
14 | import org.springframework.web.bind.annotation.RequestBody;
15 | import org.springframework.web.bind.annotation.RequestMapping;
16 | import org.springframework.web.bind.annotation.RestController;
17 |
18 | import com.hoaxify.ws.shared.CurrentUser;
19 | import com.hoaxify.ws.shared.GenericResponse;
20 | import com.hoaxify.ws.user.vm.UserUpdateVM;
21 | import com.hoaxify.ws.user.vm.UserVM;
22 |
23 | @RestController
24 | @RequestMapping("/api/1.0")
25 | public class UserController {
26 |
27 | @Autowired
28 | UserService userService;
29 |
30 | @PostMapping("/users")
31 | public GenericResponse createUser(@Valid @RequestBody User user) {
32 | userService.save(user);
33 | return new GenericResponse("user created");
34 | }
35 |
36 | @GetMapping("/users")
37 | Page getUsers(Pageable page, @CurrentUser User user){
38 | return userService.getUsers(page, user).map(UserVM::new);
39 | }
40 |
41 | @GetMapping("/users/{username}")
42 | UserVM getUser(@PathVariable String username) {
43 | User user = userService.getByUsername(username);
44 | return new UserVM(user);
45 | }
46 |
47 | @PutMapping("/users/{username}")
48 | @PreAuthorize("#username == principal.username")
49 | UserVM updateUser(@Valid @RequestBody UserUpdateVM updatedUser, @PathVariable String username) {
50 | User user = userService.updateUser(username, updatedUser);
51 | return new UserVM(user);
52 | }
53 |
54 | @DeleteMapping("/users/{username}")
55 | @PreAuthorize("#username == principal.username")
56 | GenericResponse deleteUser(@PathVariable String username) {
57 | userService.deleteUser(username);
58 | return new GenericResponse("User is removed");
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/user/UserRepository.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.user;
2 |
3 | import org.springframework.data.domain.Page;
4 | import org.springframework.data.domain.Pageable;
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 |
7 | public interface UserRepository extends JpaRepository{
8 |
9 | User findByUsername(String username);
10 |
11 | Page findByUsernameNot(String username, Pageable page);
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/user/UserService.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.user;
2 |
3 | import java.io.IOException;
4 |
5 | import org.springframework.data.domain.Page;
6 | import org.springframework.data.domain.Pageable;
7 | import org.springframework.security.crypto.password.PasswordEncoder;
8 | import org.springframework.stereotype.Service;
9 |
10 | import com.hoaxify.ws.error.NotFoundException;
11 | import com.hoaxify.ws.file.FileService;
12 | import com.hoaxify.ws.user.vm.UserUpdateVM;
13 |
14 | @Service
15 | public class UserService {
16 |
17 | UserRepository userRepository;
18 |
19 | PasswordEncoder passwordEncoder;
20 |
21 | FileService fileService;
22 |
23 | public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, FileService fileService) {
24 | this.userRepository = userRepository;
25 | this.passwordEncoder = passwordEncoder;
26 | this.fileService = fileService;
27 | }
28 |
29 | public void save(User user) {
30 | user.setPassword(this.passwordEncoder.encode(user.getPassword()));
31 | userRepository.save(user);
32 | }
33 |
34 | public Page getUsers(Pageable page, User user) {
35 | if(user != null) {
36 | return userRepository.findByUsernameNot(user.getUsername(), page);
37 | }
38 | return userRepository.findAll(page);
39 | }
40 |
41 | public User getByUsername(String username) {
42 | User inDB = userRepository.findByUsername(username);
43 | if(inDB == null) {
44 | throw new NotFoundException();
45 | }
46 | return inDB;
47 | }
48 |
49 | public User updateUser(String username, UserUpdateVM updatedUser) {
50 | User inDB = getByUsername(username);
51 | inDB.setDisplayName(updatedUser.getDisplayName());
52 | if(updatedUser.getImage() != null) {
53 | String oldImageName = inDB.getImage();
54 | try {
55 | String storedFileName = fileService.writeBase64EncodedStringToFile(updatedUser.getImage());
56 | inDB.setImage(storedFileName);
57 | } catch (IOException e) {
58 | e.printStackTrace();
59 | }
60 | fileService.deleteProfileImage(oldImageName);
61 | }
62 | return userRepository.save(inDB);
63 | }
64 |
65 | public void deleteUser(String username) {
66 | User inDB = userRepository.findByUsername(username);
67 | fileService.deleteAllStoredFilesForUser(inDB);
68 | userRepository.delete(inDB);
69 | }
70 |
71 |
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/user/vm/UserUpdateVM.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.user.vm;
2 |
3 | import javax.validation.constraints.NotNull;
4 | import javax.validation.constraints.Size;
5 |
6 | import com.hoaxify.ws.shared.FileType;
7 |
8 | import lombok.Data;
9 |
10 | @Data
11 | public class UserUpdateVM {
12 |
13 | @NotNull
14 | @Size(min = 4, max=255)
15 | private String displayName;
16 |
17 | @FileType(types= {"jpeg", "png"})
18 | private String image;
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/ws/src/main/java/com/hoaxify/ws/user/vm/UserVM.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws.user.vm;
2 |
3 | import com.hoaxify.ws.user.User;
4 |
5 | import lombok.Data;
6 |
7 | @Data
8 | public class UserVM {
9 |
10 | private String username;
11 |
12 | private String displayName;
13 |
14 | private String image;
15 |
16 | public UserVM(User user) {
17 | this.setUsername(user.getUsername());
18 | this.setDisplayName(user.getDisplayName());
19 | this.setImage(user.getImage());
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/ws/src/main/resources/ValidationMessages.properties:
--------------------------------------------------------------------------------
1 | hoaxify.constraint.username.NotNull.message = Username cannot be null
2 | hoaxify.constrain.password.Pattern.message = Password must have at least 1 uppercase, 1 lowercase letter and 1 number
3 | hoaxify.constraint.username.UniqueUsername.message = This username is in use
4 | hoaxify.constraint.FileType.message = Unsupported file. Only {types} supported
--------------------------------------------------------------------------------
/ws/src/main/resources/ValidationMessages_tr.properties:
--------------------------------------------------------------------------------
1 | hoaxify.constraint.username.NotNull.message = Kullan\u0131c\u0131 ad\u0131 bo\u015F olamaz
2 | hoaxify.constrain.password.Pattern.message = \u015Eifrenizde en az bir b\u00fcy\u00fck harf, bir k\u00fc\u00e7\u00fck harf ve bir say\u0131 olmak zorundad\u0131r
3 | hoaxify.constraint.username.UniqueUsername.message = Bu kullan\u0131c\u0131 ad\u0131 kullan\u0131l\u0131yor
4 | hoaxify.constraint.FileType.message = Desteklenmeyen dosya tipi. Sadece {types} dosyalar\u0131 kullan\u0131labilir
--------------------------------------------------------------------------------
/ws/src/main/resources/application.yaml:
--------------------------------------------------------------------------------
1 | spring:
jpa:
properties:
javax:
2 | persistence:
3 | validation:
4 | mode: none
data:
web:
pageable:
default-page-size: 10
5 | max-page-size: 100
profiles:
active:
- dev
servlet:
multipart:
max-file-size: 10MB
6 | ---
7 | spring:
profiles: production
8 | hoaxify:
upload-path: storage-production
9 | ---
10 | spring:
profiles: dev
datasource:
url: jdbc:h2:./devdb
jpa:
hibernate:
ddl-auto: update
11 | hoaxify:
upload-path: storage-dev
--------------------------------------------------------------------------------
/ws/src/test/java/com/hoaxify/ws/WsApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.hoaxify.ws;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class WsApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------