├── library-webui
├── src
│ ├── assets
│ │ └── .gitkeep
│ ├── app
│ │ ├── app.component.css
│ │ ├── login
│ │ │ ├── login.component.css
│ │ │ ├── login.component.spec.ts
│ │ │ ├── login.component.ts
│ │ │ └── login.component.html
│ │ ├── common
│ │ │ ├── main
│ │ │ │ ├── main.component.css
│ │ │ │ ├── main.component.ts
│ │ │ │ ├── main.component.html
│ │ │ │ └── main.component.spec.ts
│ │ │ ├── api
│ │ │ │ ├── book
│ │ │ │ │ ├── book.component.css
│ │ │ │ │ ├── book-details
│ │ │ │ │ │ ├── book-details.component.css
│ │ │ │ │ │ ├── book-details.component.spec.ts
│ │ │ │ │ │ └── book-details.component.ts
│ │ │ │ │ ├── Book.ts
│ │ │ │ │ ├── book.routing.module.ts
│ │ │ │ │ ├── book.component.spec.ts
│ │ │ │ │ ├── book.module.ts
│ │ │ │ │ ├── book.component.ts
│ │ │ │ │ └── book.component.html
│ │ │ │ ├── student
│ │ │ │ │ ├── student.component.css
│ │ │ │ │ ├── get-book
│ │ │ │ │ │ ├── get-book.component.css
│ │ │ │ │ │ ├── get-book.component.spec.ts
│ │ │ │ │ │ └── get-book.component.ts
│ │ │ │ │ ├── student-details
│ │ │ │ │ │ ├── student-details.component.css
│ │ │ │ │ │ ├── student-details.component.spec.ts
│ │ │ │ │ │ └── student-details.component.ts
│ │ │ │ │ ├── Student.ts
│ │ │ │ │ ├── student.routing.module.ts
│ │ │ │ │ ├── student.component.spec.ts
│ │ │ │ │ ├── student.module.ts
│ │ │ │ │ └── student.component.ts
│ │ │ │ ├── user-detail
│ │ │ │ │ ├── user-detail.component.css
│ │ │ │ │ ├── User.ts
│ │ │ │ │ ├── user.routing.module.ts
│ │ │ │ │ ├── user.module.ts
│ │ │ │ │ ├── user-detail.component.spec.ts
│ │ │ │ │ └── user-detail.component.ts
│ │ │ │ └── author
│ │ │ │ │ ├── author-detail
│ │ │ │ │ ├── author-detail.component.css
│ │ │ │ │ ├── author-detail.component.spec.ts
│ │ │ │ │ └── author-detail.component.ts
│ │ │ │ │ ├── author.component.css
│ │ │ │ │ ├── Author.ts
│ │ │ │ │ ├── author.routing.module.ts
│ │ │ │ │ ├── author.component.spec.ts
│ │ │ │ │ ├── author.module.ts
│ │ │ │ │ └── author.component.ts
│ │ │ └── header
│ │ │ │ ├── header.component.css
│ │ │ │ ├── header.component.html
│ │ │ │ ├── header.component.ts
│ │ │ │ └── header.component.spec.ts
│ │ ├── register
│ │ │ ├── register.component.css
│ │ │ ├── register.component.spec.ts
│ │ │ ├── register.component.ts
│ │ │ └── register.component.html
│ │ ├── shared
│ │ │ ├── notfound
│ │ │ │ ├── notfound.component.css
│ │ │ │ ├── notfound.component.html
│ │ │ │ ├── notfound.component.ts
│ │ │ │ └── notfound.component.spec.ts
│ │ │ └── Page.ts
│ │ ├── app.component.ts
│ │ ├── services
│ │ │ ├── book.service.spec.ts
│ │ │ ├── general
│ │ │ │ ├── api.service.spec.ts
│ │ │ │ └── api.service.ts
│ │ │ ├── user.service.spec.ts
│ │ │ ├── author.service.spec.ts
│ │ │ ├── student.service.spec.ts
│ │ │ ├── alertify.service.spec.ts
│ │ │ ├── alertify.service.ts
│ │ │ ├── user.service.ts
│ │ │ ├── author.service.ts
│ │ │ ├── book.service.ts
│ │ │ └── student.service.ts
│ │ ├── security
│ │ │ ├── auth.guard.ts
│ │ │ ├── jwt.interceptor.ts
│ │ │ ├── authentication.interceptor.ts
│ │ │ └── authentication.service.ts
│ │ ├── app.component.spec.ts
│ │ ├── app.routing.module.ts
│ │ ├── app.component.html
│ │ └── app.module.ts
│ ├── environments
│ │ ├── environment.prod.ts
│ │ └── environment.ts
│ ├── favicon.ico
│ ├── styles.css
│ ├── index.html
│ ├── main.ts
│ ├── test.ts
│ └── polyfills.ts
├── .dockerignore
├── e2e
│ ├── tsconfig.json
│ ├── src
│ │ ├── app.po.ts
│ │ └── app.e2e-spec.ts
│ └── protractor.conf.js
├── tsconfig.app.json
├── .editorconfig
├── nginx.conf
├── tsconfig.spec.json
├── Dockerfile
├── browserslist
├── tsconfig.json
├── .gitignore
├── README.md
├── karma.conf.js
├── package.json
├── tslint.json
└── angular.json
├── Library-Application
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ ├── maven-wrapper.properties
│ │ └── MavenWrapperDownloader.java
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── example
│ │ │ │ └── demo
│ │ │ │ ├── model
│ │ │ │ ├── BookStatus.java
│ │ │ │ ├── City.java
│ │ │ │ ├── User.java
│ │ │ │ ├── Author.java
│ │ │ │ ├── Book.java
│ │ │ │ └── Student.java
│ │ │ │ ├── dto
│ │ │ │ ├── TokenResponse.java
│ │ │ │ ├── LoginRequest.java
│ │ │ │ ├── RegistirationRequest.java
│ │ │ │ ├── AuthorDtoForOneEntity.java
│ │ │ │ ├── UserPasswordDto.java
│ │ │ │ ├── AuthorUpdateDto.java
│ │ │ │ ├── UserDto.java
│ │ │ │ ├── StudentDtoForOneEntity.java
│ │ │ │ ├── AuthorDto.java
│ │ │ │ ├── BookDtoForOneEntity.java
│ │ │ │ ├── AuthorOneDto.java
│ │ │ │ ├── StudenPatchtDto.java
│ │ │ │ ├── BookUpdateDto.java
│ │ │ │ ├── BookOneDto.java
│ │ │ │ ├── BookDto.java
│ │ │ │ ├── StudentDto.java
│ │ │ │ └── StudentOneDto.java
│ │ │ │ ├── repository
│ │ │ │ ├── StudentRepository.java
│ │ │ │ ├── BookRepository.java
│ │ │ │ ├── AuthorRepository.java
│ │ │ │ └── UserRepository.java
│ │ │ │ ├── exception
│ │ │ │ ├── ExceptionResponse.java
│ │ │ │ └── IMExceptionHandler.java
│ │ │ │ ├── util
│ │ │ │ ├── ApiPaths.java
│ │ │ │ └── TPage.java
│ │ │ │ ├── security
│ │ │ │ ├── JwtAuthenticationEntryPoint.java
│ │ │ │ ├── SecurityConfig.java
│ │ │ │ ├── JwtTokenUtil.java
│ │ │ │ └── JwtAuthenticationFilter.java
│ │ │ │ ├── service
│ │ │ │ ├── BookService.java
│ │ │ │ ├── AuthorService.java
│ │ │ │ ├── StudentService.java
│ │ │ │ └── imp
│ │ │ │ │ ├── UserDetailsServiceImpl.java
│ │ │ │ │ ├── AuthorServiceImp.java
│ │ │ │ │ ├── UserServiceImp.java
│ │ │ │ │ └── BookServiceImp.java
│ │ │ │ ├── LibraryApplication.java
│ │ │ │ └── api
│ │ │ │ ├── UserController.java
│ │ │ │ ├── MainController.java
│ │ │ │ ├── AuthorRestController.java
│ │ │ │ ├── BookRestController.java
│ │ │ │ └── StudentRestController.java
│ │ └── resources
│ │ │ ├── application.properties
│ │ │ └── application-docker.properties
│ └── test
│ │ └── java
│ │ └── com
│ │ └── example
│ │ └── demo
│ │ └── LibraryApplicationTests.java
├── Dockerfile
├── .gitignore
└── pom.xml
├── docker-compose.yml
└── README.md
/library-webui/src/assets/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/app.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/.dockerignore:
--------------------------------------------------------------------------------
1 | dist
2 | node_modules
--------------------------------------------------------------------------------
/library-webui/src/app/login/login.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/main/main.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/register/register.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/book/book.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/header/header.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/header/header.component.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/student.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/shared/notfound/notfound.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/get-book/get-book.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/user-detail/user-detail.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/book/book-details/book-details.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/author/author-detail/author-detail.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/student-details/student-details.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/author/author.component.css:
--------------------------------------------------------------------------------
1 | .modal-dialog{
2 | width: 90%;
3 | }
--------------------------------------------------------------------------------
/library-webui/src/environments/environment.prod.ts:
--------------------------------------------------------------------------------
1 | export const environment = {
2 | production: true
3 | };
4 |
--------------------------------------------------------------------------------
/library-webui/src/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/celalaygar/Library-Application/HEAD/library-webui/src/favicon.ico
--------------------------------------------------------------------------------
/library-webui/src/styles.css:
--------------------------------------------------------------------------------
1 | /* You can add global styles to this file, and also import other style files */
2 | @import '~bootstrap/dist/css/bootstrap.min.css';
--------------------------------------------------------------------------------
/Library-Application/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/celalaygar/Library-Application/HEAD/Library-Application/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Library-Application/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
2 |
--------------------------------------------------------------------------------
/library-webui/src/app/shared/notfound/notfound.component.html:
--------------------------------------------------------------------------------
1 |
2 |
Page Not Found !! 404
3 | OHHHHHHHH NOOOO !!!! This page what you searched was not found !!!
4 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/model/BookStatus.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.model;
2 |
3 | public enum BookStatus {
4 | USED,
5 | FREE,
6 | NOTPUBLISHED,
7 | PUBLISHED
8 | }
9 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/user-detail/User.ts:
--------------------------------------------------------------------------------
1 | export class User {
2 | public username: string;
3 | public firstname: string;
4 | public email: string;
5 | public lastname: string;
6 | constructor() { }
7 | }
--------------------------------------------------------------------------------
/library-webui/src/app/shared/Page.ts:
--------------------------------------------------------------------------------
1 | export class Page {
2 | size = 0;
3 | totalElements = 0;
4 | totalPages = 0;
5 | page = 0;
6 | constructor() {
7 | this.page = 0;
8 | this.size = 10;
9 | }
10 | }
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/author/Author.ts:
--------------------------------------------------------------------------------
1 | export class Author {
2 | id: number;
3 | public name: string;
4 | public surname: string;
5 | public email: string;
6 | public phone: string;
7 | public about: string;
8 | constructor() { }
9 | }
--------------------------------------------------------------------------------
/Library-Application/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM openjdk:8-jdk-alpine
2 | LABEL maintainer="Ramazan Sakin "
3 |
4 | # Add JAR file and run it as entrypoint
5 | ADD target/*.jar app.jar
6 | ENTRYPOINT ["java", "-jar", "/app.jar"]
7 |
8 | # Expose the port
9 | EXPOSE 8182
--------------------------------------------------------------------------------
/library-webui/src/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import { Component } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-root',
5 | templateUrl: './app.component.html',
6 | styleUrls: ['./app.component.css']
7 | })
8 | export class AppComponent {
9 | title = 'library-webui';
10 | }
11 |
--------------------------------------------------------------------------------
/library-webui/e2e/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/e2e",
5 | "module": "commonjs",
6 | "target": "es5",
7 | "types": [
8 | "jasmine",
9 | "jasminewd2",
10 | "node"
11 | ]
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/library-webui/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "./out-tsc/app",
5 | "types": []
6 | },
7 | "include": [
8 | "src/**/*.ts"
9 | ],
10 | "exclude": [
11 | "src/test.ts",
12 | "src/**/*.spec.ts"
13 | ]
14 | }
15 |
--------------------------------------------------------------------------------
/library-webui/e2e/src/app.po.ts:
--------------------------------------------------------------------------------
1 | import { browser, by, element } from 'protractor';
2 |
3 | export class AppPage {
4 | navigateTo() {
5 | return browser.get(browser.baseUrl) as Promise;
6 | }
7 |
8 | getTitleText() {
9 | return element(by.css('app-root h1')).getText() as Promise;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/library-webui/.editorconfig:
--------------------------------------------------------------------------------
1 | # Editor configuration, see https://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | max_line_length = off
13 | trim_trailing_whitespace = false
14 |
--------------------------------------------------------------------------------
/library-webui/nginx.conf:
--------------------------------------------------------------------------------
1 | events{}
2 |
3 | http {
4 |
5 | include /etc/nginx/mime.types;
6 |
7 | server {
8 | listen 80;
9 | server_name localhost;
10 | root /usr/share/nginx/html;
11 | index index.html;
12 |
13 | location / {
14 | try_files $uri $uri/ /index.html;
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/library-webui/src/app/common/header/header.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-header',
5 | templateUrl: './header.component.html',
6 | styleUrls: ['./header.component.css']
7 | })
8 | export class HeaderComponent implements OnInit {
9 |
10 | constructor() { }
11 |
12 | ngOnInit() { }
13 | }
14 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/book/Book.ts:
--------------------------------------------------------------------------------
1 | import { Author } from '../author/Author';
2 |
3 | export class Book {
4 | public id: number;
5 | public name: string;
6 | public publisher: string;
7 | public bookStatus: string;
8 | public content: string;
9 | public barcode: string;
10 | public author = new Author();
11 | constructor() { }
12 | }
--------------------------------------------------------------------------------
/library-webui/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "./out-tsc/spec",
5 | "types": [
6 | "jasmine",
7 | "node"
8 | ]
9 | },
10 | "files": [
11 | "src/test.ts",
12 | "src/polyfills.ts"
13 | ],
14 | "include": [
15 | "src/**/*.spec.ts",
16 | "src/**/*.d.ts"
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/library-webui/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | LibraryWebui
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/Student.ts:
--------------------------------------------------------------------------------
1 | export class Student {
2 | public id: number;
3 | public fullname: string;
4 | public tcNo: string;
5 | public email: string;
6 | public phone: string;
7 | public city: string;
8 | public university: string;
9 | public department: string;
10 | public address: string;
11 | constructor() { }
12 | }
--------------------------------------------------------------------------------
/library-webui/src/app/shared/notfound/notfound.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-notfound',
5 | templateUrl: './notfound.component.html',
6 | styleUrls: ['./notfound.component.css']
7 | })
8 | export class NotfoundComponent implements OnInit {
9 |
10 | constructor() { }
11 |
12 | ngOnInit() { }
13 | }
14 |
--------------------------------------------------------------------------------
/library-webui/src/app/services/book.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed } from '@angular/core/testing';
2 |
3 | import { BookService } from './book.service';
4 |
5 | describe('BookService', () => {
6 | beforeEach(() => TestBed.configureTestingModule({}));
7 |
8 | it('should be created', () => {
9 | const service: BookService = TestBed.get(BookService);
10 | expect(service).toBeTruthy();
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/library-webui/src/app/services/general/api.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed } from '@angular/core/testing';
2 |
3 | import { ApiService } from './api.service';
4 |
5 | describe('ApiService', () => {
6 | beforeEach(() => TestBed.configureTestingModule({}));
7 |
8 | it('should be created', () => {
9 | const service: ApiService = TestBed.get(ApiService);
10 | expect(service).toBeTruthy();
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/library-webui/src/app/services/user.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed } from '@angular/core/testing';
2 |
3 | import { UserService } from './user.service';
4 |
5 | describe('UserService', () => {
6 | beforeEach(() => TestBed.configureTestingModule({}));
7 |
8 | it('should be created', () => {
9 | const service: UserService = TestBed.get(UserService);
10 | expect(service).toBeTruthy();
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/TokenResponse.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Getter;
5 | import lombok.NoArgsConstructor;
6 | import lombok.Setter;
7 |
8 | @NoArgsConstructor
9 | @AllArgsConstructor
10 | @Getter
11 | @Setter
12 | public class TokenResponse {
13 |
14 | private String username;
15 |
16 | private String token;
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/library-webui/src/app/services/author.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed } from '@angular/core/testing';
2 |
3 | import { AuthorService } from './author.service';
4 |
5 | describe('AuthorService', () => {
6 | beforeEach(() => TestBed.configureTestingModule({}));
7 |
8 | it('should be created', () => {
9 | const service: AuthorService = TestBed.get(AuthorService);
10 | expect(service).toBeTruthy();
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/library-webui/src/app/services/student.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed } from '@angular/core/testing';
2 |
3 | import { StudentService } from './student.service';
4 |
5 | describe('StudentService', () => {
6 | beforeEach(() => TestBed.configureTestingModule({}));
7 |
8 | it('should be created', () => {
9 | const service: StudentService = TestBed.get(StudentService);
10 | expect(service).toBeTruthy();
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/library-webui/Dockerfile:
--------------------------------------------------------------------------------
1 | ### STAGE 1: Build ###
2 | FROM node:12.7-alpine AS build
3 | LABEL maintainer="Ramazan Sakin "
4 | WORKDIR /usr/src/app
5 | COPY package.json package-lock.json ./
6 | RUN npm install
7 | COPY . .
8 | RUN npm run build
9 |
10 | ### STAGE 2: Run ###
11 | FROM nginx:1.17.1-alpine
12 | COPY nginx.conf /etc/nginx/nginx.conf
13 | COPY --from=build /usr/src/app/dist/library-webui /usr/share/nginx/html
--------------------------------------------------------------------------------
/library-webui/src/main.ts:
--------------------------------------------------------------------------------
1 | import { enableProdMode } from '@angular/core';
2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
3 |
4 | import { AppModule } from './app/app.module';
5 | import { environment } from './environments/environment';
6 |
7 | if (environment.production) {
8 | enableProdMode();
9 | }
10 |
11 | platformBrowserDynamic().bootstrapModule(AppModule)
12 | .catch(err => console.error(err));
13 |
--------------------------------------------------------------------------------
/library-webui/src/app/services/alertify.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed } from '@angular/core/testing';
2 |
3 | import { AlertifyService } from './alertify.service';
4 |
5 | describe('AlertifyService', () => {
6 | beforeEach(() => TestBed.configureTestingModule({}));
7 |
8 | it('should be created', () => {
9 | const service: AlertifyService = TestBed.get(AlertifyService);
10 | expect(service).toBeTruthy();
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/main/main.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-main',
5 | templateUrl: './main.component.html',
6 | styleUrls: ['./main.component.css']
7 | })
8 | export class MainComponent implements OnInit {
9 |
10 | currentUser = {};
11 | constructor() { }
12 |
13 | ngOnInit() { this.currentUser = JSON.parse(localStorage.getItem('currentUser')); }
14 | }
15 |
--------------------------------------------------------------------------------
/Library-Application/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | /target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 |
5 | ### STS ###
6 | .apt_generated
7 | .classpath
8 | .factorypath
9 | .project
10 | .settings
11 | .springBeans
12 | .sts4-cache
13 |
14 | ### IntelliJ IDEA ###
15 | .idea
16 | *.iws
17 | *.iml
18 | *.ipr
19 |
20 | ### NetBeans ###
21 | /nbproject/private/
22 | /nbbuild/
23 | /dist/
24 | /nbdist/
25 | /.nb-gradle/
26 | /build/
27 |
28 | ### VS Code ###
29 | .vscode/
30 |
--------------------------------------------------------------------------------
/library-webui/browserslist:
--------------------------------------------------------------------------------
1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
2 | # For additional information regarding the format and rule options, please see:
3 | # https://github.com/browserslist/browserslist#queries
4 |
5 | # You can see what browsers were selected by your queries by running:
6 | # npx browserslist
7 |
8 | > 0.5%
9 | last 2 versions
10 | Firefox ESR
11 | not dead
12 | not IE 9-11 # For IE 9-11 support, remove 'not'.
--------------------------------------------------------------------------------
/Library-Application/src/test/java/com/example/demo/LibraryApplicationTests.java:
--------------------------------------------------------------------------------
1 | //package com.example.demo;
2 | //
3 | //import org.junit.Test;
4 | //import org.junit.runner.RunWith;
5 | //import org.springframework.boot.test.context.SpringBootTest;
6 | //import org.springframework.test.context.junit4.SpringRunner;
7 | //
8 | //@RunWith(SpringRunner.class)
9 | //@SpringBootTest
10 | //public class LibraryApplicationTests {
11 | //
12 | // @Test
13 | // public void contextLoads() {
14 | // }
15 | //
16 | //}
17 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/LoginRequest.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import javax.persistence.Column;
4 |
5 | import lombok.AllArgsConstructor;
6 | import lombok.Getter;
7 | import lombok.NoArgsConstructor;
8 | import lombok.Setter;
9 | import lombok.ToString;
10 |
11 | @NoArgsConstructor
12 | @AllArgsConstructor
13 | @Getter
14 | @Setter
15 | @ToString
16 | public class LoginRequest {
17 |
18 | private String username;
19 |
20 | private String password;
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/Library-Application/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=8182
2 |
3 | spring.datasource.url=jdbc:postgresql://localhost:5432/library
4 | spring.datasource.username=postgres
5 | spring.datasource.password=celal371
6 |
7 | spring.jpa.hibernate.ddl-auto=update
8 | spring.jpa.generate-ddl=true
9 | spring.datasource.driver-class-name=org.postgresql.Driver
10 | spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
11 |
12 | spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
13 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/repository/StudentRepository.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.repository;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 |
8 | import com.example.demo.model.Book;
9 | import com.example.demo.model.Student;
10 |
11 | public interface StudentRepository extends JpaRepository {
12 |
13 | List findByEmail(String email);
14 | List findByTcNo(String tcNo);
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/user-detail/user.routing.module.ts:
--------------------------------------------------------------------------------
1 | import {NgModule} from '@angular/core';
2 | import {RouterModule, Routes} from '@angular/router';
3 | import { UserDetailComponent } from './user-detail.component';
4 |
5 | const routes: Routes = [
6 | {
7 | path: 'user-detail/:username', component: UserDetailComponent
8 | }
9 | ];
10 |
11 | @NgModule({
12 | imports: [RouterModule.forChild(routes)],
13 | exports: [RouterModule]
14 | })
15 | // tslint:disable-next-line:eofline
16 | export class UserRoutingModule {}
--------------------------------------------------------------------------------
/Library-Application/src/main/resources/application-docker.properties:
--------------------------------------------------------------------------------
1 | server.port=8182
2 |
3 | spring.datasource.url=jdbc:postgresql://${DB_SERVER}/${POSTGRES_DB}
4 | spring.datasource.username=${POSTGRES_USER}
5 | spring.datasource.password=${POSTGRES_PASSWORD}
6 |
7 | spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
8 | spring.datasource.driver-class-name=org.postgresql.Driver
9 | spring.jpa.hibernate.ddl-auto=update
10 | spring.jpa.generate-ddl=true
11 | spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
--------------------------------------------------------------------------------
/library-webui/src/app/services/alertify.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 |
3 | declare let alertify: any;
4 | @Injectable({
5 | providedIn: 'root'
6 | })
7 | export class AlertifyService {
8 |
9 | constructor() { }
10 |
11 | success( message: string ){
12 | alertify.success( message );
13 | }
14 | warning( message: string ){
15 | alertify.warning( message );
16 | }
17 | error( message: string ){
18 | alertify.error( message );
19 | }
20 | message( message: string ){
21 | alertify.message( message );
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/RegistirationRequest.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import javax.persistence.Column;
4 | import lombok.AllArgsConstructor;
5 | import lombok.Getter;
6 | import lombok.NoArgsConstructor;
7 | import lombok.Setter;
8 |
9 | @NoArgsConstructor
10 | @AllArgsConstructor
11 | @Getter
12 | @Setter
13 | public class RegistirationRequest {
14 |
15 | private String username;
16 |
17 | private String password;
18 |
19 | private String firstname;
20 |
21 | private String lastname;
22 |
23 | private String email;
24 | }
25 |
--------------------------------------------------------------------------------
/library-webui/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compileOnSave": false,
3 | "compilerOptions": {
4 | "baseUrl": "./",
5 | "outDir": "./dist/out-tsc",
6 | "sourceMap": true,
7 | "declaration": false,
8 | "downlevelIteration": true,
9 | "emitDecoratorMetadata": true,
10 | "experimentalDecorators": true,
11 | "module": "esnext",
12 | "moduleResolution": "node",
13 | "importHelpers": true,
14 | "target": "es2015",
15 | "typeRoots": [
16 | "node_modules/@types"
17 | ],
18 | "lib": [
19 | "es2018",
20 | "dom"
21 | ]
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/repository/BookRepository.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.repository;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 | import org.springframework.data.jpa.repository.Query;
7 |
8 | import com.example.demo.model.Author;
9 | import com.example.demo.model.Book;
10 |
11 | public interface BookRepository extends JpaRepository {
12 |
13 | List findByName(String name);
14 |
15 | @Query("select b from Book b where b.name like %:name%")
16 | List SearchBooksByName(String name);
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/book/book.routing.module.ts:
--------------------------------------------------------------------------------
1 | import {NgModule} from '@angular/core';
2 | import {RouterModule, Routes} from '@angular/router';
3 | import { BookComponent } from './book.component';
4 | import { BookDetailsComponent } from './book-details/book-details.component';
5 |
6 | const routes: Routes = [
7 | {
8 | path: '', component: BookComponent
9 | },
10 | {
11 | path: 'book-detail/:id', component: BookDetailsComponent
12 | }
13 | ];
14 |
15 | @NgModule({
16 | imports: [RouterModule.forChild(routes)],
17 | exports: [RouterModule]
18 | })
19 | export class BookRoutingModule {}
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/repository/AuthorRepository.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.repository;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 | import org.springframework.data.jpa.repository.Query;
7 |
8 | import com.example.demo.model.Author;
9 |
10 | public interface AuthorRepository extends JpaRepository {
11 |
12 | Author findByEmail(String email);
13 |
14 | @Query("select a from Author a where a.name like %:name% or a.surname like %:surname%")
15 | List findByNameOrSurname(String name, String surname);
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/author/author.routing.module.ts:
--------------------------------------------------------------------------------
1 | import {NgModule} from '@angular/core';
2 | import {RouterModule, Routes} from '@angular/router';
3 | import { AuthorComponent } from './author.component';
4 | import { AuthorDetailComponent } from './author-detail/author-detail.component';
5 |
6 | const routes: Routes = [
7 | {
8 | path: '', component: AuthorComponent
9 | },
10 | {
11 | path: 'author-detail/:id', component: AuthorDetailComponent
12 | }
13 | ];
14 |
15 | @NgModule({
16 | imports: [RouterModule.forChild(routes)],
17 | exports: [RouterModule]
18 | })
19 | export class AuthorRoutingModule {}
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/AuthorDtoForOneEntity.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import java.util.List;
4 |
5 | import javax.validation.constraints.NotNull;
6 |
7 | import lombok.Data;
8 | import lombok.Getter;
9 | import lombok.NoArgsConstructor;
10 | import lombok.Setter;
11 |
12 | @Getter
13 | @Setter
14 | @Data
15 | @NoArgsConstructor
16 | public class AuthorDtoForOneEntity {
17 | private Long id;
18 |
19 | @NotNull
20 | private String name;
21 |
22 | @NotNull
23 | private String surname;
24 |
25 | private String email;
26 |
27 | private String phone;
28 |
29 | private String about;
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/main/main.component.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Kütüphane uygulaması
4 |
5 |
6 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/library-webui/src/app/security/auth.guard.ts:
--------------------------------------------------------------------------------
1 | import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
2 | import {Injectable} from '@angular/core';
3 |
4 | @Injectable({ providedIn: 'root' })
5 | export class AuthGuard implements CanActivate {
6 |
7 | constructor(private router: Router) { }
8 |
9 | // localstorage de user ımızın olup olmadıgını kontrol edıyor..
10 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
11 | if (localStorage.getItem('currentUser')) {
12 | return true;
13 | }
14 | //this.router.navigate(['/login']);
15 | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
16 | return false;
17 | }
18 | }
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/repository/UserRepository.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.repository;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 | import org.springframework.data.jpa.repository.Query;
8 | import org.springframework.data.repository.query.Param;
9 |
10 | import com.example.demo.model.User;
11 |
12 | public interface UserRepository extends JpaRepository {
13 |
14 | List findByEmail(String email);
15 |
16 | @Query("select u from User u where u.username like %:username%")
17 | List getByUsername(@Param("username") String username);
18 |
19 | User findByUsername(String username);
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/library-webui/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 |
3 | import 'zone.js/dist/zone-testing';
4 | import { getTestBed } from '@angular/core/testing';
5 | import {
6 | BrowserDynamicTestingModule,
7 | platformBrowserDynamicTesting
8 | } from '@angular/platform-browser-dynamic/testing';
9 |
10 | declare const require: any;
11 |
12 | // First, initialize the Angular testing environment.
13 | getTestBed().initTestEnvironment(
14 | BrowserDynamicTestingModule,
15 | platformBrowserDynamicTesting()
16 | );
17 | // Then we find all the tests.
18 | const context = require.context('./', true, /\.spec\.ts$/);
19 | // And load the modules.
20 | context.keys().map(context);
21 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/UserPasswordDto.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.Index;
9 | import javax.persistence.Table;
10 | import javax.validation.constraints.NotNull;
11 |
12 | import lombok.Data;
13 | import lombok.Getter;
14 | import lombok.NoArgsConstructor;
15 | import lombok.Setter;
16 |
17 | @Getter
18 | @Setter
19 | @NoArgsConstructor
20 | @Data
21 | public class UserPasswordDto {
22 |
23 | private String username;
24 |
25 | private String password;
26 | private String newpassword;
27 |
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/exception/ExceptionResponse.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.exception;
2 |
3 | import java.util.Date;
4 |
5 | public class ExceptionResponse {
6 |
7 | private Date date;
8 | private String message;
9 |
10 | public ExceptionResponse() {
11 | super();
12 | }
13 |
14 | public ExceptionResponse(Date date, String message) {
15 | super();
16 | this.date = date;
17 | this.message = message;
18 | }
19 |
20 | public Date getDate() {
21 | return date;
22 | }
23 |
24 | public void setDate(Date date) {
25 | this.date = date;
26 | }
27 |
28 | public String getMessage() {
29 | return message;
30 | }
31 |
32 | public void setMessage(String message) {
33 | this.message = message;
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/library-webui/e2e/src/app.e2e-spec.ts:
--------------------------------------------------------------------------------
1 | import { AppPage } from './app.po';
2 | import { browser, logging } from 'protractor';
3 |
4 | describe('workspace-project App', () => {
5 | let page: AppPage;
6 |
7 | beforeEach(() => {
8 | page = new AppPage();
9 | });
10 |
11 | it('should display welcome message', () => {
12 | page.navigateTo();
13 | expect(page.getTitleText()).toEqual('Welcome to library-webui!');
14 | });
15 |
16 | afterEach(async () => {
17 | // Assert that there are no errors emitted from the browser
18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER);
19 | expect(logs).not.toContain(jasmine.objectContaining({
20 | level: logging.Level.SEVERE,
21 | } as logging.Entry));
22 | });
23 | });
24 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/main/main.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { MainComponent } from './main.component';
4 |
5 | describe('MainComponent', () => {
6 | let component: MainComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ MainComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(MainComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/library-webui/src/app/login/login.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { LoginComponent } from './login.component';
4 |
5 | describe('LoginComponent', () => {
6 | let component: LoginComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ LoginComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(LoginComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/book/book.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { BookComponent } from './book.component';
4 |
5 | describe('BookComponent', () => {
6 | let component: BookComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ BookComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(BookComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/AuthorUpdateDto.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.Table;
9 | import javax.validation.constraints.NotNull;
10 |
11 | import lombok.Data;
12 | import lombok.Getter;
13 | import lombok.Setter;
14 |
15 | @Getter
16 | @Setter
17 | @Data
18 | public class AuthorUpdateDto {
19 |
20 | private Long id;
21 |
22 | @NotNull
23 | private String name;
24 |
25 | @NotNull
26 | private String surname;
27 |
28 | private String about;
29 |
30 | private String email;
31 |
32 | private String phone;
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/author/author.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { AuthorComponent } from './author.component';
4 |
5 | describe('AuthorComponent', () => {
6 | let component: AuthorComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ AuthorComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(AuthorComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/header/header.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { HeaderComponent } from './header.component';
4 |
5 | describe('HeaderComponent', () => {
6 | let component: HeaderComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ HeaderComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(HeaderComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/util/ApiPaths.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.util;
2 |
3 | public final class ApiPaths {
4 |
5 | private static final String BASE_PATH = "/api";
6 |
7 | public static final class MainCtrl {
8 | public static final String CTRL = BASE_PATH + "/main";
9 | }
10 |
11 | public static final class BookCtrl {
12 | public static final String CTRL = BASE_PATH + "/book";
13 | }
14 |
15 | public static final class AuthorCtrl {
16 | public static final String CTRL = BASE_PATH + "/author";
17 | }
18 |
19 | public static final class UserCtrl {
20 | public static final String CTRL = BASE_PATH + "/user";
21 | }
22 |
23 | public static final class StudentCtrl {
24 | public static final String CTRL = BASE_PATH + "/student";
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/student.routing.module.ts:
--------------------------------------------------------------------------------
1 | import {NgModule} from '@angular/core';
2 | import {RouterModule, Routes} from '@angular/router';
3 | import { StudentComponent } from './student.component';
4 | import { StudentDetailsComponent } from './student-details/student-details.component';
5 | import { GetBookComponent } from './get-book/get-book.component';
6 |
7 | const routes: Routes = [
8 | {
9 | path: '', component: StudentComponent
10 | },
11 | {
12 | path: 'student-detail/:id', component: StudentDetailsComponent
13 | },
14 | {
15 | path: 'get-book/:id', component: GetBookComponent
16 | }
17 | ];
18 |
19 | @NgModule({
20 | imports: [RouterModule.forChild(routes)],
21 | exports: [RouterModule]
22 | })
23 | export class StudentRoutingModule {}
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/user-detail/user.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { CommonModule } from '@angular/common';
3 | import { UserDetailComponent } from './user-detail.component';
4 | import { UserRoutingModule } from './user.routing.module';
5 | import { UserService } from 'src/app/services/user.service';
6 | import { FormsModule, ReactiveFormsModule } from '@angular/forms';
7 | import { AlertifyService } from 'src/app/services/alertify.service';
8 |
9 | @NgModule({
10 | declarations: [UserDetailComponent],
11 | imports: [
12 | CommonModule,
13 | UserRoutingModule,
14 | FormsModule,
15 | ReactiveFormsModule
16 | ],
17 | providers : [
18 | UserService,
19 | AlertifyService
20 | ]
21 | })
22 | export class UserModule { }
23 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/UserDto.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.Index;
9 | import javax.persistence.Table;
10 | import javax.validation.constraints.NotNull;
11 |
12 | import lombok.Data;
13 | import lombok.Getter;
14 | import lombok.NoArgsConstructor;
15 | import lombok.Setter;
16 |
17 | @Getter
18 | @Setter
19 | @NoArgsConstructor
20 | @Data
21 | public class UserDto {
22 |
23 | private String username;
24 |
25 | private String firstname;
26 |
27 | private String lastname;
28 |
29 | @NotNull
30 | private String email;
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/student.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { StudentComponent } from './student.component';
4 |
5 | describe('StudentComponent', () => {
6 | let component: StudentComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ StudentComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(StudentComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/library-webui/src/app/register/register.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { RegisterComponent } from './register.component';
4 |
5 | describe('RegisterComponent', () => {
6 | let component: RegisterComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ RegisterComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(RegisterComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/library-webui/src/app/security/jwt.interceptor.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
3 | import { Observable } from 'rxjs';
4 |
5 | @Injectable()
6 | export class JwtInterceptor implements HttpInterceptor {
7 |
8 | intercept(request: HttpRequest, next: HttpHandler): Observable> {
9 |
10 | // add authorization header with jwt token if available
11 | let currentUser = JSON.parse(localStorage.getItem('currentUser'));
12 | if (currentUser && currentUser.token) {
13 | request = request.clone({
14 | setHeaders: {
15 | Authorization: `Bearer ${currentUser.token}`
16 | }
17 | });
18 | }
19 | return next.handle(request);
20 | }
21 | }
--------------------------------------------------------------------------------
/library-webui/src/app/shared/notfound/notfound.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { NotfoundComponent } from './notfound.component';
4 |
5 | describe('NotfoundComponent', () => {
6 | let component: NotfoundComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ NotfoundComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(NotfoundComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/get-book/get-book.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { GetBookComponent } from './get-book.component';
4 |
5 | describe('GetBookComponent', () => {
6 | let component: GetBookComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ GetBookComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(GetBookComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/library-webui/src/environments/environment.ts:
--------------------------------------------------------------------------------
1 | // This file can be replaced during build by using the `fileReplacements` array.
2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
3 | // The list of file replacements can be found in `angular.json`.
4 |
5 | export const environment = {
6 | production: false,
7 | API_BASE_PATH: 'http://localhost:8182/api',
8 | };
9 |
10 | /*
11 | * For easier debugging in development mode, you can import the following file
12 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
13 | *
14 | * This import should be commented out in production mode because it will have a negative impact
15 | * on performance if an error is thrown.
16 | */
17 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI.
18 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/StudentDtoForOneEntity.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import java.util.List;
4 |
5 | import javax.validation.constraints.NotNull;
6 |
7 | import com.example.demo.model.City;
8 |
9 | import lombok.Data;
10 | import lombok.Getter;
11 | import lombok.NoArgsConstructor;
12 | import lombok.Setter;
13 |
14 | @Getter
15 | @Setter
16 | @NoArgsConstructor
17 | @Data
18 | public class StudentDtoForOneEntity {
19 |
20 | private Long id;
21 |
22 | private String tcNo;
23 |
24 | @NotNull
25 | private String fullname;
26 |
27 | private String university;
28 |
29 | private String department;
30 |
31 | @NotNull
32 | private String email;
33 |
34 | @NotNull
35 | private String phone;
36 |
37 | private String address;
38 |
39 | private City city;
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/user-detail/user-detail.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { UserDetailComponent } from './user-detail.component';
4 |
5 | describe('UserDetailComponent', () => {
6 | let component: UserDetailComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ UserDetailComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(UserDetailComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/book/book-details/book-details.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { BookDetailsComponent } from './book-details.component';
4 |
5 | describe('BookDetailsComponent', () => {
6 | let component: BookDetailsComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ BookDetailsComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(BookDetailsComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/author/author-detail/author-detail.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { AuthorDetailComponent } from './author-detail.component';
4 |
5 | describe('AuthorDetailComponent', () => {
6 | let component: AuthorDetailComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ AuthorDetailComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(AuthorDetailComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/AuthorDto.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import java.util.List;
4 |
5 | import javax.persistence.Column;
6 | import javax.persistence.Entity;
7 | import javax.persistence.GeneratedValue;
8 | import javax.persistence.GenerationType;
9 | import javax.persistence.Id;
10 | import javax.persistence.Table;
11 | import javax.validation.constraints.NotNull;
12 |
13 | import lombok.Data;
14 | import lombok.Getter;
15 | import lombok.Setter;
16 |
17 | @Getter
18 | @Setter
19 | @Data
20 | public class AuthorDto {
21 |
22 | private Long id;
23 |
24 | @NotNull
25 | private String name;
26 |
27 | @NotNull
28 | private String surname;
29 |
30 | private String about;
31 |
32 | private String email;
33 |
34 | private String phone;
35 |
36 | private List books;
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/library-webui/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 | # Only exists if Bazel was run
8 | /bazel-out
9 |
10 | # dependencies
11 | /node_modules
12 |
13 | # profiling files
14 | chrome-profiler-events.json
15 | speed-measure-plugin.json
16 |
17 | # IDEs and editors
18 | /.idea
19 | .project
20 | .classpath
21 | .c9/
22 | *.launch
23 | .settings/
24 | *.sublime-workspace
25 |
26 | # IDE - VSCode
27 | .vscode/*
28 | !.vscode/settings.json
29 | !.vscode/tasks.json
30 | !.vscode/launch.json
31 | !.vscode/extensions.json
32 | .history/*
33 |
34 | # misc
35 | /.sass-cache
36 | /connect.lock
37 | /coverage
38 | /libpeerconnection.log
39 | npm-debug.log
40 | yarn-error.log
41 | testem.log
42 | /typings
43 |
44 | # System Files
45 | .DS_Store
46 | Thumbs.db
47 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/BookDtoForOneEntity.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import java.util.List;
4 |
5 | import javax.validation.constraints.NotNull;
6 |
7 | import com.example.demo.model.BookStatus;
8 |
9 | import lombok.Data;
10 | import lombok.Getter;
11 | import lombok.NoArgsConstructor;
12 | import lombok.Setter;
13 |
14 | @Getter
15 | @Setter
16 | @NoArgsConstructor
17 | @Data
18 | public class BookDtoForOneEntity {
19 |
20 | private Long id;
21 |
22 | @NotNull
23 | private String name;
24 |
25 | @NotNull
26 | private String barcode;
27 |
28 | private String content;
29 |
30 | @NotNull
31 | private String publisher;
32 |
33 | private BookStatus bookStatus;
34 |
35 | private StudentDtoForOneEntity student;
36 |
37 | @NotNull
38 | private Long authorId;
39 |
40 | private Long studentId;
41 | }
42 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/student-details/student-details.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { StudentDetailsComponent } from './student-details.component';
4 |
5 | describe('StudentDetailsComponent', () => {
6 | let component: StudentDetailsComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ StudentDetailsComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(StudentDetailsComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/model/City.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.model;
2 |
3 | public enum City {
4 | ADANA,
5 | ANKARA,
6 | ANTALYA,
7 | AMASYA,
8 | AĞRI,
9 | ADIYAMAN,
10 | BARTIN,
11 | BOLU,
12 | BALIKESIR,
13 | BITLIS,
14 | BURSA,
15 | ÇANAKKALE,
16 | ÇORUM,
17 | ÇANKIRI,
18 | DENIZLI,
19 | DİYARBAKIR,
20 | EDIRNE,
21 | ELAZIĞ,
22 | ERZURUM,
23 | ESKIŞEHIR,
24 | ERZINCAN,
25 | GAZİANTEP,
26 | GİRESUN,
27 | HAKKARİ,
28 | HATAY,
29 | İSTANBUL,
30 | İZMİR,
31 | ISPARTA,
32 | KARS,
33 | KASTAMONU,
34 | KAYSERİ,
35 | KIRŞEHİR,
36 | KARAMAN,
37 | MARDİN,
38 | MANİSA,
39 | MUĞLA,
40 | MUŞ,
41 | ORDU,
42 | OSMANİYE,
43 | SİVAS,
44 | SAKARYA,
45 | SAMSUN,
46 | ŞIRNAK,
47 | ŞANLIURFA,
48 | YALOVA,
49 | YOZGAT,
50 | ZONGULDAK
51 | }
52 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/security/JwtAuthenticationEntryPoint.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.security;
2 |
3 | import java.io.IOException;
4 | import java.io.Serializable;
5 |
6 | import javax.servlet.ServletException;
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 |
10 | import org.springframework.security.core.AuthenticationException;
11 | import org.springframework.security.web.AuthenticationEntryPoint;
12 | import org.springframework.stereotype.Component;
13 |
14 | @Component
15 | public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
16 |
17 | @Override
18 | public void commence(HttpServletRequest request, HttpServletResponse response,
19 | AuthenticationException authException) throws IOException, ServletException {
20 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized1");
21 |
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/AuthorOneDto.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import java.util.List;
4 |
5 | import javax.persistence.Column;
6 | import javax.persistence.Entity;
7 | import javax.persistence.GeneratedValue;
8 | import javax.persistence.GenerationType;
9 | import javax.persistence.Id;
10 | import javax.persistence.Table;
11 | import javax.validation.constraints.NotNull;
12 |
13 | import com.example.demo.model.Book;
14 |
15 | import lombok.Data;
16 | import lombok.Getter;
17 | import lombok.NoArgsConstructor;
18 | import lombok.Setter;
19 |
20 | @Getter
21 | @Setter
22 | @Data
23 | @NoArgsConstructor
24 | public class AuthorOneDto {
25 |
26 | private Long id;
27 |
28 | @NotNull
29 | private String name;
30 |
31 | @NotNull
32 | private String surname;
33 |
34 | private String about;
35 |
36 | private String email;
37 |
38 | private String phone;
39 |
40 | private List books;
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/library-webui/e2e/protractor.conf.js:
--------------------------------------------------------------------------------
1 | // @ts-check
2 | // Protractor configuration file, see link for more information
3 | // https://github.com/angular/protractor/blob/master/lib/config.ts
4 |
5 | const { SpecReporter } = require('jasmine-spec-reporter');
6 |
7 | /**
8 | * @type { import("protractor").Config }
9 | */
10 | exports.config = {
11 | allScriptsTimeout: 11000,
12 | specs: [
13 | './src/**/*.e2e-spec.ts'
14 | ],
15 | capabilities: {
16 | 'browserName': 'chrome'
17 | },
18 | directConnect: true,
19 | baseUrl: 'http://localhost:4200/',
20 | framework: 'jasmine',
21 | jasmineNodeOpts: {
22 | showColors: true,
23 | defaultTimeoutInterval: 30000,
24 | print: function() {}
25 | },
26 | onPrepare() {
27 | require('ts-node').register({
28 | project: require('path').join(__dirname, './tsconfig.json')
29 | });
30 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
31 | }
32 | };
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '3'
2 | services:
3 | library-postgres:
4 | image: "postgres:9.6-alpine"
5 | container_name: library-postgres
6 | volumes:
7 | - library-data:/var/lib/postgresql/data
8 | ports:
9 | - "5432:5432"
10 | environment:
11 | - POSTGRES_DB=library
12 | - POSTGRES_USER=postgres
13 | - POSTGRES_PASSWORD=celal371
14 |
15 | library-app:
16 | build: ./Library-Application
17 | container_name: library-app
18 | environment:
19 | - DB_SERVER=library-postgres
20 | - POSTGRES_DB=library
21 | - POSTGRES_USER=postgres
22 | - POSTGRES_PASSWORD=celal371
23 | - spring.profiles.active=docker
24 | ports:
25 | - "8182:8182"
26 | links:
27 | - library-postgres
28 |
29 | library-ui:
30 | build: ./library-webui
31 | container_name: library-ui
32 | ports:
33 | - "3030:80"
34 | links:
35 | - library-app
36 |
37 | volumes:
38 | library-data:
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/service/BookService.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.domain.Pageable;
6 |
7 | import com.example.demo.dto.BookDto;
8 | import com.example.demo.dto.BookOneDto;
9 | import com.example.demo.dto.BookUpdateDto;
10 | import com.example.demo.util.TPage;
11 |
12 | import javassist.NotFoundException;
13 |
14 | public interface BookService {
15 | public BookOneDto save(BookOneDto bookOneDto) throws Exception;
16 | public List getAll() throws NotFoundException;
17 | public TPage getAllPageable(Pageable pageable) throws NotFoundException ;
18 | public BookUpdateDto update(Long id, BookUpdateDto bookUpdateDto) throws NotFoundException;
19 | public BookOneDto getOne(Long id) throws NotFoundException ;
20 | public Boolean delete(Long id) throws NotFoundException;
21 | public List SearchBooksByName(String name) throws NotFoundException;
22 | }
23 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/LibraryApplication.java:
--------------------------------------------------------------------------------
1 | package com.example.demo;
2 |
3 | import org.modelmapper.ModelMapper;
4 | import org.modelmapper.convention.MatchingStrategies;
5 | import org.springframework.boot.SpringApplication;
6 | import org.springframework.boot.autoconfigure.SpringBootApplication;
7 | import org.springframework.context.annotation.Bean;
8 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
9 |
10 | @SpringBootApplication
11 | public class LibraryApplication {
12 |
13 | public static void main(String[] args) {
14 | SpringApplication.run(LibraryApplication.class, args);
15 | }
16 | @Bean
17 | public ModelMapper getModelMapper() {
18 | ModelMapper modelmapper =new ModelMapper();
19 | modelmapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
20 | return modelmapper;
21 | }
22 | // @Bean
23 | // public BCryptPasswordEncoder bCryptPasswordEncoder() {
24 | // return new BCryptPasswordEncoder();
25 | // }
26 | }
27 |
--------------------------------------------------------------------------------
/library-webui/src/app/security/authentication.interceptor.ts:
--------------------------------------------------------------------------------
1 | import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
2 | import {Observable, throwError} from 'rxjs';
3 | import {Injectable} from '@angular/core';
4 | import {catchError} from 'rxjs/operators';
5 | import {AuthenticationService} from './authentication.service';
6 |
7 | @Injectable()
8 | export class ErrorInterceptor implements HttpInterceptor {
9 |
10 | constructor(private authenticationService: AuthenticationService) {}
11 |
12 | // gelen response nesnelerını kontrol eder. 401 olup olmadıgını kontrol eder
13 | intercept(request: HttpRequest, next: HttpHandler): Observable> {
14 | return next.handle(request).pipe(catchError(err => {
15 | if (err.status === 401) {
16 | this.authenticationService.logout();
17 | location.reload(true);
18 | }
19 | const error = err.error.message || err.statusText;
20 | return throwError(error);
21 | }))
22 | }
23 | }
--------------------------------------------------------------------------------
/library-webui/src/app/security/authentication.service.ts:
--------------------------------------------------------------------------------
1 | import {Injectable} from '@angular/core';
2 | import {HttpClient} from '@angular/common/http';
3 | import {map} from 'rxjs/operators';
4 | import { environment } from 'src/environments/environment';
5 |
6 | @Injectable({providedIn: 'root'})
7 | export class AuthenticationService {
8 | constructor(private http: HttpClient) {
9 | }
10 |
11 | login(username: string, password: string) {
12 | return this.http.post( environment.API_BASE_PATH + '/main/sign-in', {username, password})
13 | .pipe(map(user => {
14 | if (user && user.token) {
15 | localStorage.setItem('currentUser', JSON.stringify(user));
16 | }
17 | return user;
18 | }));
19 | }
20 | register(registerData) {
21 | return this.http.post( environment.API_BASE_PATH + '/main/sign-up', registerData)
22 | .pipe(map(resp => {
23 | return resp;
24 | }));
25 | }
26 | logout() {
27 | localStorage.removeItem('currentUser');
28 | }
29 | }
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/service/AuthorService.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.service;
2 |
3 | import java.util.List;
4 |
5 | import javax.validation.Valid;
6 |
7 | import org.springframework.data.domain.Pageable;
8 |
9 | import com.example.demo.dto.AuthorDto;
10 | import com.example.demo.dto.AuthorOneDto;
11 | import com.example.demo.dto.AuthorUpdateDto;
12 | import com.example.demo.util.TPage;
13 |
14 | import javassist.NotFoundException;
15 |
16 | public interface AuthorService {
17 | public AuthorDto save(AuthorDto authorDto);
18 | public List getAll() throws NotFoundException;
19 | public TPage getAllPageable(Pageable pageable) throws NotFoundException;
20 | public List findAllByName(String name) throws NotFoundException ;
21 | public AuthorUpdateDto update(Long id, @Valid AuthorUpdateDto authorUpdateDto) throws NotFoundException;
22 | public AuthorOneDto getOne(Long id) throws NotFoundException;
23 | public Boolean delete(Long id) throws NotFoundException ;
24 | }
25 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/StudenPatchtDto.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import java.util.List;
4 |
5 | import javax.persistence.CascadeType;
6 | import javax.persistence.Column;
7 | import javax.persistence.Entity;
8 | import javax.persistence.EnumType;
9 | import javax.persistence.Enumerated;
10 | import javax.persistence.FetchType;
11 | import javax.persistence.GeneratedValue;
12 | import javax.persistence.GenerationType;
13 | import javax.persistence.Id;
14 | import javax.persistence.OneToMany;
15 | import javax.persistence.OneToOne;
16 | import javax.persistence.SequenceGenerator;
17 | import javax.persistence.Table;
18 | import javax.validation.constraints.NotNull;
19 |
20 | import com.example.demo.model.Book;
21 | import com.example.demo.model.City;
22 |
23 | import lombok.Data;
24 | import lombok.Getter;
25 | import lombok.NoArgsConstructor;
26 | import lombok.Setter;
27 |
28 | @Getter
29 | @Setter
30 | @NoArgsConstructor
31 | @Data
32 | public class StudenPatchtDto {
33 |
34 | private Long id;
35 |
36 | private Long studentId;
37 |
38 | private Long bookId;
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/service/StudentService.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.service;
2 |
3 | import java.util.List;
4 |
5 | import javax.validation.Valid;
6 |
7 | import org.springframework.data.domain.Pageable;
8 |
9 | import com.example.demo.dto.StudenPatchtDto;
10 | import com.example.demo.dto.StudentDto;
11 | import com.example.demo.util.TPage;
12 |
13 | import javassist.NotFoundException;
14 |
15 | public interface StudentService {
16 | public StudentDto save(@Valid StudentDto studentDto) throws Exception;
17 | public TPage getAllPageable(Pageable pageable) throws NotFoundException;
18 | public List getAll() throws NotFoundException;
19 | public StudentDto findById(Long id) throws NotFoundException;
20 | public StudentDto update(Long id, @Valid StudentDto studentDto) throws Exception;
21 | public StudentDto getBookForStudent(@Valid StudenPatchtDto studenPatchtDto) throws NotFoundException;
22 | public Boolean delete(Long id) throws NotFoundException;
23 | public StudentDto leaveBookForStudent(@Valid StudenPatchtDto studenPatchtDto) throws NotFoundException;
24 | }
25 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/BookUpdateDto.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.FetchType;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.GenerationType;
8 | import javax.persistence.Id;
9 | import javax.persistence.JoinColumn;
10 | import javax.persistence.ManyToOne;
11 | import javax.persistence.Table;
12 | import javax.validation.constraints.NotNull;
13 |
14 | import com.example.demo.model.BookStatus;
15 |
16 | import lombok.Data;
17 | import lombok.Getter;
18 | import lombok.NoArgsConstructor;
19 | import lombok.Setter;
20 |
21 | @Getter
22 | @Setter
23 | @NoArgsConstructor
24 | @Data
25 | public class BookUpdateDto {
26 |
27 | private Long id;
28 | @NotNull
29 | private String name;
30 |
31 | private String content;
32 |
33 | @NotNull
34 | private Long authorId;
35 |
36 | @NotNull
37 | private String barcode;
38 |
39 | @NotNull
40 | private BookStatus bookStatus;
41 |
42 | private AuthorDtoForOneEntity author;
43 |
44 | @NotNull
45 | private String publisher;
46 | }
47 |
--------------------------------------------------------------------------------
/library-webui/README.md:
--------------------------------------------------------------------------------
1 | # LibraryWebui
2 |
3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.0.3.
4 |
5 | ## Development server
6 |
7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
8 |
9 | ## Code scaffolding
10 |
11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
12 |
13 | ## Build
14 |
15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
16 |
17 | ## Running unit tests
18 |
19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
20 |
21 | ## Running end-to-end tests
22 |
23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
24 |
25 | ## Further help
26 |
27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
28 |
--------------------------------------------------------------------------------
/library-webui/src/app/app.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed, async } from '@angular/core/testing';
2 | import { AppComponent } from './app.component';
3 |
4 | describe('AppComponent', () => {
5 | beforeEach(async(() => {
6 | TestBed.configureTestingModule({
7 | declarations: [
8 | AppComponent
9 | ],
10 | }).compileComponents();
11 | }));
12 |
13 | it('should create the app', () => {
14 | const fixture = TestBed.createComponent(AppComponent);
15 | const app = fixture.debugElement.componentInstance;
16 | expect(app).toBeTruthy();
17 | });
18 |
19 | it(`should have as title 'library-webui'`, () => {
20 | const fixture = TestBed.createComponent(AppComponent);
21 | const app = fixture.debugElement.componentInstance;
22 | expect(app.title).toEqual('library-webui');
23 | });
24 |
25 | it('should render title in a h1 tag', () => {
26 | const fixture = TestBed.createComponent(AppComponent);
27 | fixture.detectChanges();
28 | const compiled = fixture.debugElement.nativeElement;
29 | expect(compiled.querySelector('h1').textContent).toContain('Welcome to library-webui!');
30 | });
31 | });
32 |
--------------------------------------------------------------------------------
/library-webui/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage-istanbul-reporter'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | clearContext: false // leave Jasmine Spec Runner output visible in browser
17 | },
18 | coverageIstanbulReporter: {
19 | dir: require('path').join(__dirname, './coverage/library-webui'),
20 | reports: ['html', 'lcovonly', 'text-summary'],
21 | fixWebpackSourcePaths: true
22 | },
23 | reporters: ['progress', 'kjhtml'],
24 | port: 9876,
25 | colors: true,
26 | logLevel: config.LOG_INFO,
27 | autoWatch: true,
28 | browsers: ['Chrome'],
29 | singleRun: false,
30 | restartOnFileChange: true
31 | });
32 | };
33 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/book/book.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { CommonModule } from '@angular/common';
3 | import { BookRoutingModule } from './book.routing.module';
4 | import { BookComponent } from './book.component';
5 | import { AuthorService } from 'src/app/services/author.service';
6 | import { BookService } from 'src/app/services/book.service';
7 | import { ApiService } from 'src/app/services/general/api.service';
8 | import { FormsModule, ReactiveFormsModule } from '@angular/forms';
9 | import { NgxDatatableModule } from '@swimlane/ngx-datatable';
10 | import { BsModalRef } from 'ngx-bootstrap';
11 | import { BookDetailsComponent } from './book-details/book-details.component';
12 | import { AlertifyService } from 'src/app/services/alertify.service';
13 |
14 | @NgModule({
15 | declarations: [BookComponent, BookDetailsComponent],
16 | imports: [
17 | CommonModule,
18 | BookRoutingModule,
19 | FormsModule,
20 | NgxDatatableModule,
21 | ReactiveFormsModule
22 | ],
23 | providers: [
24 | AuthorService,
25 | BookService,
26 | AlertifyService,
27 | BsModalRef,
28 | ApiService
29 | ]
30 | })
31 | export class BookModule { }
32 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/BookOneDto.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.FetchType;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.GenerationType;
8 | import javax.persistence.Id;
9 | import javax.persistence.JoinColumn;
10 | import javax.persistence.ManyToOne;
11 | import javax.persistence.Table;
12 | import javax.validation.constraints.NotNull;
13 |
14 | import com.example.demo.model.BookStatus;
15 |
16 | import lombok.Data;
17 | import lombok.Getter;
18 | import lombok.NoArgsConstructor;
19 | import lombok.Setter;
20 |
21 | @Getter
22 | @Setter
23 | @NoArgsConstructor
24 | @Data
25 | public class BookOneDto {
26 |
27 | private Long id;
28 |
29 | @NotNull
30 | private String name;
31 |
32 | @NotNull
33 | private String barcode;
34 |
35 | private String content;
36 |
37 | @NotNull
38 | private String publisher;
39 |
40 | private Long studentId;
41 |
42 | private BookStatus bookStatus;
43 |
44 | @NotNull
45 | private Long authorId;
46 |
47 | private AuthorDtoForOneEntity author;
48 |
49 | private StudentDtoForOneEntity student;
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/BookDto.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.FetchType;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.GenerationType;
8 | import javax.persistence.Id;
9 | import javax.persistence.JoinColumn;
10 | import javax.persistence.ManyToOne;
11 | import javax.persistence.Table;
12 | import javax.validation.constraints.NotNull;
13 |
14 | import com.example.demo.model.BookStatus;
15 | import com.example.demo.model.Student;
16 |
17 | import lombok.Data;
18 | import lombok.Getter;
19 | import lombok.NoArgsConstructor;
20 | import lombok.Setter;
21 |
22 | @Getter
23 | @Setter
24 | @NoArgsConstructor
25 | @Data
26 | public class BookDto {
27 |
28 | private Long id;
29 |
30 | @NotNull
31 | private String name;
32 |
33 | @NotNull
34 | private String barcode;
35 |
36 | private String content;
37 |
38 | @NotNull
39 | private String publisher;
40 |
41 | private Long studentId;
42 |
43 | private BookStatus bookStatus;
44 |
45 | @NotNull
46 | private Long authorId;
47 |
48 | private AuthorDtoForOneEntity author;
49 |
50 | private StudentDtoForOneEntity student;
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/model/User.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.model;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.Index;
9 | import javax.persistence.Table;
10 |
11 | import lombok.Getter;
12 | import lombok.NoArgsConstructor;
13 | import lombok.Setter;
14 |
15 | @NoArgsConstructor
16 | @Getter
17 | @Setter
18 | @Entity
19 | @Table(name = "users", indexes = { @Index(name = "idx_username", columnList = "uname") })
20 | public class User {
21 |
22 | @Id
23 | @GeneratedValue(strategy = GenerationType.AUTO)
24 | private Long id;
25 |
26 | @Column(name = "uname", length = 100, unique = true)
27 | private String username;
28 |
29 | @Column(name = "pwd", length = 300)
30 | private String password;
31 |
32 | @Column(name = "firstname", length = 100)
33 | private String firstname;
34 |
35 | @Column(name = "lastname", length = 100)
36 | private String lastname;
37 |
38 | @Column(name = "email", length = 100, unique = true)
39 | private String email;
40 |
41 | @Column(name = "realpwd", length = 300)
42 | private String realPassword;
43 | }
44 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/student.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { CommonModule } from '@angular/common';
3 | import { StudentComponent } from './student.component';
4 | import { StudentDetailsComponent } from './student-details/student-details.component';
5 | import { StudentRoutingModule } from './student.routing.module';
6 | import { FormsModule, ReactiveFormsModule } from '@angular/forms';
7 | import { NgxDatatableModule } from '@swimlane/ngx-datatable';
8 | import { AuthorService } from 'src/app/services/author.service';
9 | import { BookService } from 'src/app/services/book.service';
10 | import { BsModalRef } from 'ngx-bootstrap';
11 | import { StudentService } from 'src/app/services/student.service';
12 | import { GetBookComponent } from './get-book/get-book.component';
13 | import { AlertifyService } from 'src/app/services/alertify.service';
14 |
15 | @NgModule({
16 | declarations: [StudentComponent, StudentDetailsComponent, GetBookComponent],
17 | imports: [
18 | CommonModule,
19 | StudentRoutingModule,
20 | FormsModule,
21 | NgxDatatableModule,
22 | ReactiveFormsModule
23 | ],
24 | providers: [
25 | AuthorService,
26 | AlertifyService,
27 | BookService,
28 | StudentService,
29 | BsModalRef
30 | ]
31 | })
32 | export class StudentModule { }
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/author/author.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { CommonModule } from '@angular/common';
3 | import { AuthorRoutingModule } from './author.routing.module';
4 | import { AuthorComponent } from './author.component';
5 | import { NgxDatatableModule } from '@swimlane/ngx-datatable';
6 | import { BsModalRef, ModalModule, BsModalService} from 'ngx-bootstrap';
7 | import { AuthorService } from 'src/app/services/author.service';
8 | import { FormsModule, ReactiveFormsModule } from '@angular/forms';
9 | import { AuthorDetailComponent } from './author-detail/author-detail.component';
10 | import { BookService } from 'src/app/services/book.service';
11 | import { ApiService } from 'src/app/services/general/api.service';
12 | import { AlertifyService } from 'src/app/services/alertify.service';
13 |
14 | import { EditorModule } from '@tinymce/tinymce-angular';
15 | @NgModule({
16 | declarations: [AuthorComponent, AuthorDetailComponent],
17 | imports: [
18 | CommonModule,
19 | AuthorRoutingModule,
20 | FormsModule,
21 | NgxDatatableModule,
22 | ReactiveFormsModule,
23 | EditorModule
24 | ],
25 | providers: [
26 | AuthorService,
27 | BookService,
28 | AlertifyService,
29 | ApiService,
30 | BsModalRef
31 | ]
32 | })
33 | export class AuthorModule { }
34 |
--------------------------------------------------------------------------------
/library-webui/src/app/services/user.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 | import { ApiService } from './general/api.service';
3 | import { Observable } from 'rxjs';
4 | import { map } from 'rxjs/operators';
5 |
6 | @Injectable({
7 | providedIn: 'root'
8 | })
9 | export class UserService {
10 | USER_PATH = '/user';
11 | CHANGE_PASSWORD_PATH = '/change-password';
12 | constructor(private apiService: ApiService) { }
13 |
14 | getByName(username: string): Observable {
15 | return this.apiService.getByName(this.USER_PATH + '/' + username).pipe(map(
16 | res => {
17 | if (res) {
18 | return res;
19 | } else {
20 | return {};
21 | }
22 | }
23 | ));
24 | }
25 | put(username: string, user): Observable {
26 | return this.apiService.put(this.USER_PATH + '/' + username, user).pipe(map(
27 | res => {
28 | if (res) {
29 | return res;
30 | } else {
31 | return {};
32 | }
33 | }
34 | ));
35 | }
36 | changePassword(params): Observable {
37 | console.log(params)
38 | return this.apiService.patch(this.USER_PATH + this.CHANGE_PASSWORD_PATH, params).pipe(map(
39 | res => {
40 | if (res) {
41 | return res;
42 | } else {
43 | return {};
44 | }
45 | }
46 | ));
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/StudentDto.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import java.util.List;
4 |
5 | import javax.persistence.CascadeType;
6 | import javax.persistence.Column;
7 | import javax.persistence.Entity;
8 | import javax.persistence.EnumType;
9 | import javax.persistence.Enumerated;
10 | import javax.persistence.FetchType;
11 | import javax.persistence.GeneratedValue;
12 | import javax.persistence.GenerationType;
13 | import javax.persistence.Id;
14 | import javax.persistence.OneToMany;
15 | import javax.persistence.OneToOne;
16 | import javax.persistence.SequenceGenerator;
17 | import javax.persistence.Table;
18 | import javax.validation.constraints.NotNull;
19 |
20 | import com.example.demo.model.Book;
21 | import com.example.demo.model.City;
22 |
23 | import lombok.Data;
24 | import lombok.Getter;
25 | import lombok.NoArgsConstructor;
26 | import lombok.Setter;
27 |
28 | @Getter
29 | @Setter
30 | @NoArgsConstructor
31 | @Data
32 | public class StudentDto {
33 |
34 | private Long id;
35 |
36 | private String tcNo;
37 |
38 | @NotNull
39 | private String fullname;
40 |
41 | private String university;
42 |
43 | private String department;
44 |
45 | @NotNull
46 | private String email;
47 |
48 | @NotNull
49 | private String phone;
50 |
51 | private String address;
52 |
53 | private City city;
54 |
55 | private List books;
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/library-webui/src/app/app.routing.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { RouterModule, Routes } from '@angular/router';
3 | import { LoginComponent } from './login/login.component';
4 | import { RegisterComponent } from './register/register.component';
5 | import { NotfoundComponent } from './shared/notfound/notfound.component';
6 | import { MainComponent } from './common/main/main.component';
7 | import { AuthGuard } from './security/auth.guard';
8 |
9 | const routes: Routes = [
10 | {
11 | path: '', component: MainComponent, canActivate: [AuthGuard],
12 | children: [
13 | {path: '', pathMatch: 'full', redirectTo: 'author'},
14 | { path: 'author', loadChildren: './common/api/author/author.module#AuthorModule' },
15 | { path: 'book', loadChildren: './common/api/book/book.module#BookModule' },
16 | { path: 'student', loadChildren: './common/api/student/student.module#StudentModule' },
17 | { path: 'user', loadChildren: './common/api/user-detail/user.module#UserModule' },
18 | ]
19 | },
20 | //{path: '', pathMatch: 'full', redirectTo: 'login'},
21 | { path: 'login', component: LoginComponent },
22 | { path: 'register', component: RegisterComponent },
23 | { path: '**', component: NotfoundComponent }
24 | ];
25 |
26 | @NgModule({
27 |
28 | imports: [RouterModule.forRoot(routes)],
29 | exports: [RouterModule]
30 | })
31 | export class AppRoutingModule {
32 | }
33 |
34 |
35 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/dto/StudentOneDto.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.dto;
2 |
3 | import java.util.List;
4 |
5 | import javax.persistence.CascadeType;
6 | import javax.persistence.Column;
7 | import javax.persistence.Entity;
8 | import javax.persistence.EnumType;
9 | import javax.persistence.Enumerated;
10 | import javax.persistence.FetchType;
11 | import javax.persistence.GeneratedValue;
12 | import javax.persistence.GenerationType;
13 | import javax.persistence.Id;
14 | import javax.persistence.OneToMany;
15 | import javax.persistence.OneToOne;
16 | import javax.persistence.SequenceGenerator;
17 | import javax.persistence.Table;
18 | import javax.validation.constraints.NotNull;
19 |
20 | import com.example.demo.model.Book;
21 | import com.example.demo.model.City;
22 |
23 | import lombok.Data;
24 | import lombok.Getter;
25 | import lombok.NoArgsConstructor;
26 | import lombok.Setter;
27 |
28 | @Getter
29 | @Setter
30 | @NoArgsConstructor
31 | @Data
32 | public class StudentOneDto {
33 |
34 | private Long id;
35 |
36 | private String tcNo;
37 |
38 | @NotNull
39 | private String fullname;
40 |
41 | private String university;
42 |
43 | private String department;
44 |
45 | @NotNull
46 | private String email;
47 |
48 | @NotNull
49 | private String phone;
50 |
51 | private String address;
52 |
53 | private City city;
54 |
55 | private Long bookId;
56 |
57 | private List books;
58 | }
59 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/exception/IMExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.exception;
2 |
3 | import java.util.Date;
4 |
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.http.HttpStatus;
8 | import org.springframework.http.ResponseEntity;
9 | import org.springframework.web.bind.annotation.ControllerAdvice;
10 | import org.springframework.web.bind.annotation.ExceptionHandler;
11 | import org.springframework.web.bind.annotation.RestController;
12 | import org.springframework.web.bind.annotation.RestControllerAdvice;
13 | import org.springframework.web.context.request.WebRequest;
14 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
15 |
16 | @RestController
17 | @RestControllerAdvice
18 | public class IMExceptionHandler extends ResponseEntityExceptionHandler {
19 |
20 | private static final Logger logger = LoggerFactory.getLogger(IMExceptionHandler.class);
21 |
22 | @ExceptionHandler(Exception.class)
23 | public final ResponseEntity> handleExceptions(Exception ex, WebRequest request) {
24 |
25 | ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage());
26 | logger.error("--Application was Error : "+ex.getMessage());
27 | // Log.info("ControllerAdvice -> ExceptionHandler : "+ex);
28 |
29 | return new ResponseEntity<>(exceptionResponse, HttpStatus.EXPECTATION_FAILED);
30 | //return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/model/Author.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.model;
2 |
3 | import java.util.List;
4 |
5 | import javax.persistence.CascadeType;
6 | import javax.persistence.Column;
7 | import javax.persistence.Entity;
8 | import javax.persistence.FetchType;
9 | import javax.persistence.GeneratedValue;
10 | import javax.persistence.GenerationType;
11 | import javax.persistence.Id;
12 | import javax.persistence.Lob;
13 | import javax.persistence.OneToMany;
14 | import javax.persistence.SequenceGenerator;
15 | import javax.persistence.Table;
16 | import javax.validation.constraints.NotNull;
17 |
18 | import org.hibernate.annotations.Type;
19 |
20 | import lombok.Getter;
21 | import lombok.NoArgsConstructor;
22 | import lombok.Setter;
23 |
24 | @Getter
25 | @Setter
26 | @NoArgsConstructor
27 | @Entity
28 | @Table(name = "author")
29 | public class Author {
30 |
31 | @Id
32 | @GeneratedValue(strategy = GenerationType.AUTO)
33 | private Long id;
34 |
35 | @NotNull
36 | @Column(name = "name", length = 100)
37 | private String name;
38 |
39 | @Type(type = "text")
40 | @Lob
41 | @Column(name = "about", length = 8000)
42 | private String about;
43 |
44 | @NotNull
45 | @Column(name = "surname", length = 100)
46 | private String surname;
47 |
48 | @Column(name = "email", length = 100, unique = true)
49 | private String email;
50 |
51 | @Column(name = "phone", length = 100)
52 | private String phone;
53 |
54 | @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
55 | private List books;
56 | }
57 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Library-Application
2 | This project is about Library Application for automation.
3 |
4 | ## Used Tools & Technologies
5 | ```
6 | - Spring Boot 2.1.5
7 | - Spring Security, JWT
8 | - REST API (get, post, put, delete, patch)
9 | - Lombok
10 | - ModelMapper, DTO
11 | - JPA, Hibernate
12 | - PostgreSql 9.6
13 | - Angular 8
14 | - Typescript
15 | - Alertify Js
16 | - Bootstrap 4,
17 | - TinyMCE
18 | ```
19 |
20 | ## Create backend side Spring boot 2.1.5
21 | - Download this repository
22 | - After opening this project on STS When you click Library Application project then right click `Maven->Update project`
23 |
24 | ## Create front side regarding Angular 8
25 | ##### Create client
26 | if you wanna create this project again you need to write the following command directly on terminal or gitbash.
27 | - npm i @angular/cli
28 | - ng new project-name
29 | - cd project-name
30 | - npm install bootstrap
31 | - npm install jquery
32 | - npm install alertifyjs --save
33 | - npm install @swimlane/ngx-datatable
34 | - npm i ngx-datatable
35 | - npm install --save @tinymce/tinymce-angular
36 | ##### Run project
37 | - first download this project
38 | - second open front side on VS Code and write `ng update` on terminal
39 | - last you can run `ng serve` or `ng serve --port PORT_NUMBER` or `ng serve --port PORT_NUMBER --open`
40 | ##### Build client
41 | if you wanna build this project You need to write `ng build` then You can run client `ng serve --port 5422`
42 | - ng build
43 | - ng serve --port 5422
44 |
45 | ## How to run with Docker
46 |
47 | - Start all services :
48 | ```bash
49 | docker-compose up
50 | ```
51 |
52 | - Stop and remove all service containers :
53 | ```bash
54 | docker-compose down
55 | ```
56 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/util/TPage.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.util;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.domain.Page;
6 | import org.springframework.data.domain.Sort;
7 |
8 | public class TPage {
9 |
10 | private int number;
11 | private int size;
12 | private Sort sort;
13 | private int totalPages;
14 | private Long totalElements;
15 | private List content;
16 |
17 | public void setStat(Page page, List list) {
18 | this.number = page.getNumber();
19 | this.size = page.getSize();
20 | this.sort = page.getSort();
21 | this.totalPages = page.getTotalPages();
22 | this.totalElements = page.getTotalElements();
23 | this.content = list;
24 | }
25 |
26 | public TPage() {
27 | super();
28 | }
29 |
30 | public int getNumber() {
31 | return number;
32 | }
33 |
34 | public void setNumber(int number) {
35 | this.number = number;
36 | }
37 |
38 | public int getSize() {
39 | return size;
40 | }
41 |
42 | public void setSize(int size) {
43 | this.size = size;
44 | }
45 |
46 | public Sort getSort() {
47 | return sort;
48 | }
49 |
50 | public void setSort(Sort sort) {
51 | this.sort = sort;
52 | }
53 |
54 | public int getTotalPages() {
55 | return totalPages;
56 | }
57 |
58 | public void setTotalPages(int totalPages) {
59 | this.totalPages = totalPages;
60 | }
61 |
62 | public Long getTotalElements() {
63 | return totalElements;
64 | }
65 |
66 | public void setTotalElements(Long totalElements) {
67 | this.totalElements = totalElements;
68 | }
69 |
70 | public List getContent() {
71 | return content;
72 | }
73 |
74 | public void setContent(List content) {
75 | this.content = content;
76 | }
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/model/Book.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.model;
2 |
3 | import javax.persistence.CascadeType;
4 | import javax.persistence.Column;
5 | import javax.persistence.Entity;
6 | import javax.persistence.EnumType;
7 | import javax.persistence.Enumerated;
8 | import javax.persistence.FetchType;
9 | import javax.persistence.GeneratedValue;
10 | import javax.persistence.GenerationType;
11 | import javax.persistence.Id;
12 | import javax.persistence.JoinColumn;
13 | import javax.persistence.ManyToOne;
14 | import javax.persistence.OneToOne;
15 | import javax.persistence.SequenceGenerator;
16 | import javax.persistence.Table;
17 | import javax.validation.constraints.NotNull;
18 |
19 | import lombok.Getter;
20 | import lombok.NoArgsConstructor;
21 | import lombok.Setter;
22 |
23 | @NoArgsConstructor
24 | @Getter
25 | @Setter
26 | @Entity
27 | @Table(name = "book")
28 | public class Book {
29 |
30 | @Id
31 | @GeneratedValue(strategy = GenerationType.TABLE)
32 | private Long id;
33 |
34 | @Column(name = "name", length = 300)
35 | private String name;
36 |
37 | @Column(name = "content", length = 3000)
38 | private String content;
39 |
40 | @Column(name = "barcode", length = 100, unique = true)
41 | private String barcode;
42 |
43 | @Column(name = "publisher", length = 300)
44 | private String publisher;
45 |
46 | @Column(name = "bookStatus", length = 50)
47 | @Enumerated(EnumType.STRING)
48 | private BookStatus bookStatus;
49 |
50 | @NotNull
51 | @JoinColumn(name = "author_id")
52 | @ManyToOne(optional = true, fetch = FetchType.LAZY)
53 | private Author author;
54 |
55 | @JoinColumn(name = "student_id")
56 | @ManyToOne(optional = true, fetch = FetchType.LAZY)
57 | private Student student;
58 | }
59 |
--------------------------------------------------------------------------------
/library-webui/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "library-webui",
3 | "version": "0.0.0",
4 | "scripts": {
5 | "ng": "ng",
6 | "start": "ng serve",
7 | "build": "ng build",
8 | "test": "ng test",
9 | "lint": "ng lint",
10 | "e2e": "ng e2e"
11 | },
12 | "private": true,
13 | "dependencies": {
14 | "@angular/animations": "~8.0.1",
15 | "@angular/common": "~8.0.1",
16 | "@angular/compiler": "~8.0.1",
17 | "@angular/core": "~8.0.1",
18 | "@angular/forms": "~8.0.1",
19 | "@angular/platform-browser": "~8.0.1",
20 | "@angular/platform-browser-dynamic": "~8.0.1",
21 | "@angular/router": "~8.0.1",
22 | "@swimlane/ngx-datatable": "^15.0.2",
23 | "@tinymce/tinymce-angular": "^3.3.1",
24 | "alertifyjs": "^1.11.4",
25 | "bootstrap": "^4.3.1",
26 | "jquery": "^3.4.1",
27 | "ngx-bootstrap": "^4.3.0",
28 | "ngx-datatable": "^1.0.3",
29 | "rxjs": "~6.4.0",
30 | "tslib": "^1.9.0",
31 | "zone.js": "~0.9.1"
32 | },
33 | "devDependencies": {
34 | "@angular-devkit/build-angular": "~0.800.0",
35 | "@angular/cli": "~8.0.3",
36 | "@angular/compiler-cli": "~8.0.1",
37 | "@angular/language-service": "~8.0.1",
38 | "@types/node": "~8.9.4",
39 | "@types/jasmine": "~3.3.8",
40 | "@types/jasminewd2": "~2.0.3",
41 | "codelyzer": "^5.0.0",
42 | "jasmine-core": "~3.4.0",
43 | "jasmine-spec-reporter": "~4.2.1",
44 | "karma": "~4.1.0",
45 | "karma-chrome-launcher": "~2.2.0",
46 | "karma-coverage-istanbul-reporter": "~2.0.1",
47 | "karma-jasmine": "~2.0.1",
48 | "karma-jasmine-html-reporter": "^1.4.0",
49 | "protractor": "~5.4.0",
50 | "ts-node": "~7.0.0",
51 | "tslint": "~5.15.0",
52 | "typescript": "~3.4.3"
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/model/Student.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.model;
2 |
3 | import java.util.List;
4 |
5 | import javax.persistence.CascadeType;
6 | import javax.persistence.Column;
7 | import javax.persistence.Entity;
8 | import javax.persistence.EnumType;
9 | import javax.persistence.Enumerated;
10 | import javax.persistence.FetchType;
11 | import javax.persistence.GeneratedValue;
12 | import javax.persistence.GenerationType;
13 | import javax.persistence.Id;
14 | import javax.persistence.OneToMany;
15 | import javax.persistence.OneToOne;
16 | import javax.persistence.SequenceGenerator;
17 | import javax.persistence.Table;
18 | import javax.validation.constraints.NotNull;
19 |
20 | import org.hibernate.validator.constraints.UniqueElements;
21 |
22 | import lombok.Getter;
23 | import lombok.NoArgsConstructor;
24 | import lombok.Setter;
25 |
26 | @Getter
27 | @Setter
28 | @NoArgsConstructor
29 | @Entity
30 | @Table(name = "student")
31 | public class Student {
32 |
33 | @Id
34 | @GeneratedValue(strategy = GenerationType.AUTO)
35 | private Long id;
36 |
37 | @NotNull
38 | @Column(name = "tcNo", length = 11, unique = true)
39 | private String tcNo;
40 |
41 | @NotNull
42 | @Column(name = "fullname", length = 100, unique = true)
43 | private String fullname;
44 |
45 | @NotNull
46 | @Column(name = "email", length = 100, unique = true)
47 | private String email;
48 |
49 | @Column(name = "university", length = 3000)
50 | private String university;
51 |
52 | @Column(name = "department", length = 3000)
53 | private String department;
54 |
55 | @NotNull
56 | @Column(name = "phone", length = 100)
57 | private String phone;
58 |
59 | @Column(name = "address", length = 100)
60 | private String address;
61 |
62 | @Column(name = "city", length = 100)
63 | @Enumerated(EnumType.STRING)
64 | private City city;
65 |
66 | @OneToMany(mappedBy = "student", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
67 | private List books;
68 | }
69 |
--------------------------------------------------------------------------------
/library-webui/src/app/register/register.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { FormGroup, Validators, FormBuilder } from '@angular/forms';
3 | import { Router } from '@angular/router';
4 | import { AuthenticationService } from '../security/authentication.service';
5 | import { first } from 'rxjs/operators';
6 | import { AlertifyService } from '../services/alertify.service';
7 |
8 | @Component({
9 | selector: 'app-register',
10 | templateUrl: './register.component.html',
11 | styleUrls: ['./register.component.css']
12 | })
13 | export class RegisterComponent implements OnInit {
14 | registerForm: FormGroup;
15 | loading = false;
16 | submitted = false;
17 | error = '';
18 |
19 | constructor(private formBuilder: FormBuilder,
20 | private router: Router,
21 | private alert: AlertifyService,
22 | private authenticationService: AuthenticationService) {
23 | }
24 |
25 | ngOnInit() {
26 | this.registerForm = this.formBuilder.group({
27 | username: ['', Validators.required],
28 | password: ['', Validators.required],
29 | firstname: ['', Validators.required],
30 | lastname: ['', Validators.required],
31 | email: ['', [Validators.required, Validators.email]],
32 | });
33 | this.authenticationService.logout();
34 | }
35 | get f() { return this.registerForm.controls; }
36 | register() {
37 | this.submitted = true;
38 | if (this.registerForm.invalid) {
39 | return;
40 | }
41 | this.loading = true;
42 | this.authenticationService.register(this.registerForm.value)
43 | .pipe(first())
44 | .subscribe(
45 | data => {
46 | this.alert.success('Kayıt işlemi başarılı...');
47 | this.router.navigate(['/login']);
48 | },
49 | error => {
50 | this.alert.error('Hata : ' + error);
51 | this.error = error;
52 | this.loading = false;
53 | });
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/service/imp/UserDetailsServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.service.imp;
2 |
3 | import org.springframework.security.core.userdetails.UserDetailsService;
4 | import org.springframework.stereotype.Service;
5 |
6 | import com.example.demo.model.User;
7 | import com.example.demo.repository.UserRepository;
8 |
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
11 | import org.springframework.security.core.userdetails.UserDetails;
12 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
13 |
14 | import static java.util.Collections.emptyList;
15 |
16 | import java.util.Arrays;
17 |
18 | @Service
19 | public class UserDetailsServiceImpl implements UserDetailsService {
20 |
21 | @Autowired
22 | private UserRepository userRepository;
23 |
24 | @Override
25 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
26 | User user = userRepository.findByUsername(username);
27 | if (user == null) {
28 | throw new UsernameNotFoundException("Invalid username or password.");
29 | }
30 | return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
31 | Arrays.asList(new SimpleGrantedAuthority("USER")));
32 | }
33 |
34 | // private UserRepository userRepository;
35 | //
36 | // @Override
37 | // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
38 | // System.out.println(username);
39 | // User developer = userRepository.findByUsername(username);
40 | // if (developer == null) {
41 | // throw new UsernameNotFoundException(username);
42 | // }
43 | // return new org.springframework.security.core.userdetails.User(
44 | // developer.getUsername(),
45 | // developer.getPassword(),
46 | // Arrays.asList(new SimpleGrantedAuthority("USER")));
47 | // }
48 | }
49 |
--------------------------------------------------------------------------------
/library-webui/src/app/app.component.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/library-webui/src/app/login/login.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { FormBuilder, FormGroup, Validators } from '@angular/forms';
3 | import { Router, ActivatedRoute } from '@angular/router';
4 | import { AuthenticationService } from '../security/authentication.service';
5 | import { first } from 'rxjs/operators';
6 | import { AlertifyService } from '../services/alertify.service';
7 |
8 | @Component({
9 | selector: 'app-login',
10 | templateUrl: './login.component.html',
11 | styleUrls: ['./login.component.css']
12 | })
13 | export class LoginComponent implements OnInit {
14 | //form parameters
15 | loginForm: FormGroup;
16 | loading = false;
17 | submitted = false;
18 | returnUrl: string;
19 | error = '';
20 | constructor(private formBuilder: FormBuilder,
21 | private route: ActivatedRoute,
22 | private alert: AlertifyService,
23 | private router: Router,
24 | private authenticationService: AuthenticationService) { }
25 |
26 | ngOnInit() {
27 | this.loginForm = this.formBuilder.group({
28 | 'username': [null, [Validators.required]],
29 | 'password': [null, [Validators.required]]
30 | });
31 | // reset login status
32 | this.authenticationService.logout();
33 |
34 | // return url var ise al yoksa / linkine git
35 | // get return url from route parameters or default to '/'
36 | this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
37 | }
38 | login() {
39 | this.submitted = true;
40 | if (!this.loginForm.valid) {
41 | return;
42 | }
43 |
44 | this.loading = true;
45 | this.authenticationService.login(this.f.username.value, this.f.password.value)
46 | .pipe(first())
47 | .subscribe(
48 | data => {
49 | this.router.navigate([this.returnUrl]);
50 | this.alert.success('Hoşgeldiniz ' + this.f.username.value);
51 | },
52 | error => {
53 | this.error = error;
54 | this.alert.success('Hata : ' + error);
55 | this.loading = false;
56 | }
57 | );
58 | }
59 | get f() { return this.loginForm.controls; }
60 | }
61 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/api/UserController.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.api;
2 |
3 | import javax.validation.Valid;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.CrossOrigin;
8 | import org.springframework.web.bind.annotation.GetMapping;
9 | import org.springframework.web.bind.annotation.PatchMapping;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.PutMapping;
12 | import org.springframework.web.bind.annotation.RequestBody;
13 | import org.springframework.web.bind.annotation.RequestMapping;
14 | import org.springframework.web.bind.annotation.RestController;
15 |
16 | import com.example.demo.dto.BookUpdateDto;
17 | import com.example.demo.dto.RegistirationRequest;
18 | import com.example.demo.dto.StudentDto;
19 | import com.example.demo.dto.UserDto;
20 | import com.example.demo.dto.UserPasswordDto;
21 | import com.example.demo.service.imp.UserServiceImp;
22 | import com.example.demo.util.ApiPaths;
23 |
24 | import javassist.NotFoundException;
25 |
26 | @RestController
27 | @RequestMapping(ApiPaths.UserCtrl.CTRL)
28 | @CrossOrigin
29 | public class UserController {
30 |
31 | @Autowired
32 | private UserServiceImp userServiceImp;
33 |
34 | @GetMapping("/{username}")
35 | public ResponseEntity findByUserName(@PathVariable(name = "username", required = true) String username)
36 | throws NotFoundException {
37 | return ResponseEntity.ok(userServiceImp.findByUserName(username));
38 | }
39 |
40 | @PutMapping("/{username}")
41 | public ResponseEntity updateUser(@PathVariable(name = "username", required = true) String username,
42 | @Valid @RequestBody UserDto userDto) throws NotFoundException {
43 | return ResponseEntity.ok(userServiceImp.update(username, userDto));
44 | }
45 |
46 | @PatchMapping("/change-password")
47 | public ResponseEntity signUp(@RequestBody UserPasswordDto userPasswordDto) throws NotFoundException {
48 |
49 | Boolean result = userServiceImp.changePassword(userPasswordDto);
50 | return ResponseEntity.ok(result);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/library-webui/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "tslint:recommended",
3 | "rules": {
4 | "array-type": false,
5 | "arrow-parens": false,
6 | "deprecation": {
7 | "severity": "warn"
8 | },
9 | "component-class-suffix": true,
10 | "contextual-lifecycle": true,
11 | "directive-class-suffix": true,
12 | "directive-selector": [
13 | true,
14 | "attribute",
15 | "app",
16 | "camelCase"
17 | ],
18 | "component-selector": [
19 | true,
20 | "element",
21 | "app",
22 | "kebab-case"
23 | ],
24 | "import-blacklist": [
25 | true,
26 | "rxjs/Rx"
27 | ],
28 | "interface-name": false,
29 | "max-classes-per-file": false,
30 | "max-line-length": [
31 | true,
32 | 140
33 | ],
34 | "member-access": false,
35 | "member-ordering": [
36 | true,
37 | {
38 | "order": [
39 | "static-field",
40 | "instance-field",
41 | "static-method",
42 | "instance-method"
43 | ]
44 | }
45 | ],
46 | "no-consecutive-blank-lines": false,
47 | "no-console": [
48 | true,
49 | "debug",
50 | "info",
51 | "time",
52 | "timeEnd",
53 | "trace"
54 | ],
55 | "no-empty": false,
56 | "no-inferrable-types": [
57 | true,
58 | "ignore-params"
59 | ],
60 | "no-non-null-assertion": true,
61 | "no-redundant-jsdoc": true,
62 | "no-switch-case-fall-through": true,
63 | "no-use-before-declare": true,
64 | "no-var-requires": false,
65 | "object-literal-key-quotes": [
66 | true,
67 | "as-needed"
68 | ],
69 | "object-literal-sort-keys": false,
70 | "ordered-imports": false,
71 | "quotemark": [
72 | true,
73 | "single"
74 | ],
75 | "trailing-comma": false,
76 | "no-conflicting-lifecycle": true,
77 | "no-host-metadata-property": true,
78 | "no-input-rename": true,
79 | "no-inputs-metadata-property": true,
80 | "no-output-native": true,
81 | "no-output-on-prefix": true,
82 | "no-output-rename": true,
83 | "no-outputs-metadata-property": true,
84 | "template-banana-in-box": true,
85 | "template-no-negated-async": true,
86 | "use-lifecycle-interface": true,
87 | "use-pipe-transform-interface": true
88 | },
89 | "rulesDirectory": [
90 | "codelyzer"
91 | ]
92 | }
--------------------------------------------------------------------------------
/library-webui/src/app/app.module.ts:
--------------------------------------------------------------------------------
1 | import { BrowserModule } from '@angular/platform-browser';
2 | import { NgModule } from '@angular/core';
3 |
4 | import { AppComponent } from './app.component';
5 | import { HeaderComponent } from './common/header/header.component';
6 | import { AuthorComponent } from './common/api/author/author.component';
7 | import { BookComponent } from './common/api/book/book.component';
8 | import { LoginComponent } from './login/login.component';
9 | import { RegisterComponent } from './register/register.component';
10 | import { NotfoundComponent } from './shared/notfound/notfound.component';
11 | import { AppRoutingModule } from './app.routing.module';
12 | import { MainComponent } from './common/main/main.component';
13 | import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
14 | import { FormsModule, ReactiveFormsModule } from '@angular/forms';
15 | import { AuthorService } from './services/author.service';
16 | import { NgxDatatableModule } from '@swimlane/ngx-datatable';
17 | import { ApiService } from './services/general/api.service';
18 | import { BookService } from './services/book.service';
19 | import { StudentService } from './services/student.service';
20 | import { JwtInterceptor } from './security/jwt.interceptor';
21 | import { AuthGuard } from './security/auth.guard';
22 | import { AuthenticationService } from './security/authentication.service';
23 | import { ErrorInterceptor } from './security/authentication.interceptor';
24 | import { AlertifyService } from './services/alertify.service';
25 | import { EditorModule } from '@tinymce/tinymce-angular';
26 | @NgModule({
27 | declarations: [
28 | AppComponent,
29 | HeaderComponent,
30 | LoginComponent,
31 | RegisterComponent,
32 | NotfoundComponent,
33 | MainComponent
34 | ],
35 | imports: [
36 | BrowserModule,
37 | HttpClientModule,
38 | ReactiveFormsModule,
39 | FormsModule,
40 | AppRoutingModule,
41 | EditorModule ,
42 | NgxDatatableModule
43 | ],
44 | providers: [
45 | AuthorService,
46 | BookService,
47 | StudentService,
48 | AlertifyService,
49 | ApiService,
50 | AuthGuard,
51 | AuthenticationService,
52 | {provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true},
53 | {provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true},
54 |
55 | ],
56 | bootstrap: [AppComponent]
57 | })
58 | export class AppModule { }
59 |
--------------------------------------------------------------------------------
/library-webui/src/app/services/general/api.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 | import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
3 | import { environment } from 'src/environments/environment';
4 | import { Observable } from 'rxjs';
5 | import { catchError } from 'rxjs/internal/operators';
6 | @Injectable({
7 | providedIn: 'root'
8 | })
9 | export class ApiService {
10 |
11 | constructor(private http: HttpClient) {
12 | }
13 |
14 | private httpOptions = {
15 | headers: new HttpHeaders({
16 | 'Content-Type': 'application/json'
17 | })
18 | };
19 |
20 | getAll(path: string): Observable {
21 | return this.http.get(environment.API_BASE_PATH + path).pipe(catchError(this.formatError));
22 | }
23 |
24 | getAllPageable(path: string, params: HttpParams = new HttpParams()): Observable {
25 | return this.http.get(environment.API_BASE_PATH + path, {params}).pipe(catchError(this.formatError));
26 | }
27 |
28 | getById(path: string): Observable {
29 | return this.http.get(environment.API_BASE_PATH + path).pipe(catchError(this.formatError));
30 | }
31 | getByName(path: string): Observable {
32 | return this.http.get(environment.API_BASE_PATH + path).pipe(catchError(this.formatError));
33 | }
34 | findAllByName(path: string): Observable {
35 | return this.http.get(environment.API_BASE_PATH + path).pipe(catchError(this.formatError));
36 | }
37 | post(path: string, params: HttpParams = new HttpParams()): Observable {
38 | return this.http.post(environment.API_BASE_PATH + path, params).pipe(catchError(this.formatError));
39 | }
40 |
41 | put(path: string, params: HttpParams = new HttpParams()): Observable {
42 | return this.http.put(environment.API_BASE_PATH + path, JSON.stringify(params), this.httpOptions).pipe(catchError(this.formatError));
43 | }
44 | patch(path: string, params: HttpParams = new HttpParams()): Observable {
45 | return this.http.patch(environment.API_BASE_PATH + path, params).pipe(catchError(this.formatError));
46 | }
47 |
48 | delete(path: string, params: HttpParams = new HttpParams()): Observable {
49 | return this.http.delete(environment.API_BASE_PATH + path).pipe(catchError(this.formatError));
50 | }
51 |
52 | private formatError(error: any) {
53 | return Observable.call(environment.API_BASE_PATH + error.error);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/library-webui/src/app/login/login.component.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
Üye Giriş
6 |
7 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/library-webui/src/app/services/author.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 | import { ApiService } from './general/api.service';
3 | import { HttpClient } from '@angular/common/http';
4 | import { Observable } from 'rxjs';
5 | import { map } from 'rxjs/internal/operators';
6 |
7 | @Injectable({
8 | providedIn: 'root'
9 | })
10 | export class AuthorService {
11 | AUTHOR_PATH = '/author';
12 | AUTHOR_PATH_PAGE = '/pagination';
13 | FIND_ALL_BY_NAME_PATH = '/find?name=';
14 |
15 | constructor(private apiService: ApiService, private http: HttpClient) { }
16 |
17 | getAll(): Observable {
18 | return this.apiService.getAll(this.AUTHOR_PATH).pipe(map(
19 | res => {
20 | if (res) {
21 | return res;
22 | } else {
23 | return {};
24 | }
25 | }
26 | ));
27 | }
28 | getAllPageable(page){
29 | return this.apiService.getAllPageable(this.AUTHOR_PATH + this.AUTHOR_PATH_PAGE, page ).pipe(map(
30 | res => {
31 | if (res) {
32 | return res;
33 | } else {
34 | return {};
35 | }
36 | }
37 | ));
38 | }
39 | findAllByName(name){
40 | return this.apiService.findAllByName(this.AUTHOR_PATH + this.FIND_ALL_BY_NAME_PATH + name).pipe(map(
41 | res => {
42 | if (res) {
43 | return res;
44 | } else {
45 | return {};
46 | }
47 | }
48 | ));
49 | }
50 | getById(id: number): Observable {
51 | return this.apiService.getById(this.AUTHOR_PATH + '/' + id).pipe(map(
52 | res => {
53 | if (res) {
54 | return res;
55 | } else {
56 | return {};
57 | }
58 | }
59 | ));
60 | }
61 | post(author): Observable {
62 | return this.apiService.post(this.AUTHOR_PATH, author).pipe(map(
63 | res => {
64 | if (res) {
65 | return res;
66 | } else {
67 | return {};
68 | }
69 | }
70 | ));
71 | }
72 | put(id,author): Observable {
73 | return this.apiService.put(this.AUTHOR_PATH + '/' + id, author).pipe(map(
74 | res => {
75 | if (res) {
76 | return res;
77 | } else {
78 | return {};
79 | }
80 | }
81 | ));
82 | }
83 | delete(id): Observable {
84 | return this.apiService.delete(this.AUTHOR_PATH + '/' + id).pipe(map(
85 | res => {
86 | if (res) {
87 | return res;
88 | } else {
89 | return {};
90 | }
91 | }
92 | ));
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/library-webui/src/app/services/book.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 | import { Observable } from 'rxjs';
3 | import { ApiService } from './general/api.service';
4 | import { HttpClient, HttpHeaders } from '@angular/common/http';
5 | import { map } from 'rxjs/internal/operators';
6 |
7 | @Injectable({
8 | providedIn: 'root'
9 | })
10 | export class BookService {
11 | BOOK_PATH = '/book';
12 | BOOK_PATH_PAGE = '/pagination';
13 | BOOK_STATUS_PATH = '/statuses';
14 | FIND_BY_NAME = '/find';
15 | constructor(private apiService: ApiService,
16 | private http: HttpClient) { }
17 |
18 | getAllPageable(page){
19 | return this.apiService.getAllPageable(this.BOOK_PATH + this.BOOK_PATH_PAGE, page ).pipe(map(
20 | res => {
21 | if (res) {
22 | return res;
23 | } else {
24 | return {};
25 | }
26 | }
27 | ));
28 | }
29 |
30 | getAllBookStatus(): Observable {
31 | return this.apiService.getAll(this.BOOK_PATH + this.BOOK_STATUS_PATH).pipe(map(
32 | res => {
33 | if (res) {
34 | return res;
35 | } else {
36 | return {};
37 | }
38 | }
39 | ));
40 | }
41 | getById(id: number): Observable {
42 | return this.apiService.getById(this.BOOK_PATH + '/' + id).pipe(map(
43 | res => {
44 | if (res) {
45 | return res;
46 | } else {
47 | return {};
48 | }
49 | }
50 | ));
51 | }
52 | findAllByName(name: string): Observable {
53 | return this.apiService.findAllByName(this.BOOK_PATH + this.FIND_BY_NAME + '/' + name).pipe(map(
54 | res => {
55 | if (res) {
56 | return res;
57 | } else {
58 | return {};
59 | }
60 | }
61 | ));
62 | }
63 | post(params): Observable {
64 | return this.apiService.post(this.BOOK_PATH, params).pipe(map(
65 | res => {
66 | if (res) {
67 | return res;
68 | } else {
69 | return {};
70 | }
71 | }
72 | ));
73 | }
74 | put(id: number, book): Observable {
75 | return this.apiService.put(this.BOOK_PATH + '/' + id, book).pipe(map(
76 | res => {
77 | if (res) {
78 | return res;
79 | } else {
80 | return {};
81 | }
82 | }
83 | ));
84 | }
85 | delete(id): Observable {
86 | return this.apiService.delete(this.BOOK_PATH + '/' + id).pipe(map(
87 | res => {
88 | if (res) {
89 | return res;
90 | } else {
91 | return {};
92 | }
93 | }
94 | ));
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/book/book.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { Page } from 'src/app/shared/Page';
3 | import { BookService } from 'src/app/services/book.service';
4 | import { FormGroup, FormBuilder, Validators } from '@angular/forms';
5 | import { AlertifyService } from 'src/app/services/alertify.service';
6 |
7 | @Component({
8 | selector: 'app-book',
9 | templateUrl: './book.component.html',
10 | styleUrls: ['./book.component.css']
11 | })
12 | export class BookComponent implements OnInit {
13 |
14 | //ngx datatable parameters
15 | rows = [];
16 | cols = [];
17 | page = new Page();
18 | control = true;
19 | books = [];
20 | //search book form
21 | searchBookForm: FormGroup;
22 | message: string | undefined;
23 |
24 | constructor(private bookService: BookService,
25 | private alert: AlertifyService,
26 | private formBuilder: FormBuilder) { }
27 |
28 | ngOnInit() {
29 | this.control = true;
30 | this.loadStaticPage();
31 | }
32 | loadStaticPage() {
33 | this.setPage({ offset: 0 });
34 | this.searchBookForm = this.formBuilder.group({
35 | 'name': [null, [Validators.minLength(3), Validators.required]]
36 | });
37 | }
38 | setPage(pageInfo) {
39 | this.page.page = pageInfo.offset;
40 | this.bookService.getAllPageable(this.page).subscribe(pagedData => {
41 | this.page.size = pagedData.size;
42 | this.page.page = pagedData.page;
43 | this.page.totalElements = pagedData.totalElements;
44 | this.rows = pagedData.content;
45 | });
46 | }
47 |
48 | searchBook() {
49 | if (!this.searchBookForm.valid) {
50 | return;
51 | }
52 | this.bookService.findAllByName(this.searchBookForm.value['name']).subscribe(
53 | res => {
54 | this.control = false;
55 | this.books = res;
56 | this.message = ' Kayıtlar bulunmuştur. ';
57 | this.alert.success(' Kayıtlar bulunmuştur. ')
58 | },
59 | error => {
60 | this.control = true;
61 | this.loadStaticPage();
62 | this.alert.error(' Hay Aksi. Herhangi bir kitap kaydı bulunamamıştır.');
63 | this.message = ' Hay Aksi. Herhangi bir kitap kaydı bulunamamıştır.';
64 | });
65 | }
66 | deleteBook(id) {
67 | this.bookService.delete(id).subscribe(res => {
68 | this.control = true;
69 | this.loadStaticPage();
70 | this.message = ' Kayıt silinmiştir. ';
71 | this.alert.success(' Kayıt silinmiştir. ');
72 | },
73 | error => {
74 | this.alert.error(' Kayıt Bulunamamıştır.. ');
75 | this.message = ' Kayıt Bulunamamıştır.. ';
76 | });
77 | }
78 | get sf() { return this.searchBookForm.controls; }
79 | }
80 |
--------------------------------------------------------------------------------
/Library-Application/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 2.1.5.RELEASE
9 |
10 |
11 | com.example
12 | Library-Application
13 | 0.0.1-SNAPSHOT
14 | Library-Application
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-data-rest
29 |
30 |
31 | org.springframework.boot
32 | spring-boot-starter-web
33 |
34 |
35 | org.springframework.boot
36 | spring-boot-starter-security
37 |
38 |
39 |
40 | io.jsonwebtoken
41 | jjwt
42 | 0.9.1
43 |
44 |
45 | org.projectlombok
46 | lombok
47 | true
48 |
49 |
50 | org.modelmapper
51 | modelmapper
52 | 0.7.5
53 |
54 |
55 | org.springframework.boot
56 | spring-boot-devtools
57 | runtime
58 |
59 |
60 | org.postgresql
61 | postgresql
62 | runtime
63 |
64 |
65 | org.springframework.boot
66 | spring-boot-starter-test
67 | test
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 | org.springframework.boot
76 | spring-boot-maven-plugin
77 |
78 |
79 |
80 |
81 |
82 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/book/book-details/book-details.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { ActivatedRoute } from '@angular/router';
3 | import { Location } from '@angular/common';
4 | import { BookService } from 'src/app/services/book.service';
5 | import { FormGroup, Validators, FormBuilder } from '@angular/forms';
6 | import { Book } from '../Book';
7 | import { AlertifyService } from 'src/app/services/alertify.service';
8 |
9 | @Component({
10 | selector: 'app-book-details',
11 | templateUrl: './book-details.component.html',
12 | styleUrls: ['./book-details.component.css']
13 | })
14 | export class BookDetailsComponent implements OnInit {
15 |
16 | id: number;
17 | book = new Book();
18 | showModal = true;
19 | bookStatuses = [];
20 | //book update form parameters
21 | BookForm: FormGroup;
22 |
23 | constructor(private route: ActivatedRoute,
24 | private location: Location,
25 | private alert: AlertifyService,
26 | private bookService: BookService,
27 | private formBuilder: FormBuilder) { }
28 |
29 | ngOnInit() {
30 | this.loadBookDetails();
31 | this.LoadBookUpdateForm(this.book);
32 | }
33 |
34 | loadBookDetails() {
35 | this.getAllBookStatus();
36 | this.route.params.subscribe(params => {
37 | this.id = params['id'];
38 | });
39 | this.bookService.getById(this.id).subscribe(res => {
40 | this.book = res;
41 | });
42 | }
43 | LoadBookUpdateForm(res) {
44 | this.showModal = true;
45 | this.BookForm = this.formBuilder.group({
46 | 'id': [this.id, [Validators.required]],
47 | 'name': [res.name, [Validators.required]],
48 | 'publisher': [res.publisher, [Validators.required]],
49 | 'barcode': [res.barcode, [Validators.required]],
50 | 'content': [res.content, [Validators.required]],
51 | 'bookStatus': [res.bookStatus, [Validators.required]],
52 | 'authorId': [res.author.id]
53 | });
54 | }
55 | updateBook() {
56 | if (!this.BookForm.valid) {
57 | return;
58 | }
59 | this.bookService.put(this.id, this.BookForm.value).subscribe(
60 | res=>{
61 | this.loadBookDetails();
62 | this.LoadBookUpdateForm(this.book);
63 | this.showModal = false;
64 | this.alert.success('Kitap bilgileri güncellenmiştr.');
65 | },
66 | error=>{
67 | this.alert.error('Kitap bilgileri güncellenememiştir. Bir hata oluştu.')
68 | }
69 | );
70 | }
71 | getAllBookStatus(){
72 | this.bookService.getAllBookStatus().subscribe( res => {
73 | this.bookStatuses = res;
74 | });
75 | }
76 | get f1() { return this.BookForm.controls; }
77 | backClicked() {
78 | this.location.back();
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/library-webui/src/app/register/register.component.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/security/SecurityConfig.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.security;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.security.authentication.AuthenticationManager;
7 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
8 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
10 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
12 | import org.springframework.security.config.http.SessionCreationPolicy;
13 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
14 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
15 |
16 | import com.example.demo.service.imp.UserDetailsServiceImpl;
17 |
18 | @Configuration
19 | @EnableWebSecurity
20 | @EnableGlobalMethodSecurity(prePostEnabled = true)
21 | public class SecurityConfig extends WebSecurityConfigurerAdapter {
22 | @Autowired
23 | private UserDetailsServiceImpl userDetailsService;
24 |
25 | @Autowired
26 | private JwtAuthenticationEntryPoint unauthorizedHandler;
27 |
28 | @Override
29 | @Bean
30 | public AuthenticationManager authenticationManagerBean() throws Exception {
31 | return super.authenticationManagerBean();
32 | }
33 |
34 | @Autowired
35 | public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
36 | auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
37 | }
38 |
39 | // her bir requesti kendimiz şifreleyeceğimiz ve token haline getireceğimiz
40 | // classımızdır.
41 | @Bean
42 | public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
43 | return new JwtAuthenticationFilter();
44 | }
45 |
46 | @Override
47 | protected void configure(HttpSecurity http) throws Exception {
48 | http.cors().and().csrf().disable().authorizeRequests().antMatchers("/api/main/sign-up", "/api/main/sign-in")
49 | .permitAll().anyRequest().authenticated().and().exceptionHandling()
50 | .authenticationEntryPoint(unauthorizedHandler).and().sessionManagement()
51 | .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
52 | http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
53 | }
54 |
55 | // şifreleme algoritması ile hash lenip veritabanına yerleştiriliyor.
56 | @Bean
57 | public BCryptPasswordEncoder encoder() {
58 | return new BCryptPasswordEncoder();
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/security/JwtTokenUtil.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.security;
2 |
3 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
4 | import org.springframework.security.core.userdetails.UserDetails;
5 | import org.springframework.stereotype.Component;
6 |
7 | import com.example.demo.model.User;
8 |
9 | import io.jsonwebtoken.Claims;
10 | import io.jsonwebtoken.Jwts;
11 | import io.jsonwebtoken.SignatureAlgorithm;
12 |
13 | import java.util.Arrays;
14 | import java.util.Date;
15 | import java.util.function.Function;
16 |
17 | @Component
18 | public class JwtTokenUtil {
19 | // token kullanım süresi
20 | // 1Gün ==> saat * dakika * saniye * mili saniye
21 | // 1Gün
22 | public static final long ACCESS_TOKEN_VALIDITY_SECONDS = 24 * 60 * 60 * 1000;
23 |
24 | // token şifreleme ve çözme için kullanılan key (Yani JWT nin 3. partini )
25 | public static final String SIGNING_KEY = "hcelal";
26 |
27 | // token dan username ı aldığımız method
28 | public String getUsernameFromToken(String token) {
29 | return getClaimFromToken(token, Claims::getSubject);
30 | }
31 |
32 | // token nın biteceği tarihi öğrenme method
33 | public Date getExpirationDateFromToken(String token) {
34 | return getClaimFromToken(token, Claims::getExpiration);
35 | }
36 |
37 | public T getClaimFromToken(String token, Function claimsResolver) {
38 | final Claims claims = getAllClaimsFromToken(token);
39 | return claimsResolver.apply(claims);
40 | }
41 |
42 | private Claims getAllClaimsFromToken(String token) {
43 | return Jwts.parser().setSigningKey(SIGNING_KEY).parseClaimsJws(token).getBody();
44 | }
45 |
46 | // token nın süresi doldumu
47 | private Boolean isTokenExpired(String token) {
48 | final Date expiration = getExpirationDateFromToken(token);
49 | return expiration.before(new Date());
50 | }
51 |
52 | // User dan token generate işlemi
53 | public String generateToken(User user) {
54 | return doGenerateToken(user.getUsername());
55 | }
56 |
57 | // User name dan token generate işlemi
58 | private String doGenerateToken(String subject) {
59 |
60 | Claims claims = Jwts.claims().setSubject(subject);
61 | claims.put("scopes", Arrays.asList(new SimpleGrantedAuthority("USER")));
62 |
63 | return Jwts.builder().setClaims(claims)
64 | // imzalama yeri sunucu, domain gibi ..
65 | .setIssuer("http://hcelal.com")
66 | // imzalanma zamanı (saati)
67 | .setIssuedAt(new Date(System.currentTimeMillis()))
68 | // tokenın biteceği tarih
69 | // (şuanki zaman + belirlenen süre 24 saat mili saniye olarak)
70 | .setExpiration(new Date(System.currentTimeMillis() + ACCESS_TOKEN_VALIDITY_SECONDS))
71 | // şifreleme algoritmaso ve imzası ile (hcelal :D )
72 | .signWith(SignatureAlgorithm.HS256, SIGNING_KEY).compact();
73 | }
74 |
75 | public Boolean validateToken(String token, UserDetails userDetails) {
76 | final String username = getUsernameFromToken(token);
77 | return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
78 | }
79 |
80 | }
81 |
--------------------------------------------------------------------------------
/library-webui/src/polyfills.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * This file includes polyfills needed by Angular and is loaded before the app.
3 | * You can add your own extra polyfills to this file.
4 | *
5 | * This file is divided into 2 sections:
6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
8 | * file.
9 | *
10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
13 | *
14 | * Learn more in https://angular.io/guide/browser-support
15 | */
16 |
17 | /***************************************************************************************************
18 | * BROWSER POLYFILLS
19 | */
20 |
21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */
22 | // import 'classlist.js'; // Run `npm install --save classlist.js`.
23 |
24 | /**
25 | * Web Animations `@angular/platform-browser/animations`
26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
28 | */
29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`.
30 |
31 | /**
32 | * By default, zone.js will patch all possible macroTask and DomEvents
33 | * user can disable parts of macroTask/DomEvents patch by setting following flags
34 | * because those flags need to be set before `zone.js` being loaded, and webpack
35 | * will put import in the top of bundle, so user need to create a separate file
36 | * in this directory (for example: zone-flags.ts), and put the following flags
37 | * into that file, and then add the following code before importing zone.js.
38 | * import './zone-flags.ts';
39 | *
40 | * The flags allowed in zone-flags.ts are listed here.
41 | *
42 | * The following flags will work for all browsers.
43 | *
44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
47 | *
48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge
50 | *
51 | * (window as any).__Zone_enable_cross_context_check = true;
52 | *
53 | */
54 |
55 | /***************************************************************************************************
56 | * Zone JS is required by default for Angular itself.
57 | */
58 | import 'zone.js/dist/zone'; // Included with Angular CLI.
59 |
60 |
61 | /***************************************************************************************************
62 | * APPLICATION IMPORTS
63 | */
64 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/api/MainController.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.api;
2 |
3 | import org.modelmapper.ModelMapper;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.http.ResponseEntity;
6 | import org.springframework.security.authentication.AuthenticationManager;
7 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
8 | import org.springframework.security.core.AuthenticationException;
9 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
10 | import org.springframework.web.bind.annotation.CrossOrigin;
11 | import org.springframework.web.bind.annotation.GetMapping;
12 | import org.springframework.web.bind.annotation.RequestBody;
13 | import org.springframework.web.bind.annotation.RequestMapping;
14 | import org.springframework.web.bind.annotation.RequestMethod;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import com.example.demo.dto.LoginRequest;
18 | import com.example.demo.dto.RegistirationRequest;
19 | import com.example.demo.dto.TokenResponse;
20 | import com.example.demo.model.Student;
21 | import com.example.demo.model.User;
22 | import com.example.demo.repository.UserRepository;
23 | import com.example.demo.security.JwtTokenUtil;
24 | import com.example.demo.service.imp.UserServiceImp;
25 | import com.example.demo.util.ApiPaths;
26 |
27 | import javassist.NotFoundException;
28 |
29 | @RestController
30 | @RequestMapping(ApiPaths.MainCtrl.CTRL)
31 | @CrossOrigin
32 | public class MainController {
33 |
34 | private final AuthenticationManager authenticationManager;
35 |
36 | private final UserRepository userRepository;
37 | private final UserServiceImp userServiceImp;
38 |
39 | private final BCryptPasswordEncoder bCryptPasswordEncoder;
40 |
41 | private final ModelMapper modelMapper;
42 |
43 | @Autowired
44 | private JwtTokenUtil jwtTokenUtil;
45 |
46 | public MainController(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder,
47 | AuthenticationManager authenticationManager, ModelMapper modelMapper, UserServiceImp userServiceImp) {
48 | this.userRepository = userRepository;
49 | this.bCryptPasswordEncoder = bCryptPasswordEncoder;
50 | this.modelMapper = modelMapper;
51 | this.authenticationManager = authenticationManager;
52 | this.userServiceImp = userServiceImp;
53 | }
54 |
55 | @RequestMapping(value = "/sign-in", method = RequestMethod.POST)
56 | public ResponseEntity login(@RequestBody LoginRequest request) throws AuthenticationException {
57 | authenticationManager
58 | .authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
59 | final User user = userRepository.findByUsername(request.getUsername());
60 | final String token = jwtTokenUtil.generateToken(user);
61 | return ResponseEntity.ok(new TokenResponse(user.getUsername(), token));
62 | }
63 |
64 | @RequestMapping(value = "/sign-up", method = RequestMethod.POST)
65 | public ResponseEntity signUp(@RequestBody RegistirationRequest registirationRequest) throws Exception {
66 |
67 | Boolean result = userServiceImp.register(registirationRequest);
68 | return ResponseEntity.ok(result);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/security/JwtAuthenticationFilter.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.security;
2 |
3 | import java.io.IOException;
4 | import java.util.Arrays;
5 |
6 | import javax.servlet.FilterChain;
7 | import javax.servlet.ServletException;
8 | import javax.servlet.http.HttpServletRequest;
9 | import javax.servlet.http.HttpServletResponse;
10 |
11 | import org.springframework.beans.factory.annotation.Autowired;
12 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
13 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
14 | import org.springframework.security.core.context.SecurityContextHolder;
15 | import org.springframework.security.core.userdetails.UserDetails;
16 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
17 | import org.springframework.stereotype.Service;
18 | import org.springframework.web.filter.OncePerRequestFilter;
19 |
20 | import com.example.demo.service.imp.UserDetailsServiceImpl;
21 |
22 | import io.jsonwebtoken.ExpiredJwtException;
23 | import io.jsonwebtoken.SignatureException;
24 | import lombok.extern.slf4j.Slf4j;
25 |
26 | @Service
27 | @Slf4j
28 | public class JwtAuthenticationFilter extends OncePerRequestFilter {
29 |
30 | public static final String TOKEN_PREFIX = "Bearer ";
31 | public static final String HEADER_STRING = "Authorization";
32 |
33 | @Autowired
34 | private UserDetailsServiceImpl userDetailsService;
35 |
36 | @Autowired
37 | private JwtTokenUtil jwtTokenUtil;
38 |
39 | @Override
40 | protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
41 | throws IOException, ServletException {
42 | String header = req.getHeader(HEADER_STRING);
43 | String username = null;
44 | String authToken = null;
45 | if (header != null && header.startsWith(TOKEN_PREFIX)) {
46 | authToken = header.replace(TOKEN_PREFIX, "");
47 | try {
48 | username = jwtTokenUtil.getUsernameFromToken(authToken);
49 | } catch (IllegalArgumentException e) {
50 | // log.error("an error occured during getting username from token", e);
51 | } catch (ExpiredJwtException e) {
52 | // log.warn("the token is expired and not valid anymore", e);
53 | } catch (SignatureException e) {
54 | // log.error("Authentication Failed. Username or Password not valid.");
55 | }
56 | } else {
57 | // log.warn("couldn't find bearer string, will ignore the header");
58 | }
59 | if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
60 |
61 | UserDetails userDetails = userDetailsService.loadUserByUsername(username);
62 |
63 | if (jwtTokenUtil.validateToken(authToken, userDetails)) {
64 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
65 | userDetails, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
66 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
67 | // log.info("authenticated user " + username + ", setting security context");
68 | SecurityContextHolder.getContext().setAuthentication(authentication);
69 | }
70 | }
71 |
72 | chain.doFilter(req, res);
73 | }
74 | }
--------------------------------------------------------------------------------
/library-webui/src/app/services/student.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 | import { ApiService } from './general/api.service';
3 | import { HttpClient, HttpHeaders } from '@angular/common/http';
4 | import { Observable } from 'rxjs';
5 | import { map } from 'rxjs/internal/operators';
6 |
7 | @Injectable({
8 | providedIn: 'root'
9 | })
10 | export class StudentService {
11 | STUDENT_PATH = '/student';
12 | STUDENT_PATH_PAGE = '/pagination';
13 | GET_BOOK_PATH = '/get-book';
14 | LEAVE_BOOK_PATH = '/leave-book';
15 | CITIES_PATH = '/cities';
16 | FIND_BY_TC_NO = '/find';
17 | constructor(private apiService: ApiService,
18 | private http: HttpClient) { }
19 |
20 | getAllPageable(page){
21 | return this.apiService.getAllPageable(this.STUDENT_PATH + this.STUDENT_PATH_PAGE, page ).pipe(map(
22 | res => {
23 | if (res) {
24 | return res;
25 | } else {
26 | return {};
27 | }
28 | }
29 | ));
30 | }
31 | getById(id: number): Observable {
32 | return this.apiService.getById(this.STUDENT_PATH + '/' + id).pipe(map(
33 | res => {
34 | if (res) {
35 | return res;
36 | } else {
37 | return {};
38 | }
39 | }
40 | ));
41 | }
42 | findAllByName(name: string): Observable {
43 | return this.apiService.findAllByName(this.STUDENT_PATH + this.FIND_BY_TC_NO + '/' + name).pipe(map(
44 | res => {
45 | if (res) {
46 | return res;
47 | } else {
48 | return {};
49 | }
50 | }
51 | ));
52 | }
53 | post(params): Observable {
54 | return this.apiService.post(this.STUDENT_PATH, params).pipe(map(
55 | res => {
56 | if (res) {
57 | return res;
58 | } else {
59 | return {};
60 | }
61 | }
62 | ));
63 | }
64 | put(id: number, book): Observable {
65 | return this.apiService.put(this.STUDENT_PATH + '/' + id, book).pipe(map(
66 | res => {
67 | if (res) {
68 | return res;
69 | } else {
70 | return {};
71 | }
72 | }
73 | ));
74 | }
75 | getBook(params): Observable {
76 | return this.apiService.patch(this.STUDENT_PATH + this.GET_BOOK_PATH, params).pipe(map(
77 | res => {
78 | if (res) {
79 | return res;
80 | } else {
81 | return {};
82 | }
83 | }
84 | ));
85 | }
86 | leaveBook(params): Observable {
87 | return this.apiService.patch(this.STUDENT_PATH + this.LEAVE_BOOK_PATH, params).pipe(map(
88 | res => {
89 | if (res) {
90 | return res;
91 | } else {
92 | return {};
93 | }
94 | }
95 | ));
96 | }
97 | delete(id): Observable {
98 | return this.apiService.delete(this.STUDENT_PATH + '/' + id).pipe(map(
99 | res => {
100 | if (res) {
101 | return res;
102 | } else {
103 | return {};
104 | }
105 | }
106 | ));
107 | }
108 | getAllCities(): Observable {
109 | return this.apiService.getAll(this.STUDENT_PATH + this.CITIES_PATH).pipe(map(
110 | res => {
111 | if (res) {
112 | return res;
113 | } else {
114 | return {};
115 | }
116 | }
117 | ));
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/api/AuthorRestController.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.api;
2 |
3 | import java.util.List;
4 |
5 | import javax.validation.Valid;
6 |
7 | import org.springframework.data.domain.Pageable;
8 | import org.springframework.http.ResponseEntity;
9 | import org.springframework.web.bind.annotation.CrossOrigin;
10 | import org.springframework.web.bind.annotation.DeleteMapping;
11 | import org.springframework.web.bind.annotation.GetMapping;
12 | import org.springframework.web.bind.annotation.PathVariable;
13 | import org.springframework.web.bind.annotation.PostMapping;
14 | import org.springframework.web.bind.annotation.PutMapping;
15 | import org.springframework.web.bind.annotation.RequestBody;
16 | import org.springframework.web.bind.annotation.RequestMapping;
17 | import org.springframework.web.bind.annotation.RequestParam;
18 | import org.springframework.web.bind.annotation.RestController;
19 | import com.example.demo.dto.AuthorDto;
20 | import com.example.demo.dto.AuthorOneDto;
21 | import com.example.demo.dto.AuthorUpdateDto;
22 | import com.example.demo.dto.BookDto;
23 | import com.example.demo.dto.BookUpdateDto;
24 | import com.example.demo.service.imp.AuthorServiceImp;
25 | import com.example.demo.util.ApiPaths;
26 | import com.example.demo.util.TPage;
27 |
28 | import javassist.NotFoundException;
29 |
30 | @RestController
31 | @RequestMapping(ApiPaths.AuthorCtrl.CTRL)
32 | @CrossOrigin
33 | public class AuthorRestController {
34 |
35 | private final AuthorServiceImp authorServiceImp;
36 |
37 | public AuthorRestController(AuthorServiceImp authorServiceImp) {
38 | super();
39 | this.authorServiceImp = authorServiceImp;
40 | }
41 |
42 | // http://localhost:8182/api/author
43 | @GetMapping()
44 | public ResponseEntity> getAll() throws NotFoundException {
45 | List authorDtos = authorServiceImp.getAll();
46 | return ResponseEntity.ok(authorDtos);
47 | }
48 |
49 | // localhost:8182/api/author/pagination?page=1&size=3
50 | @GetMapping("/pagination")
51 | public ResponseEntity> getAllByPagination(Pageable pageable) throws NotFoundException {
52 | TPage data = authorServiceImp.getAllPageable(pageable);
53 | return ResponseEntity.ok(data);
54 | }
55 |
56 | // http://localhost:8182/api/author/find?name=name
57 | @GetMapping("/find")
58 | public ResponseEntity> findAllByName(@RequestParam String name) throws NotFoundException {
59 | List authorDtos = authorServiceImp.findAllByName(name);
60 | return ResponseEntity.ok(authorDtos);
61 | }
62 |
63 | // http://localhost:8182/api/author/2
64 | @GetMapping("/{id}")
65 | public ResponseEntity getOneAuthor(@PathVariable(name = "id", required = true) Long id)
66 | throws NotFoundException {
67 | return ResponseEntity.ok(authorServiceImp.getOne(id));
68 | }
69 |
70 | @PostMapping()
71 | public ResponseEntity createAuthor(@Valid @RequestBody AuthorDto authorDto) {
72 | return ResponseEntity.ok(authorServiceImp.save(authorDto));
73 | }
74 |
75 | @PutMapping("/{id}")
76 | public ResponseEntity updateAuthor(@PathVariable(name = "id", required = true) Long id,
77 | @Valid @RequestBody AuthorUpdateDto authorUpdateDto) throws NotFoundException {
78 | return ResponseEntity.ok(authorServiceImp.update(id, authorUpdateDto));
79 | }
80 |
81 | @DeleteMapping("/{id}")
82 | public ResponseEntity deleteBook(@PathVariable(name = "id", required = true) Long id)
83 | throws NotFoundException {
84 | return ResponseEntity.ok(authorServiceImp.delete(id));
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/student.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { BookService } from 'src/app/services/book.service';
3 | import { FormBuilder, FormGroup, Validators } from '@angular/forms';
4 | import { ActivatedRoute } from '@angular/router';
5 | import { StudentService } from 'src/app/services/student.service';
6 | import { Page } from 'src/app/shared/Page';
7 | import { AlertifyService } from 'src/app/services/alertify.service';
8 |
9 | @Component({
10 | selector: 'app-student',
11 | templateUrl: './student.component.html',
12 | styleUrls: ['./student.component.css']
13 | })
14 | export class StudentComponent implements OnInit {
15 |
16 | message: string | undefined;
17 | //ngx datatable parameters
18 | rows = [];
19 | page = new Page();
20 | control = true;
21 | //student insert form parameters
22 | cities: Array = [];
23 | StudentInsertForm: FormGroup;
24 | showModal = true;
25 | constructor(private route: ActivatedRoute,
26 | private alert: AlertifyService,
27 | private studentService: StudentService,
28 | private formBuilder: FormBuilder) { }
29 |
30 | ngOnInit() {
31 | this.loadStaticPage();
32 | }
33 | loadStaticPage(){
34 | this.setPage({ offset: 0 });
35 | this.LoadStudentInsertForm();
36 | }
37 | setPage(pageInfo) {
38 | this.control = true;
39 | this.page.page = pageInfo.offset;
40 | this.studentService.getAllPageable(this.page).subscribe(pagedData => {
41 | this.page.size = pagedData.size;
42 | this.page.page = pagedData.page;
43 | this.page.totalElements = pagedData.totalElements;
44 | this.rows = pagedData.content;
45 | });
46 | }
47 |
48 | LoadStudentInsertForm(){
49 | this.getAllCities();
50 | this.showModal = true;
51 | this.StudentInsertForm = this.formBuilder.group({
52 | 'fullname': [null, [Validators.required]],
53 | 'tcNo': [null, [Validators.min(10000000000),Validators.max(100000000000),Validators.required]],
54 | 'email': [null, [Validators.required,Validators.email]],
55 | 'phone': [null, [Validators.required]],
56 | 'address': [null, [Validators.required]],
57 | 'city': [null, [Validators.required]],
58 | 'university': [null, [Validators.required]],
59 | 'department': [null, [Validators.required]],
60 | });
61 | }
62 |
63 | insertStudent(){
64 | if (!this.StudentInsertForm.valid) {
65 | return;
66 | }
67 | this.studentService.post(this.StudentInsertForm.value).subscribe(res=>{
68 | this.loadStaticPage();
69 | console.log("insert student");
70 | this.message = ' Kayıt Yapılmıştır.. ';
71 | this.showModal = false;
72 | this.alert.success(' Kayıt Yapılmıştır.. ');
73 | this.message = ' Kayıt işlemi başarılı.';
74 | }, error => {
75 | this.alert.error(' Kayıt Yapılamadı. Email adresi veya tc no hatalıdır. ' );
76 | this.message = ' Kayıt Yapılamadı. Email adresi veya tc no hatalıdır.' ;
77 | });
78 | }
79 |
80 | getAllCities(){
81 | this.studentService.getAllCities().subscribe(res => {
82 | this.cities = res;
83 | });
84 | }
85 | deleteStudent(id){
86 | console.log(id);
87 | this.studentService.delete(id).subscribe(res => {
88 | this.loadStaticPage();
89 | this.message = ' Kayıt Silinmiştir. ';
90 | this.alert.warning(' Kayıt Silinmiştir. ');
91 | }, error => {
92 | this.alert.error(' Hay Aksi Kayıt Silinemedi. ' );
93 | this.message = ' Hay Aksi Kayıt Silinemedi. ' ;
94 | });
95 | }
96 | get sif() { return this.StudentInsertForm.controls; }
97 | }
98 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/api/BookRestController.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.api;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | import javax.validation.Valid;
7 |
8 | import org.springframework.data.domain.Pageable;
9 | import org.springframework.http.ResponseEntity;
10 | import org.springframework.web.bind.annotation.CrossOrigin;
11 | import org.springframework.web.bind.annotation.DeleteMapping;
12 | import org.springframework.web.bind.annotation.GetMapping;
13 | import org.springframework.web.bind.annotation.PathVariable;
14 | import org.springframework.web.bind.annotation.PostMapping;
15 | import org.springframework.web.bind.annotation.PutMapping;
16 | import org.springframework.web.bind.annotation.RequestBody;
17 | import org.springframework.web.bind.annotation.RequestMapping;
18 | import org.springframework.web.bind.annotation.ResponseBody;
19 | import org.springframework.web.bind.annotation.RestController;
20 |
21 | import com.example.demo.dto.AuthorDto;
22 | import com.example.demo.dto.BookDto;
23 | import com.example.demo.dto.BookOneDto;
24 | import com.example.demo.dto.BookUpdateDto;
25 | import com.example.demo.model.BookStatus;
26 | import com.example.demo.service.imp.AuthorServiceImp;
27 | import com.example.demo.service.imp.BookServiceImp;
28 | import com.example.demo.util.ApiPaths;
29 | import com.example.demo.util.TPage;
30 |
31 | import javassist.NotFoundException;
32 |
33 | @RestController
34 | @RequestMapping(ApiPaths.BookCtrl.CTRL)
35 | @CrossOrigin
36 | public class BookRestController {
37 |
38 | private final AuthorServiceImp authorServiceImp;
39 | private final BookServiceImp bookServiceImp;
40 |
41 | public BookRestController(AuthorServiceImp authorServiceImp, BookServiceImp bookServiceImp) {
42 | super();
43 | this.authorServiceImp = authorServiceImp;
44 | this.bookServiceImp = bookServiceImp;
45 | }
46 |
47 | @GetMapping()
48 | public ResponseEntity> getAll() throws NotFoundException {
49 | return ResponseEntity.ok(bookServiceImp.getAll());
50 | }
51 |
52 | // localhost:8182/api/book/pagination?page=1&size=3
53 | @GetMapping("/pagination")
54 | public ResponseEntity> getAllByPagination(Pageable pageable) throws NotFoundException {
55 | TPage data = bookServiceImp.getAllPageable(pageable);
56 | return ResponseEntity.ok(data);
57 | }
58 |
59 | // localhost:8182/api/book/1
60 | // localhost:8182/api/book/5
61 | @GetMapping("/{id}")
62 | public ResponseEntity getAll(@PathVariable(name = "id", required = true) Long id)
63 | throws NotFoundException {
64 | return ResponseEntity.ok(bookServiceImp.getOne(id));
65 | }
66 |
67 | @GetMapping("/find/{name}")
68 | public ResponseEntity> findByName(@PathVariable(name = "name", required = true) String name)
69 | throws NotFoundException {
70 | return ResponseEntity.ok(bookServiceImp.SearchBooksByName(name));
71 | }
72 |
73 | @PostMapping()
74 | public ResponseEntity createProject(@Valid @RequestBody BookOneDto bookOneDto) throws Exception {
75 | return ResponseEntity.ok(bookServiceImp.save(bookOneDto));
76 | }
77 |
78 | @PutMapping("/{id}")
79 | public ResponseEntity updateBook(@PathVariable(name = "id", required = true) Long id,
80 | @Valid @RequestBody BookUpdateDto bookUpdateDto) throws NotFoundException {
81 | return ResponseEntity.ok(bookServiceImp.update(id, bookUpdateDto));
82 | }
83 |
84 | @DeleteMapping("/{id}")
85 | public ResponseEntity deleteBook(@PathVariable(name = "id", required = true) Long id)
86 | throws NotFoundException {
87 | return ResponseEntity.ok(bookServiceImp.delete(id));
88 | }
89 |
90 | @GetMapping("/statuses")
91 | public ResponseEntity> getAllBookStatus() {
92 | return ResponseEntity.ok(Arrays.asList(BookStatus.values()));
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/api/StudentRestController.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.api;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | import javax.validation.Valid;
7 |
8 | import org.springframework.data.domain.Pageable;
9 | import org.springframework.http.ResponseEntity;
10 | import org.springframework.web.bind.annotation.CrossOrigin;
11 | import org.springframework.web.bind.annotation.DeleteMapping;
12 | import org.springframework.web.bind.annotation.GetMapping;
13 | import org.springframework.web.bind.annotation.PatchMapping;
14 | import org.springframework.web.bind.annotation.PathVariable;
15 | import org.springframework.web.bind.annotation.PostMapping;
16 | import org.springframework.web.bind.annotation.PutMapping;
17 | import org.springframework.web.bind.annotation.RequestBody;
18 | import org.springframework.web.bind.annotation.RequestMapping;
19 | import org.springframework.web.bind.annotation.RestController;
20 | import com.example.demo.dto.AuthorDto;
21 | import com.example.demo.dto.AuthorUpdateDto;
22 | import com.example.demo.dto.BookUpdateDto;
23 | import com.example.demo.dto.StudenPatchtDto;
24 | import com.example.demo.dto.StudentDto;
25 | import com.example.demo.model.BookStatus;
26 | import com.example.demo.model.City;
27 | import com.example.demo.service.imp.AuthorServiceImp;
28 | import com.example.demo.service.imp.StudentServiceImp;
29 | import com.example.demo.util.ApiPaths;
30 | import com.example.demo.util.TPage;
31 |
32 | import javassist.NotFoundException;
33 |
34 | @RestController
35 | @RequestMapping(ApiPaths.StudentCtrl.CTRL)
36 | @CrossOrigin
37 | public class StudentRestController {
38 |
39 | private final StudentServiceImp studentServiceImp;
40 |
41 | public StudentRestController(StudentServiceImp studentServiceImp) {
42 | super();
43 | this.studentServiceImp = studentServiceImp;
44 | }
45 |
46 | @GetMapping()
47 | public ResponseEntity> getAll() throws NotFoundException {
48 | List customerDtos = studentServiceImp.getAll();
49 | return ResponseEntity.ok(customerDtos);
50 | }
51 |
52 | // localhost:8182/api/student/pagination?page=1&size=3
53 | @GetMapping("/pagination")
54 | public ResponseEntity> getAllByPagination(Pageable pageable) throws NotFoundException {
55 | TPage data = studentServiceImp.getAllPageable(pageable);
56 | return ResponseEntity.ok(data);
57 | }
58 |
59 | @GetMapping("/{id}")
60 | public ResponseEntity selectStudent(@PathVariable(name = "id", required = true) Long id)
61 | throws NotFoundException {
62 | return ResponseEntity.ok(studentServiceImp.findById(id));
63 | }
64 |
65 | @PostMapping()
66 | public ResponseEntity createStudent(@Valid @RequestBody StudentDto studentDto) throws Exception {
67 | return ResponseEntity.ok(studentServiceImp.save(studentDto));
68 | }
69 |
70 | @PutMapping("/{id}")
71 | public ResponseEntity updateStudent(@PathVariable(name = "id", required = true) Long id,
72 | @Valid @RequestBody StudentDto studentDto) throws Exception {
73 | return ResponseEntity.ok(studentServiceImp.update(id, studentDto));
74 | }
75 |
76 | @PatchMapping("/get-book")
77 | public ResponseEntity getBookForStudent(@Valid @RequestBody StudenPatchtDto studenPatchtDto)
78 | throws NotFoundException {
79 | // @Valid @RequestBody Long bookId ) throws NotFoundException {
80 | return ResponseEntity.ok(studentServiceImp.getBookForStudent(studenPatchtDto));
81 | }
82 |
83 | @PatchMapping("/leave-book")
84 | public ResponseEntity leaveBookForStudent(@Valid @RequestBody StudenPatchtDto studenPatchtDto)
85 | throws NotFoundException {
86 |
87 | return ResponseEntity.ok(studentServiceImp.leaveBookForStudent(studenPatchtDto));
88 | }
89 |
90 | @DeleteMapping("/{id}")
91 | public ResponseEntity deleteBook(@PathVariable(name = "id", required = true) Long id)
92 | throws NotFoundException {
93 | return ResponseEntity.ok(studentServiceImp.delete(id));
94 | }
95 |
96 | @GetMapping("/cities")
97 | public ResponseEntity> getAllBookStatus() {
98 | return ResponseEntity.ok(Arrays.asList(City.values()));
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/book/book.component.html:
--------------------------------------------------------------------------------
1 | Kitaplar
2 |
3 |
4 |
5 |
6 | Dikkat !!! {{message}}
7 |
10 |
11 |
24 |
25 |
26 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | Detaylı Gör
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 | | id |
60 | Name |
61 | barcode |
62 | Author Name |
63 | publisher |
64 | bookStatus |
65 | Student |
66 | İşlemler |
67 |
68 |
69 |
70 |
71 | | {{book.id}} |
72 | {{book.name}} |
73 | {{book.barcode}} |
74 | {{book.author.name}} |
75 | {{book.publisher}} |
76 | {{book.bookStatus}} |
77 | {{book.student.fullname}} |
78 |
79 | |
80 |
81 |
82 | Detaylı Gör
83 |
84 | |
85 |
86 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/user-detail/user-detail.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { ActivatedRoute, Router } from '@angular/router';
3 | import { FormBuilder, FormGroup, Validators } from '@angular/forms';
4 | import { Location } from '@angular/common';
5 | import { UserService } from 'src/app/services/user.service';
6 | import { User } from './User';
7 | import { AlertifyService } from 'src/app/services/alertify.service';
8 |
9 | @Component({
10 | selector: 'app-user-detail',
11 | templateUrl: './user-detail.component.html',
12 | styleUrls: ['./user-detail.component.css']
13 | })
14 | export class UserDetailComponent implements OnInit {
15 | currentUser = {};
16 | error = '';
17 | username = '';
18 | user = new User();
19 | message: string | undefined;
20 | //User update form parameters
21 | UserUpdateForm: FormGroup;
22 | showModal = false ;
23 |
24 | //Password update form parameters
25 | PasswordUpdateForm: FormGroup;
26 | constructor(private route: ActivatedRoute,
27 | private location: Location,
28 | private userService: UserService,
29 | private alert: AlertifyService,
30 | private router: Router,
31 | private formBuilder: FormBuilder) { }
32 |
33 | ngOnInit() {
34 | this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
35 | this.loadUserDetail();
36 | this.loadUserUpdateForm();
37 | this.loadPasswordUpdateForm();
38 | }
39 |
40 | loadUserDetail() {
41 | this.route.params.subscribe(params => {
42 | this.username = params['username'];
43 | });
44 | this.userService.getByName(this.username).subscribe(
45 | res => {
46 | this.user = res;
47 | this.loadUserUpdateForm();
48 | },
49 | error => {
50 | this.alert.error('hata : '+error + '
Daha sonra tekrar deneyiniz.');
51 | this.LoadBackPage();
52 | }
53 | );
54 |
55 | }
56 |
57 | loadUserUpdateForm(){
58 | this.UserUpdateForm = this.formBuilder.group({
59 | 'username': [this.user.username, [Validators.required]],
60 | 'firstname': [this.user.firstname, [Validators.required]],
61 | 'lastname': [this.user.lastname, [Validators.required]],
62 | 'email': [this.user.email, [Validators.required, Validators.email]],
63 | });
64 | }
65 | loadPasswordUpdateForm(){
66 | this.PasswordUpdateForm = this.formBuilder.group({
67 | 'username': [this.currentUser['username'], [Validators.required]],
68 | 'password': [null, [Validators.required]],
69 | 'newpassword': [null, [Validators.required]],
70 | 'newpassword2': [null, [Validators.required]],
71 | });
72 | }
73 |
74 | updateUser(){
75 | if (!this.UserUpdateForm.valid) {
76 | return;
77 | }
78 | this.userService.put(this.username, this.UserUpdateForm.value).subscribe(
79 | res => {
80 | this.alert.success('Güncelleme işlemi başarılı..');
81 | this.router.navigate(['/login']);
82 | },
83 | error => {
84 | this.alert.error('Hata : ' + error);
85 | this.message = error;
86 | }
87 | );
88 | }
89 |
90 | updatePassword(){
91 |
92 |
93 | if (!this.PasswordUpdateForm.valid) {
94 | return;
95 | }
96 | if(this.PasswordUpdateForm.value['newpassword'] === this.PasswordUpdateForm.value['newpassword2']){
97 | this.error = '';
98 | this.userService.changePassword(this.PasswordUpdateForm.value).subscribe(
99 | res => {
100 | this.alert.success('Şifreniz güncellenmiştir.');
101 | this.router.navigate(['/login']);
102 | },
103 | error => {
104 | this.alert.error('Mevcut şifrenizi yanlış girdiniz.');
105 | this.error = 'Mevcut şifrenizi yanlış girdiniz.';
106 | }
107 | );
108 | } else {
109 | this.alert.error('Şifreler aynı olmak zorundadır.');
110 | this.error = 'Şifreler aynı olmak zorundadır.';
111 | }
112 | }
113 |
114 | get pf() { return this.PasswordUpdateForm.controls; }
115 | get uf() { return this.UserUpdateForm.controls; }
116 |
117 | LoadBackPage() {
118 | this.location.back();
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/author/author.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
2 | import { AuthorService } from 'src/app/services/author.service';
3 | import { Page } from 'src/app/shared/Page';
4 | import { ModalDirective } from 'ngx-bootstrap';
5 | import { FormGroup, FormBuilder, Validators } from '@angular/forms';
6 | import { AlertifyService } from 'src/app/services/alertify.service';
7 |
8 | @Component({
9 | selector: 'app-author',
10 | templateUrl: './author.component.html',
11 | styleUrls: ['./author.component.css']
12 | })
13 | export class AuthorComponent implements OnInit {
14 | authors = [];
15 | rows = [];
16 | cols = [];
17 | page = new Page();
18 | control = true;
19 | controlAuthorForm = true;
20 | //form parameters
21 | AuthorForm: FormGroup;
22 |
23 | searchForm: FormGroup;
24 | message: string | undefined;
25 | constructor(private authorService: AuthorService,
26 | private alert: AlertifyService,
27 | private formBuilder: FormBuilder) { }
28 |
29 | ngOnInit() {
30 | this.control = true;
31 | this.loadStaticPage();
32 | }
33 |
34 | loadStaticPage(){
35 | this.setPage({ offset: 0 });
36 | this.searchForm= this.formBuilder.group({
37 | 'name': [null, [Validators.minLength(3)]]
38 | });
39 | this.AuthorForm = this.formBuilder.group({
40 | 'name': [null, [Validators.required]],
41 | 'surname': [null, [Validators.required]],
42 | 'about': [null, [Validators.required]],
43 | 'email': [null, [Validators.email]],
44 | 'phone': [null, [Validators.required]]
45 | });
46 | }
47 |
48 | loadAuthors(){
49 | this.authorService.getAll().subscribe(res => {
50 | this.authors = res;
51 | });
52 | }
53 |
54 | loadAuthorFormPanel(){
55 | this.controlAuthorForm=true;
56 | this.AuthorForm = this.formBuilder.group({
57 | 'name': [null, [Validators.required]],
58 | 'surname': [null, [Validators.required]],
59 | 'about': [null, [Validators.required]],
60 | 'email': [null, [Validators.email,Validators.required]],
61 | 'phone': [null, [Validators.required]],
62 | });
63 | }
64 |
65 | setPage(pageInfo) {
66 | this.page.page = pageInfo.offset;
67 | this.authorService.getAllPageable(this.page).subscribe(pagedData => {
68 | this.page.size = pagedData.size;
69 | this.page.page = pagedData.page;
70 | this.page.totalElements = pagedData.totalElements;
71 | this.rows = pagedData.content;
72 | });
73 | }
74 | saveAuthor(){
75 | if (!this.AuthorForm.valid) {
76 | return;
77 | }
78 | this.authorService.post(this.AuthorForm.value).subscribe(
79 | res => {
80 | this.AuthorForm.reset();
81 | this.setPage({ offset: 0 });
82 | this.controlAuthorForm = false;
83 | this.message = 'Kayıt işlemi başarılı.';
84 | this.alert.success( 'Kayıt işlemi başarılı.');
85 | },
86 | error =>{
87 | this.alert.error('Kayıt işlemi başarısız
Hata : ' + error);
88 | this.message = 'Kayıt işlemi başarısız';
89 | });
90 | }
91 | deleteAuthor(id){
92 | console.log(id);
93 | this.authorService.delete(id).subscribe(
94 | res=>{
95 | this.alert.success('Kaydınız silinmiştir.');
96 | this.setPage({ offset: 0 });
97 | this.control = true;
98 | this.loadStaticPage();
99 | },
100 | error =>{
101 | this.alert.error('Kaydınız silinememiştir..
Hata : ' + error);
102 | this.loadStaticPage();
103 | }
104 | );
105 | }
106 |
107 | searchAuthor(){
108 | if (!this.searchForm.valid) {
109 | return;
110 | }
111 | this.authorService.findAllByName(this.searchForm.value['name']).subscribe(res => {
112 | this.authors = res;
113 | this.control = false;
114 | this.message = 'Kayıtlar bulunmuştur.';
115 | this.alert.success('Kayıtlar bulunmuştur.');
116 | },
117 | error =>{
118 | this.message = 'Herhangi bir kayıt bulunamamıştır' ;
119 | this.alert.error('Herhangi bir kayıt bulunamamıştır ');
120 | this.control = true;
121 | this.loadStaticPage();
122 | });
123 | }
124 |
125 | get sf() { return this.searchForm.controls; }
126 | get f() { return this.AuthorForm.controls; }
127 | }
128 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/student-details/student-details.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { ActivatedRoute } from '@angular/router';
3 | import { Location } from '@angular/common';
4 | import { FormBuilder, FormGroup, Validators } from '@angular/forms';
5 | import { BookService } from 'src/app/services/book.service';
6 | import { StudentService } from 'src/app/services/student.service';
7 | import { Student } from '../Student';
8 | import { Book } from '../../book/Book';
9 | import { AlertifyService } from 'src/app/services/alertify.service';
10 |
11 | @Component({
12 | selector: 'app-student-details',
13 | templateUrl: './student-details.component.html',
14 | styleUrls: ['./student-details.component.css']
15 | })
16 | export class StudentDetailsComponent implements OnInit {
17 | message: string | undefined;
18 | id: number;
19 | student = new Student();
20 | books: Array;
21 | //student update form parameters
22 | StudentUpdateForm: FormGroup;
23 | updated = true;
24 | cities: Array = [];
25 |
26 | //leave book parameters
27 | leaveBookForm: FormGroup;
28 | constructor(private route: ActivatedRoute,
29 | private location: Location,
30 | private alert: AlertifyService,
31 | private studentService: StudentService,
32 | private formBuilder: FormBuilder) { }
33 |
34 | ngOnInit() {
35 | this.loadStudentDetails();
36 | this.LoadStudentUpdateForm(this.student);
37 | }
38 |
39 | loadStudentDetails() {
40 | this.getAllCities();
41 |
42 | this.route.params.subscribe(params => {
43 | this.id = params['id'];
44 | });
45 |
46 | this.leaveBookForm = this.formBuilder.group({
47 | 'bookId': [null, [Validators.required]],
48 | 'studentId': [this.id, [Validators.required]]
49 | });
50 |
51 | this.studentService.getById(this.id).subscribe(
52 | res => {
53 | this.student = res;
54 | this.books = res['books'];
55 | },
56 | error => {
57 | this.message = 'Bu id : ' + this.id + ' bir kullanıcı bulunamadı.';
58 | });
59 | }
60 |
61 | LoadStudentUpdateForm(res){
62 | this.updated = true;
63 | this.StudentUpdateForm = this.formBuilder.group({
64 | 'fullname': [res.fullname, [Validators.required]],
65 | 'tcNo': [res.tcNo, [Validators.min(10000000000), Validators.max(100000000000), Validators.required]],
66 | 'email': [res.email, [Validators.required,Validators.email]],
67 | 'phone': [res.phone, [Validators.required]],
68 | 'address': [res.address, [Validators.required]],
69 | 'city': [res.city, [Validators.required]],
70 | 'university': [res.university, [Validators.required]],
71 | 'department': [res.department, [Validators.required]],
72 | });
73 | }
74 |
75 | updateStudent(){
76 | if (!this.StudentUpdateForm.valid) {
77 | return;
78 | }
79 | this.studentService.put(this.id, this.StudentUpdateForm.value).subscribe(
80 | res =>{
81 | this.loadStudentDetails();
82 | if(this.id == res['id']){
83 | this.alert.success(' kayıt başarıyla yapılmıştır.');
84 | this.message = ' kayıt başarıyla yapılmıştır.';
85 | this.updated = false;
86 | }
87 | },
88 | error =>{
89 | this.alert.error(' kayıt yapılamamıştır');
90 | this.message = ' kayıt yapılamamıştır';
91 | });
92 | }
93 | getAllCities(){
94 | this.studentService.getAllCities().subscribe(res => {
95 | this.cities = res;
96 | });
97 | }
98 |
99 | leaveBook(bookId){
100 | this.leaveBookForm = this.formBuilder.group({
101 | 'bookId': [bookId, [Validators.required]],
102 | 'studentId': [this.id, [Validators.required]]
103 | });
104 | this.studentService.leaveBook(this.leaveBookForm.value).subscribe(
105 | res => {
106 | this.loadStudentDetails();
107 | this.LoadStudentUpdateForm(this.student);
108 | this.alert.success( ' Silme işlemi başarılıdır. ');
109 | this.message = ' Silme işlemi başarılıdır. ';
110 | }
111 | , error => {
112 | this.alert.error(' Silme işlemi başarısız. : ' + error);
113 | this.message = ' Silme işlemi başarısız. : ' + error;
114 | }
115 | );
116 | }
117 | get suf() { return this.StudentUpdateForm.controls; }
118 | backClicked() {
119 | this.location.back();
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/student/get-book/get-book.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { ActivatedRoute } from '@angular/router';
3 | import { Location } from '@angular/common';
4 | import { Page } from 'src/app/shared/Page';
5 | import { BookService } from 'src/app/services/book.service';
6 | import { FormBuilder, Validators, FormGroup } from '@angular/forms';
7 | import { StudentService } from 'src/app/services/student.service';
8 | import { Student } from '../Student';
9 | import { AlertifyService } from 'src/app/services/alertify.service';
10 |
11 | @Component({
12 | selector: 'app-get-book',
13 | templateUrl: './get-book.component.html',
14 | styleUrls: ['./get-book.component.css']
15 | })
16 | export class GetBookComponent implements OnInit {
17 | message: string | undefined;
18 | id: number;
19 | student = new Student();
20 |
21 | //ngx datatable parameters
22 | rows = [];
23 | cols = [];
24 | page = new Page();
25 | control = true;
26 | books = [];
27 | bookId: any;
28 |
29 | //search book form
30 | searchBookForm: FormGroup;
31 | getbookForm: FormGroup;
32 | constructor(private route: ActivatedRoute,
33 | private location: Location,
34 | private alert: AlertifyService,
35 | private bookService: BookService,
36 | private studentService: StudentService,
37 | private formBuilder: FormBuilder) { }
38 |
39 | ngOnInit() {
40 | this.control = true;
41 | this.loadStaticPage();
42 | }
43 |
44 | loadStaticPage() {
45 | //Select id
46 | this.route.params.subscribe(params => {
47 | this.id = params['id'];
48 | });
49 | this.studentService.getById(this.id).subscribe(
50 | res => {
51 | this.student = res;
52 | },
53 | error => {
54 | this.message = 'Bu id : ' + this.id + ' bir kullanıcı bulunamadı.';
55 | });
56 |
57 | //load getbook form
58 | this.getbookForm = this.formBuilder.group({
59 | 'bookId': [null, [Validators.required]],
60 | 'studentId': [this.id, [Validators.required]]
61 | });
62 |
63 | this.setPage({ offset: 0 });
64 | this.searchBookForm = this.formBuilder.group({
65 | 'name': [null, [Validators.minLength(3), Validators.required]]
66 | });
67 | }
68 |
69 | searchBook() {
70 | if (!this.searchBookForm.valid) {
71 | return;
72 | }
73 | console.log(this.searchBookForm.value['name']);
74 | this.bookService.findAllByName(this.searchBookForm.value['name']).subscribe(
75 | res => {
76 | this.control = false;
77 | this.books = res;
78 | this.message = ' Kayıtlar bulunmuştur. ';
79 | this.alert.success(' Kayıtlar bulunmuştur. ');
80 | },
81 | error => {
82 | this.control = true;
83 | this.loadStaticPage();
84 | this.alert.error(' Hay Aksi bu isimde bir kitap kaydı bulunamamıştır. ');
85 | this.message = ' Hay Aksi bu isimde bir kitap kaydı bulunamamıştır. ';
86 | });
87 | }
88 |
89 | getBook(bookId) {
90 | this.message = null;
91 | this.getbookForm = this.formBuilder.group({
92 | 'bookId': [bookId, [Validators.required]],
93 | 'studentId': [this.id, [Validators.required]]
94 | });
95 |
96 | this.bookService.getById(bookId).subscribe(res => {
97 | if (res['student'] == null) {
98 |
99 | this.studentService.getBook(this.getbookForm.value).subscribe(
100 | res => {
101 | this.loadStaticPage();
102 | this.message = ' Kayıt işlemi başarılıdır. ';
103 | this.alert.success( ' Kayıt işlemi başarılıdır. ');
104 | }
105 | , error => {
106 | this.alert.error(' Kayıt işlemi başarısız. : ');
107 | this.message = ' Kayıt işlemi başarısız. : ';
108 | }
109 | );
110 | } else {
111 | this.alert.error( ' Kitabın kayıtlı bir sahibi vardır. ');
112 | this.message = ' Kitabın kayıtlı bir sahibi vardır. ';
113 | }
114 | });
115 | }
116 | setPage(pageInfo) {
117 | this.page.page = pageInfo.offset;
118 | this.bookService.getAllPageable(this.page).subscribe(pagedData => {
119 | this.page.size = pagedData.size;
120 | this.page.page = pagedData.page;
121 | this.page.totalElements = pagedData.totalElements;
122 | this.rows = pagedData.content;
123 | });
124 | }
125 | get sf() { return this.searchBookForm.controls; }
126 | backClicked() {
127 | this.location.back();
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/library-webui/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "version": 1,
4 | "newProjectRoot": "projects",
5 | "projects": {
6 | "library-webui": {
7 | "projectType": "application",
8 | "schematics": {},
9 | "root": "",
10 | "sourceRoot": "src",
11 | "prefix": "app",
12 | "architect": {
13 | "build": {
14 | "builder": "@angular-devkit/build-angular:browser",
15 | "options": {
16 | "outputPath": "dist/library-webui",
17 | "index": "src/index.html",
18 | "main": "src/main.ts",
19 | "polyfills": "src/polyfills.ts",
20 | "tsConfig": "tsconfig.app.json",
21 | "aot": false,
22 | "assets": [
23 | "src/favicon.ico",
24 | "src/assets"
25 | ],
26 | "styles": [
27 | "src/styles.css",
28 | "node_modules/ngx-bootstrap/datepicker/bs-datepicker.css",
29 | "node_modules/@swimlane/ngx-datatable/release/index.css",
30 | "node_modules/@swimlane/ngx-datatable/release/themes/bootstrap.css",
31 | "node_modules/@swimlane/ngx-datatable/release/assets/icons.css",
32 | "node_modules/bootstrap/dist/css/bootstrap.min.css",
33 | "node_modules/alertifyjs/build/css/alertify.min.css",
34 | "node_modules/alertifyjs/build/css/themes/bootstrap.min.css"
35 |
36 |
37 | ],
38 | "scripts": [
39 | "node_modules/jquery/dist/jquery.min.js",
40 | "node_modules/bootstrap/dist/js/bootstrap.min.js",
41 | "node_modules/alertifyjs/build/alertify.min.js"
42 | ]
43 | },
44 | "configurations": {
45 | "production": {
46 | "fileReplacements": [
47 | {
48 | "replace": "src/environments/environment.ts",
49 | "with": "src/environments/environment.prod.ts"
50 | }
51 | ],
52 | "optimization": true,
53 | "outputHashing": "all",
54 | "sourceMap": false,
55 | "extractCss": true,
56 | "namedChunks": false,
57 | "aot": true,
58 | "extractLicenses": true,
59 | "vendorChunk": false,
60 | "buildOptimizer": true,
61 | "budgets": [
62 | {
63 | "type": "initial",
64 | "maximumWarning": "2mb",
65 | "maximumError": "5mb"
66 | }
67 | ]
68 | }
69 | }
70 | },
71 | "serve": {
72 | "builder": "@angular-devkit/build-angular:dev-server",
73 | "options": {
74 | "browserTarget": "library-webui:build"
75 | },
76 | "configurations": {
77 | "production": {
78 | "browserTarget": "library-webui:build:production"
79 | }
80 | }
81 | },
82 | "extract-i18n": {
83 | "builder": "@angular-devkit/build-angular:extract-i18n",
84 | "options": {
85 | "browserTarget": "library-webui:build"
86 | }
87 | },
88 | "test": {
89 | "builder": "@angular-devkit/build-angular:karma",
90 | "options": {
91 | "main": "src/test.ts",
92 | "polyfills": "src/polyfills.ts",
93 | "tsConfig": "tsconfig.spec.json",
94 | "karmaConfig": "karma.conf.js",
95 | "assets": [
96 | "src/favicon.ico",
97 | "src/assets"
98 | ],
99 | "styles": [
100 | "src/styles.css"
101 | ],
102 | "scripts": []
103 | }
104 | },
105 | "lint": {
106 | "builder": "@angular-devkit/build-angular:tslint",
107 | "options": {
108 | "tsConfig": [
109 | "tsconfig.app.json",
110 | "tsconfig.spec.json",
111 | "e2e/tsconfig.json"
112 | ],
113 | "exclude": [
114 | "**/node_modules/**"
115 | ]
116 | }
117 | },
118 | "e2e": {
119 | "builder": "@angular-devkit/build-angular:protractor",
120 | "options": {
121 | "protractorConfig": "e2e/protractor.conf.js",
122 | "devServerTarget": "library-webui:serve"
123 | },
124 | "configurations": {
125 | "production": {
126 | "devServerTarget": "library-webui:serve:production"
127 | }
128 | }
129 | }
130 | }
131 | }},
132 | "defaultProject": "library-webui"
133 | }
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/service/imp/AuthorServiceImp.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.service.imp;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import javax.validation.Valid;
8 |
9 | import org.modelmapper.ModelMapper;
10 | import org.springframework.data.domain.Page;
11 | import org.springframework.data.domain.PageRequest;
12 | import org.springframework.data.domain.Pageable;
13 | import org.springframework.data.domain.Sort;
14 | import org.springframework.stereotype.Service;
15 |
16 | import com.example.demo.dto.AuthorDto;
17 | import com.example.demo.dto.AuthorOneDto;
18 | import com.example.demo.dto.AuthorUpdateDto;
19 | import com.example.demo.dto.BookDto;
20 | import com.example.demo.dto.BookUpdateDto;
21 | import com.example.demo.dto.UserDto;
22 | import com.example.demo.model.Author;
23 | import com.example.demo.model.Book;
24 | import com.example.demo.model.User;
25 | import com.example.demo.repository.AuthorRepository;
26 | import com.example.demo.repository.UserRepository;
27 | import com.example.demo.service.AuthorService;
28 | import com.example.demo.util.TPage;
29 |
30 | import javassist.NotFoundException;
31 |
32 | @Service
33 | public class AuthorServiceImp implements AuthorService{
34 | private final ModelMapper modelMapper;
35 | private final UserRepository userRepository;
36 | private final AuthorRepository authorRepository;
37 |
38 | public AuthorServiceImp(ModelMapper modelMapper, UserRepository userRepository, AuthorRepository authorRepository) {
39 | super();
40 | this.modelMapper = modelMapper;
41 | this.userRepository = userRepository;
42 | this.authorRepository = authorRepository;
43 | }
44 |
45 | public AuthorDto save(AuthorDto authorDto) {
46 | Author authorChecked = authorRepository.findByEmail(authorDto.getEmail());
47 | if (authorChecked != null) {
48 | throw new IllegalArgumentException("User email already exist");
49 | }
50 | Author author = modelMapper.map(authorDto, Author.class);
51 | authorRepository.save(author);
52 | authorDto.setId(author.getId());
53 | return authorDto;
54 | }
55 |
56 | public List getAll() throws NotFoundException {
57 | List authors = authorRepository.findAll();
58 | if (authors.size() < 1) {
59 | throw new NotFoundException("Author don't already exist");
60 | }
61 | AuthorDto[] authorDtos = modelMapper.map(authors, AuthorDto[].class);
62 |
63 | return Arrays.asList(authorDtos);
64 | }
65 |
66 | public TPage getAllPageable(Pageable pageable) throws NotFoundException {
67 | try {
68 | Page page = authorRepository.findAll(PageRequest.of(pageable.getPageNumber(),
69 | pageable.getPageSize(), Sort.by(Sort.Direction.ASC, "id")));
70 | // Page page=authorRepository.findAll(pageable);
71 | TPage tPage = new TPage();
72 | AuthorDto[] authorDtos = modelMapper.map(page.getContent(), AuthorDto[].class);
73 |
74 | tPage.setStat(page, Arrays.asList(authorDtos));
75 | return tPage;
76 | } catch (Exception e) {
77 | throw new NotFoundException("User email dosen't exist : " + e);
78 | }
79 | }
80 |
81 | public List findAllByName(String name) throws NotFoundException {
82 | List authors = authorRepository.findByNameOrSurname(name, name);
83 | if (authors.size() < 1) {
84 | throw new NotFoundException("Author don't already exist");
85 | }
86 | AuthorDto[] authorDtos = modelMapper.map(authors, AuthorDto[].class);
87 |
88 | return Arrays.asList(authorDtos);
89 | }
90 |
91 | public AuthorUpdateDto update(Long id, @Valid AuthorUpdateDto authorUpdateDto) throws NotFoundException {
92 | Optional authorOpt = authorRepository.findById(id);
93 | if (!authorOpt.isPresent()) {
94 | throw new NotFoundException("User dosen't exist : " + id);
95 | }
96 | Author author = modelMapper.map(authorUpdateDto, Author.class);
97 | author.setId(id);
98 | authorRepository.save(author);
99 | authorUpdateDto.setId(author.getId());
100 | return authorUpdateDto;
101 |
102 | }
103 |
104 | public AuthorOneDto getOne(Long id) throws NotFoundException {
105 |
106 | Optional author = authorRepository.findById(id);
107 | if (!author.isPresent()) {
108 | throw new NotFoundException("User dosen't exist : " + id);
109 | }
110 |
111 | AuthorOneDto authorOneDto = modelMapper.map(author.get(), AuthorOneDto.class);
112 | authorOneDto.setId(id);
113 | authorOneDto.getBooks().forEach(data -> {
114 | data.setAuthorId(id);
115 | });
116 | return authorOneDto;
117 |
118 | }
119 |
120 | public Boolean delete(Long id) throws NotFoundException {
121 |
122 | Optional author = authorRepository.findById(id);
123 | if (!author.isPresent()) {
124 | throw new NotFoundException("User dosen't exist : " + id);
125 | }
126 | authorRepository.deleteById(id);
127 | return true;
128 |
129 | }
130 |
131 | }
132 |
--------------------------------------------------------------------------------
/library-webui/src/app/common/api/author/author-detail/author-detail.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { AuthorService } from 'src/app/services/author.service';
3 | import { ActivatedRoute } from '@angular/router';
4 | import { Location } from '@angular/common';
5 | import { FormBuilder, FormGroup, Validators } from '@angular/forms';
6 | import { BookService } from 'src/app/services/book.service';
7 | import { Author } from '../Author';
8 | import { BsModalRef } from 'ngx-bootstrap';
9 | import { AlertifyService } from 'src/app/services/alertify.service';
10 | @Component({
11 | selector: 'app-author-detail',
12 | templateUrl: './author-detail.component.html',
13 | styleUrls: ['./author-detail.component.css']
14 | })
15 | export class AuthorDetailComponent implements OnInit {
16 | //Author detail parameters
17 | author = new Author();
18 | books = [];
19 | id: number;
20 | authors = [];
21 | bookStatuses: Array = [];
22 | //form parameters about book
23 | BookForm: FormGroup;
24 | modalRef: BsModalRef;
25 | updated = true;
26 | //form parameters about Author
27 | AuthorUpdateForm: FormGroup;
28 | showModal = true;
29 |
30 | constructor(private authorService: AuthorService,
31 | private bookService: BookService,
32 | private alert: AlertifyService,
33 | private route: ActivatedRoute,
34 | private location: Location,
35 | private formBuilder: FormBuilder) { }
36 |
37 | ngOnInit() {
38 | this.staticLoadPage();
39 | this.LoadAuthorUpdateForm(this.author);
40 | }
41 | staticLoadPage(){
42 | this.route.params.subscribe(params => {
43 | this.id = params['id'];
44 | });
45 |
46 | this.BookForm = this.formBuilder.group({
47 | 'name': [null, [Validators.required]],
48 | 'publisher': [null, [Validators.required]],
49 | 'barcode': [null, [Validators.required]],
50 | 'content': [null, [Validators.required]],
51 | 'bookStatus': [null, [Validators.required]],
52 | 'authorId': [this.id]
53 | });
54 | this.BookForm.value['authorId'] = this.id;
55 | this.loadAuthorDetail();
56 | this.getAllBookStatus();
57 | }
58 |
59 | loadAuthorDetail() {
60 | this.authorService.getById(this.id).subscribe(response => {
61 | this.author = response;
62 | this.books = response['books'];
63 | });
64 | }
65 | LoadAuthorUpdateForm(res){
66 | this.updated=true;
67 | this.AuthorUpdateForm = this.formBuilder.group({
68 | 'name': [res['name'], [Validators.required]],
69 | 'surname': [res['surname'], [Validators.required]],
70 | 'email': [res['email'], [Validators.required]],
71 | 'phone': [res['phone'], [Validators.required]],
72 | 'about': [res['about']]
73 | });
74 | }
75 | updateAuthor(){
76 | console.log('loading')
77 | if (!this.AuthorUpdateForm.valid) {
78 | return;
79 | }
80 | this.authorService.put(this.id,this.AuthorUpdateForm.value).subscribe(
81 | res => {
82 | this.staticLoadPage();
83 | this.LoadAuthorUpdateForm(res);
84 | if(res['id']==this.id){
85 | this.updated = false;
86 | this.alert.success('Yazar kayıtları güncellenmiştir.');
87 | }
88 | },
89 | error=>{
90 | this.alert.success('Yazar güncelleme işlemi başarısız.
Daha sonra tekrar deneyiniz..');
91 | }
92 | );
93 | }
94 | saveBook() {
95 | this.BookForm.value['authorId'] = this.id;
96 | if (!this.BookForm.valid) {
97 | return;
98 | }
99 | this.bookService.post(this.BookForm.value).subscribe(
100 | res => {
101 | this.loadAuthorDetail();
102 | if(res['id'] > 0 ){
103 | this.showModal = false;
104 | this.alert.success('Kayıt işlemi başarılı.');
105 | }
106 | this.BookForm.reset();
107 | },
108 | error=>{
109 | this.staticLoadPage();
110 | this.LoadAuthorUpdateForm(this.author);
111 | this.alert.error('Kayıt işlemi başarısız.');
112 | }
113 | );
114 | }
115 |
116 | deleteBook(id) {
117 | this.bookService.delete(id).subscribe(
118 | res => {
119 | if (res === true) {
120 | this.loadAuthorDetail();
121 | this.alert.success('Silme işlemi başarılı.');
122 | } else {
123 | this.loadAuthorDetail();
124 | this.alert.error('Silme işlemi başarısız.
Daha sonra tekrar deneyiniz.');
125 | }
126 | },
127 | error=>{
128 | this.alert.error('Silme işlemi başarısız.
Daha sonra tekrar deneyiniz.');
129 | }
130 | );
131 | }
132 | getAllBookStatus(){
133 | this.bookService.getAllBookStatus().subscribe( res => {
134 | this.bookStatuses = res;
135 | });
136 | }
137 | backClicked() {
138 | this.location.back();
139 | }
140 | LoadInsertBookForm() {
141 | this.showModal = true;
142 | }
143 | get f1() { return this.BookForm.controls; }
144 | get f2() { return this.AuthorUpdateForm.controls; }
145 | }
146 |
--------------------------------------------------------------------------------
/Library-Application/.mvn/wrapper/MavenWrapperDownloader.java:
--------------------------------------------------------------------------------
1 | /*
2 | Licensed to the Apache Software Foundation (ASF) under one
3 | or more contributor license agreements. See the NOTICE file
4 | distributed with this work for additional information
5 | regarding copyright ownership. The ASF licenses this file
6 | to you under the Apache License, Version 2.0 (the
7 | "License"); you may not use this file except in compliance
8 | with the License. You may obtain a copy of the License at
9 |
10 | https://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing,
13 | software distributed under the License is distributed on an
14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | KIND, either express or implied. See the License for the
16 | specific language governing permissions and limitations
17 | under the License.
18 | */
19 |
20 | import java.io.File;
21 | import java.io.FileInputStream;
22 | import java.io.FileOutputStream;
23 | import java.io.IOException;
24 | import java.net.URL;
25 | import java.nio.channels.Channels;
26 | import java.nio.channels.ReadableByteChannel;
27 | import java.util.Properties;
28 |
29 | public class MavenWrapperDownloader {
30 |
31 | /**
32 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
33 | */
34 | private static final String DEFAULT_DOWNLOAD_URL =
35 | "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
36 |
37 | /**
38 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
39 | * use instead of the default one.
40 | */
41 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
42 | ".mvn/wrapper/maven-wrapper.properties";
43 |
44 | /**
45 | * Path where the maven-wrapper.jar will be saved to.
46 | */
47 | private static final String MAVEN_WRAPPER_JAR_PATH =
48 | ".mvn/wrapper/maven-wrapper.jar";
49 |
50 | /**
51 | * Name of the property which should be used to override the default download url for the wrapper.
52 | */
53 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
54 |
55 | public static void main(String args[]) {
56 | System.out.println("- Downloader started");
57 | File baseDirectory = new File(args[0]);
58 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
59 |
60 | // If the maven-wrapper.properties exists, read it and check if it contains a custom
61 | // wrapperUrl parameter.
62 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
63 | String url = DEFAULT_DOWNLOAD_URL;
64 | if(mavenWrapperPropertyFile.exists()) {
65 | FileInputStream mavenWrapperPropertyFileInputStream = null;
66 | try {
67 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
68 | Properties mavenWrapperProperties = new Properties();
69 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
70 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
71 | } catch (IOException e) {
72 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
73 | } finally {
74 | try {
75 | if(mavenWrapperPropertyFileInputStream != null) {
76 | mavenWrapperPropertyFileInputStream.close();
77 | }
78 | } catch (IOException e) {
79 | // Ignore ...
80 | }
81 | }
82 | }
83 | System.out.println("- Downloading from: : " + url);
84 |
85 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
86 | if(!outputFile.getParentFile().exists()) {
87 | if(!outputFile.getParentFile().mkdirs()) {
88 | System.out.println(
89 | "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
90 | }
91 | }
92 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
93 | try {
94 | downloadFileFromURL(url, outputFile);
95 | System.out.println("Done");
96 | System.exit(0);
97 | } catch (Throwable e) {
98 | System.out.println("- Error downloading");
99 | e.printStackTrace();
100 | System.exit(1);
101 | }
102 | }
103 |
104 | private static void downloadFileFromURL(String urlString, File destination) throws Exception {
105 | URL website = new URL(urlString);
106 | ReadableByteChannel rbc;
107 | rbc = Channels.newChannel(website.openStream());
108 | FileOutputStream fos = new FileOutputStream(destination);
109 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
110 | fos.close();
111 | rbc.close();
112 | }
113 |
114 | }
115 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/service/imp/UserServiceImp.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.service.imp;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import javax.transaction.Transactional;
8 | import javax.validation.Valid;
9 |
10 | import org.modelmapper.ModelMapper;
11 | import org.springframework.security.authentication.AuthenticationManager;
12 | import org.springframework.security.core.Authentication;
13 | import org.springframework.security.core.context.SecurityContextHolder;
14 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
15 | import org.springframework.stereotype.Service;
16 |
17 | import com.example.demo.dto.RegistirationRequest;
18 | import com.example.demo.dto.UserDto;
19 | import com.example.demo.dto.UserPasswordDto;
20 | import com.example.demo.model.User;
21 | import com.example.demo.repository.UserRepository;
22 |
23 | import javassist.NotFoundException;
24 |
25 | @Service
26 | public class UserServiceImp {
27 |
28 | private final AuthenticationManager authenticationManager;
29 | private final ModelMapper modelMapper;
30 | private final UserRepository userRepository;
31 | private final BCryptPasswordEncoder bCryptPasswordEncoder;
32 |
33 | public UserServiceImp(ModelMapper modelMapper, UserRepository userRepository,
34 | BCryptPasswordEncoder bCryptPasswordEncoder,
35 | AuthenticationManager authenticationManager) {
36 | super();
37 | this.modelMapper = modelMapper;
38 | this.userRepository = userRepository;
39 | this.bCryptPasswordEncoder = bCryptPasswordEncoder;
40 | this.authenticationManager = authenticationManager;
41 | }
42 |
43 | public List getAll() throws NotFoundException {
44 | List users = userRepository.findAll();
45 | if (users.size() < 1) {
46 | throw new NotFoundException("Project don't already exist");
47 | }
48 | UserDto[] userdto = modelMapper.map(users, UserDto[].class);
49 | return Arrays.asList(userdto);
50 | }
51 |
52 | @Transactional
53 | public Boolean register(RegistirationRequest registirationRequest) throws Exception {
54 |
55 | List userList = userRepository.findByEmail(registirationRequest.getEmail());
56 | if (userList.size() > 0) {
57 | throw new Exception("User exist with this : " + registirationRequest.getEmail());
58 | }
59 | if (userRepository.getByUsername(registirationRequest.getUsername()).size() > 0) {
60 | throw new Exception("User exist with this name called : " + registirationRequest.getUsername());
61 | }
62 | User user = new User();
63 | user.setRealPassword(registirationRequest.getPassword());
64 | registirationRequest.setPassword(bCryptPasswordEncoder.encode(registirationRequest.getPassword()));
65 | // user = modelMapper.map(registirationRequest, User.class);
66 | user.setUsername(registirationRequest.getUsername());
67 | user.setEmail(registirationRequest.getEmail());
68 | user.setFirstname(registirationRequest.getFirstname());
69 | user.setLastname(registirationRequest.getLastname());
70 | user.setPassword(registirationRequest.getPassword());
71 | userRepository.save(user);
72 | return true;
73 |
74 | }
75 |
76 | public UserDto findByUserName(String username) throws NotFoundException {
77 | try {
78 | User user = userRepository.findByUsername(username);
79 | UserDto userDto = modelMapper.map(user, UserDto.class);
80 | return userDto;
81 | } catch (Exception e) {
82 | throw new NotFoundException("User dosen't exist with this name called : " + username);
83 | }
84 | }
85 |
86 | public Boolean update(String username, @Valid UserDto userDto) throws NotFoundException {
87 |
88 | List userlist = userRepository.getByUsername(username);
89 | if (userlist.size() < 0) {
90 | throw new NotFoundException("User dosen't exist with this name called : " + username);
91 | }
92 | User user = modelMapper.map(userDto, User.class);
93 | user.setId(userlist.get(0).getId());
94 | user.setRealPassword(userlist.get(0).getRealPassword());
95 | user.setPassword(userlist.get(0).getPassword());
96 | userRepository.save(user);
97 | return true;
98 | }
99 |
100 | public Boolean changePassword(UserPasswordDto userPasswordDto) throws NotFoundException {
101 | Authentication auth = SecurityContextHolder.getContext().getAuthentication();
102 | if(!userPasswordDto.getUsername().equals(auth.getName())) {
103 | return false;
104 | }
105 |
106 | List userlist = userRepository.getByUsername(userPasswordDto.getUsername());
107 | if (userlist.size() < 0) {
108 | throw new NotFoundException("User dosen't exist with this name called : " + userPasswordDto.getUsername());
109 | }
110 | System.out.println(userlist.get(0).getPassword());
111 | boolean control=bCryptPasswordEncoder.matches( userPasswordDto.getPassword(),userlist.get(0).getPassword());
112 | if (!control) {
113 | throw new NotFoundException("Mevcut şifreniz yanlıştır.");
114 | }
115 | userlist.get(0).setRealPassword(userPasswordDto.getNewpassword());
116 | userlist.get(0).setPassword(bCryptPasswordEncoder.encode(userPasswordDto.getNewpassword()));
117 | userRepository.save(userlist.get(0));
118 | return true;
119 |
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/Library-Application/src/main/java/com/example/demo/service/imp/BookServiceImp.java:
--------------------------------------------------------------------------------
1 | package com.example.demo.service.imp;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import org.modelmapper.ModelMapper;
8 | import org.springframework.data.domain.Page;
9 | import org.springframework.data.domain.PageRequest;
10 | import org.springframework.data.domain.Pageable;
11 | import org.springframework.data.domain.Sort;
12 | import org.springframework.stereotype.Service;
13 | import org.springframework.transaction.annotation.Transactional;
14 |
15 | import com.example.demo.dto.AuthorDto;
16 | import com.example.demo.dto.AuthorDtoForOneEntity;
17 | import com.example.demo.dto.AuthorOneDto;
18 | import com.example.demo.dto.BookDto;
19 | import com.example.demo.dto.BookOneDto;
20 | import com.example.demo.dto.BookUpdateDto;
21 | import com.example.demo.dto.UserDto;
22 | import com.example.demo.model.Author;
23 | import com.example.demo.model.Book;
24 | import com.example.demo.model.User;
25 | import com.example.demo.repository.AuthorRepository;
26 | import com.example.demo.repository.BookRepository;
27 | import com.example.demo.repository.UserRepository;
28 | import com.example.demo.service.BookService;
29 | import com.example.demo.util.TPage;
30 |
31 | import javassist.NotFoundException;
32 |
33 | @Service
34 | public class BookServiceImp implements BookService {
35 | private final ModelMapper modelMapper;
36 | private final UserRepository userRepository;
37 | private final AuthorRepository authorRepository;
38 | private final BookRepository bookRepository;
39 |
40 | public BookServiceImp(ModelMapper modelMapper, UserRepository userRepository, AuthorRepository authorRepository,
41 | BookRepository bookRepository) {
42 | super();
43 | this.modelMapper = modelMapper;
44 | this.userRepository = userRepository;
45 | this.authorRepository = authorRepository;
46 | this.bookRepository = bookRepository;
47 | }
48 |
49 | public BookOneDto save(BookOneDto bookOneDto) throws Exception {
50 |
51 | List bookChecked = bookRepository.findByName(bookOneDto.getName().trim());
52 | if (bookChecked.size() > 0) {
53 | throw new Exception("book already exist");
54 | }
55 |
56 | Optional authorOpt = authorRepository.findById(bookOneDto.getAuthorId());
57 | if (!authorOpt.isPresent() && authorOpt.get().getId() != bookOneDto.getAuthorId()) {
58 | throw new IllegalArgumentException("Author does not match");
59 | }
60 |
61 | Book book = modelMapper.map(bookOneDto, Book.class);
62 | book.setAuthor(authorOpt.get());
63 | bookRepository.save(book);
64 |
65 | bookOneDto.setId(book.getId());
66 |
67 | bookOneDto.setAuthor(modelMapper.map(authorOpt.get(), AuthorDtoForOneEntity.class));
68 | return bookOneDto;
69 | }
70 |
71 | public List getAll() throws NotFoundException {
72 |
73 | List books = bookRepository.findAll(Sort.by(Sort.Direction.ASC, "id"));
74 | if (books.size() < 1) {
75 | throw new NotFoundException("Book don't already exist");
76 | }
77 | BookDto[] bookDtos = modelMapper.map(books, BookDto[].class);
78 | Arrays.asList(bookDtos).forEach(data -> {
79 | data.setAuthorId(data.getAuthor().getId());
80 | });
81 | return Arrays.asList(bookDtos);
82 |
83 | }
84 |
85 | public TPage getAllPageable(Pageable pageable) throws NotFoundException {
86 |
87 | try {
88 | Page page = bookRepository.findAll(PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(),
89 | Sort.by(Sort.Direction.ASC, "id")));
90 | TPage tPage = new TPage();
91 | BookDto[] bookDtos = modelMapper.map(page.getContent(), BookDto[].class);
92 | Arrays.asList(bookDtos).forEach(data -> {
93 | data.setAuthorId(data.getAuthor().getId());
94 | });
95 | tPage.setStat(page, Arrays.asList(bookDtos));
96 | return tPage;
97 | } catch (Exception e) {
98 | throw new NotFoundException("Book does not exist : ");
99 | }
100 | }
101 |
102 | @Transactional
103 | public BookUpdateDto update(Long id, BookUpdateDto bookUpdateDto) throws NotFoundException {
104 |
105 | Optional bookOpt = bookRepository.findById(id);
106 | if (!bookOpt.isPresent()) {
107 | throw new NotFoundException("Book does not exist id : " + id);
108 | }
109 | Optional author = authorRepository.findById(bookUpdateDto.getAuthorId());
110 | if (!author.isPresent()) {
111 | throw new NotFoundException("Author does not exist id : " + bookUpdateDto.getAuthorId());
112 | }
113 | Book realbook = modelMapper.map(bookUpdateDto, Book.class);
114 | realbook.setAuthor(author.get());
115 | realbook.setStudent(bookOpt.get().getStudent());
116 | bookRepository.save(realbook);
117 | bookUpdateDto = modelMapper.map(realbook, BookUpdateDto.class);
118 | bookUpdateDto.setAuthorId(author.get().getId());
119 |
120 | return bookUpdateDto;
121 |
122 | }
123 |
124 | public BookOneDto getOne(Long id) throws NotFoundException {
125 |
126 | Optional book = bookRepository.findById(id);
127 | if (!book.isPresent()) {
128 | throw new NotFoundException("Book does not exist id : " + id);
129 | }
130 | BookOneDto bookOneDto = modelMapper.map(book.get(), BookOneDto.class);
131 | bookOneDto.setId(id);
132 | bookOneDto.setAuthorId(bookOneDto.getAuthor().getId());
133 |
134 | return bookOneDto;
135 |
136 | }
137 |
138 | public Boolean delete(Long id) throws NotFoundException {
139 |
140 | Optional book = bookRepository.findById(id);
141 | if (!book.isPresent()) {
142 | throw new NotFoundException("Book does not exist id : " + id);
143 | }
144 | bookRepository.deleteById(id);
145 | return true;
146 |
147 | }
148 |
149 | public List SearchBooksByName(String name) throws NotFoundException {
150 | List books = bookRepository.SearchBooksByName(name.trim());
151 | if (books.size() < 1) {
152 | throw new NotFoundException("Book don't already exist");
153 | }
154 | BookDto[] bookDtos = modelMapper.map(books, BookDto[].class);
155 | return Arrays.asList(bookDtos);
156 | }
157 |
158 | }
159 |
--------------------------------------------------------------------------------