Initial commit

This commit is contained in:
aditya.chandel
2024-12-13 12:58:23 -07:00
commit baff376b9c
414 changed files with 552987 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary
+37
View File
@@ -0,0 +1,37 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
+54
View File
@@ -0,0 +1,54 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.4.0'
id 'io.spring.dependency-management' version '1.1.6'
id 'org.hibernate.orm' version '6.6.2.Final'
id 'org.graalvm.buildtools.native' version '0.10.3'
}
group = 'com.adityachandel'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
implementation 'org.apache.pdfbox:pdfbox:3.0.3'
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
implementation 'org.flywaydb:flyway-mysql:10.12.0'
implementation 'com.github.jai-imageio:jai-imageio-core:1.4.0'
implementation 'com.github.jai-imageio:jai-imageio-jpeg2000:1.3.0'
implementation 'org.apache.pdfbox:jbig2-imageio:3.0.3'
}
hibernate {
enhancement {
enableAssociationManagement = true
}
}
tasks.named('test') {
useJUnitPlatform()
}
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+252
View File
@@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+1
View File
@@ -0,0 +1 @@
rootProject.name = 'booklore-api'
@@ -0,0 +1,13 @@
package com.adityachandel.booklore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BookloreApplication {
public static void main(String[] args) {
SpringApplication.run(BookloreApplication.class, args);
}
}
@@ -0,0 +1,15 @@
package com.adityachandel.booklore.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "app")
@Getter
@Setter
public class AppProperties {
private String pathBook;
private String pathConfig;
}
@@ -0,0 +1,17 @@
package com.adityachandel.booklore.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*");
}
}
@@ -0,0 +1,27 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.dto.AuthorDTO;
import com.adityachandel.booklore.service.AuthorService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RequestMapping("/v1/author")
@RestController
@AllArgsConstructor
public class AuthorController {
private AuthorService authorService;
@GetMapping("/{authorId}")
public ResponseEntity<AuthorDTO> getAuthor(@PathVariable long authorId) {
return ResponseEntity.ok(authorService.getAuthorById(authorId));
}
@GetMapping("/book/{bookId}")
public ResponseEntity<List<AuthorDTO>> getAuthorsByBookId(@PathVariable long bookId) {
return ResponseEntity.ok(authorService.getAuthorsByBookId(bookId));
}
}
@@ -0,0 +1,60 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.dto.BookDTO;
import com.adityachandel.booklore.dto.BookViewerSettingDTO;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.exception.ErrorCode;
import com.adityachandel.booklore.service.BooksService;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.AllArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@RequestMapping("/v1/book")
@RestController
@AllArgsConstructor
public class BookController {
private BooksService booksService;
@GetMapping("/{bookId}")
public ResponseEntity<BookDTO> getBook(@PathVariable long bookId) {
return ResponseEntity.ok(booksService.getBook(bookId));
}
@GetMapping()
public ResponseEntity<Page<BookDTO>> getBooks(@RequestParam(defaultValue = "0") @Min(0) int page, @RequestParam(defaultValue = "25") @Min(1) @Max(100) int size) {
Page<BookDTO> books = booksService.getBooks(page, size);
return ResponseEntity.ok(books);
}
@GetMapping("/search")
public ResponseEntity<List<BookDTO>> searchBooks(@RequestParam String title) {
List<BookDTO> books = booksService.search(title);
return ResponseEntity.ok(books);
}
@GetMapping("/{bookId}/cover")
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
return ResponseEntity.ok(booksService.getBookCover(bookId));
}
@GetMapping("/{bookId}/data")
public ResponseEntity<byte[]> getBookData(@PathVariable long bookId) throws IOException {
return booksService.getBookData(bookId);
}
@PutMapping("/{bookId}/viewer-setting")
public ResponseEntity<Void> updateBookViewerSettings(@RequestBody BookViewerSettingDTO bookViewerSettingDTO, @PathVariable long bookId) {
booksService.saveBookViewerSetting(bookId, bookViewerSettingDTO);
return ResponseEntity.noContent().build();
}
}
@@ -0,0 +1,59 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.dto.BookDTO;
import com.adityachandel.booklore.dto.LibraryDTO;
import com.adityachandel.booklore.dto.request.CreateLibraryRequest;
import com.adityachandel.booklore.service.LibraryService;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@RestController
@RequestMapping("/v1/library")
@AllArgsConstructor
public class LibraryController {
private LibraryService libraryService;
@PostMapping(consumes = "application/json", produces = "application/json")
public SseEmitter createLibrary(@RequestBody CreateLibraryRequest request) {
return libraryService.createLibrary(request);
}
@GetMapping("/{libraryId}")
public ResponseEntity<LibraryDTO> getLibrary(@PathVariable long libraryId) {
return ResponseEntity.ok(libraryService.getLibrary(libraryId));
}
@DeleteMapping("/{libraryId}")
public ResponseEntity<?> deleteLibrary(@PathVariable long libraryId) {
libraryService.deleteLibrary(libraryId);
return ResponseEntity.noContent().build();
}
@GetMapping
public ResponseEntity<Page<LibraryDTO>> getLibraries(
@RequestParam(defaultValue = "0") @Min(0) int page,
@RequestParam(defaultValue = "25") @Min(1) @Max(100) int size) {
return ResponseEntity.ok(libraryService.getLibraries(page, size));
}
@GetMapping("/{libraryId}/book/{bookId}")
public ResponseEntity<BookDTO> getBook(@PathVariable long libraryId, @PathVariable long bookId) {
return ResponseEntity.ok(libraryService.getBook(libraryId, bookId));
}
@GetMapping("/{libraryId}/book")
public ResponseEntity<Page<BookDTO>> getBooks(
@PathVariable long libraryId,
@RequestParam(defaultValue = "0") @Min(0) int page,
@RequestParam(defaultValue = "25") @Min(1) @Max(100) int size) {
Page<BookDTO> books = libraryService.getBooks(libraryId, page, size);
return ResponseEntity.ok(books);
}
}
@@ -0,0 +1,23 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.service.PathService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/v1/path")
@AllArgsConstructor
public class PathController {
private PathService pathService;
@GetMapping
public List<String> getFolders(@RequestParam String path) {
return pathService.getFoldersAtPath(path);
}
}
@@ -0,0 +1,37 @@
package com.adityachandel.booklore.convertor;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Converter
public class PathsConverter implements AttributeConverter<List<String>, String> {
private static final String DELIMITER = ";";
@Override
public String convertToDatabaseColumn(List<String> attribute) {
if (attribute == null || attribute.isEmpty()) {
return null;
}
return attribute.stream()
.filter(Objects::nonNull)
.map(String::trim)
.collect(Collectors.joining(DELIMITER));
}
@Override
public List<String> convertToEntityAttribute(String dbData) {
if (dbData == null || dbData.isEmpty()) {
return null;
}
return Arrays.stream(dbData.split(DELIMITER))
.filter(Objects::nonNull)
.map(String::trim)
.collect(Collectors.toList());
}
}
@@ -0,0 +1,16 @@
package com.adityachandel.booklore.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;
import java.util.List;
@Builder
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AuthorDTO {
private Long id;
private String name;
private List<BookDTO> books;
}
@@ -0,0 +1,17 @@
package com.adityachandel.booklore.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BookDTO {
private Long id;
private Long libraryId;
private String fileName;
private String title;
private List<AuthorDTO> authors = new ArrayList<>();
}
@@ -0,0 +1,13 @@
package com.adityachandel.booklore.dto;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class BookViewerSettingDTO {
private int pageNumber;
private String zoom;
private boolean sidebar_visible;
private String spread;
}
@@ -0,0 +1,14 @@
package com.adityachandel.booklore.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LibraryDTO {
private Long id;
private String name;
}
@@ -0,0 +1,13 @@
package com.adityachandel.booklore.dto.request;
import lombok.Builder;
import lombok.Data;
import java.util.List;
@Data
@Builder
public class CreateLibraryRequest {
private String name;
private List<String> paths;
}
@@ -0,0 +1,26 @@
package com.adityachandel.booklore.entity;
import jakarta.persistence.*;
import lombok.*;
import java.util.List;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "author")
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@ManyToMany(mappedBy = "authors")
private List<Book> books;
}
@@ -0,0 +1,43 @@
package com.adityachandel.booklore.entity;
import jakarta.persistence.*;
import lombok.*;
import java.util.List;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "file_name", length = 1000)
private String fileName;
@Column(name = "title")
private String title;
@Column(name = "path")
private String path;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "book_author_mapping",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id")
)
private List<Author> authors;
@ManyToOne
@JoinColumn(name = "library_id", nullable = false)
private Library library;
@OneToOne(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
private BookViewerSetting viewerSetting;
}
@@ -0,0 +1,35 @@
package com.adityachandel.booklore.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "book_viewer_setting")
public class BookViewerSetting {
@Id
private Long bookId;
@OneToOne
@MapsId
@JoinColumn(name = "book_id")
@JsonIgnore
private Book book;
@Column(name = "page_number")
private int pageNumber;
@Column(name = "zoom")
private String zoom;
@Column(name = "sidebar_visible")
private boolean sidebar_visible;
@Column(name = "spread")
private String spread;
}
@@ -0,0 +1,30 @@
package com.adityachandel.booklore.entity;
import com.adityachandel.booklore.convertor.PathsConverter;
import jakarta.persistence.*;
import lombok.*;
import java.util.List;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "library")
public class Library {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Convert(converter = PathsConverter.class)
@Column(name = "paths")
private List<String> paths;
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Book> books;
}
@@ -0,0 +1,28 @@
package com.adityachandel.booklore.entity;
public class PathInfo {
private String name;
private String fullPath;
public PathInfo(String name, String fullPath) {
this.name = name;
this.fullPath = fullPath;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFullPath() {
return fullPath;
}
public void setFullPath(String fullPath) {
this.fullPath = fullPath;
}
}
@@ -0,0 +1,18 @@
package com.adityachandel.booklore.exception;
import lombok.Getter;
import org.springframework.http.HttpStatus;
@Getter
public class APIException extends RuntimeException {
private final HttpStatus status;
private final String message;
public APIException(String formattedMessage, HttpStatus status) {
super(formattedMessage);
this.status = status;
this.message = formattedMessage;
}
}
@@ -0,0 +1,30 @@
package com.adityachandel.booklore.exception;
import lombok.Getter;
import org.springframework.http.HttpStatus;
@Getter
public enum ErrorCode {
AUTHOR_NOT_FOUND(HttpStatus.NOT_FOUND, "Author not found with ID: %d"),
BOOK_NOT_FOUND(HttpStatus.NOT_FOUND, "Book not found with ID: %d"),
FILE_READ_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Error reading files from path"),
IMAGE_NOT_FOUND(HttpStatus.NOT_FOUND, "Image not found or not readable"),
INVALID_FILE_FORMAT(HttpStatus.BAD_REQUEST, "Invalid file format"),
LIBRARY_NOT_FOUND(HttpStatus.NOT_FOUND, "Library not found with ID: %d"),
BAD_REQUEST(HttpStatus.BAD_REQUEST, "Bad request"),
INVALID_QUERY_PARAMETERS(HttpStatus.BAD_REQUEST, "Query parameters are required for the search.");
private final HttpStatus status;
private final String message;
ErrorCode(HttpStatus status, String message) {
this.status = status;
this.message = message;
}
public APIException createException(Object... details) {
String formattedMessage = (details.length > 0) ? String.format(message, details) : message;
return new APIException(formattedMessage, this.status);
}
}
@@ -0,0 +1,36 @@
package com.adityachandel.booklore.exception;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;
import lombok.AllArgsConstructor;
import java.time.LocalDateTime;
import java.util.List;
@Getter
@Setter
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ErrorResponse {
private int status;
private String message;
private LocalDateTime timestamp;
private List<String> details;
public ErrorResponse(int status, String message) {
this.status = status;
this.message = message;
this.timestamp = LocalDateTime.now();
}
public ErrorResponse(int status, String message, List<String> details) {
this.status = status;
this.message = message;
this.timestamp = LocalDateTime.now();
this.details = details;
}
}
@@ -0,0 +1,52 @@
package com.adityachandel.booklore.exception;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;
import java.util.stream.Collectors;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(APIException.class)
public ResponseEntity<ErrorResponse> handleAPIException(APIException ex) {
ErrorResponse errorResponse = new ErrorResponse(ex.getStatus().value(), ex.getMessage());
return new ResponseEntity<>(errorResponse, ex.getStatus());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationExceptions(MethodArgumentNotValidException ex) {
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.collect(Collectors.toList());
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "Validation error", errors);
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<ErrorResponse> handleConstraintViolationExceptions(ConstraintViolationException ex) {
List<String> errors = ex.getConstraintViolations()
.stream()
.map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
.collect(Collectors.toList());
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "Validation error", errors);
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An unexpected error occurred.");
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@@ -0,0 +1,21 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.entity.Author;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface AuthorRepository extends JpaRepository<Author, Long> {
Optional<Author> findByName(String name);
@Query("SELECT a FROM Author a JOIN a.books b WHERE b.id = :bookId")
List<Author> findAuthorsByBookId(@Param("bookId") Long bookId);
}
@@ -0,0 +1,23 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.entity.Book;
import com.adityachandel.booklore.entity.Library;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> {
Page<Book> findBooksByLibraryId(Long libraryId, Pageable pageable);
Optional<Book> findBookByIdAndLibraryId(long id, long libraryId);
List<Book> findByTitleContainingIgnoreCase(String title);
}
@@ -0,0 +1,10 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.entity.BookViewerSetting;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BookViewerSettingRepository extends JpaRepository<BookViewerSetting, Long> {
}
@@ -0,0 +1,15 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.entity.Library;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface LibraryRepository extends JpaRepository<Library, Long>, JpaSpecificationExecutor<Library> {
List<Library> findByName(String name);
}
@@ -0,0 +1,45 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.dto.AuthorDTO;
import com.adityachandel.booklore.entity.Author;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.exception.ErrorCode;
import com.adityachandel.booklore.repository.AuthorRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.transformer.AuthorTransformer;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.util.List;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@AllArgsConstructor
public class AuthorService {
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
public AuthorDTO getAuthorById(Long id) {
Author author = authorRepository.findById(id).orElseThrow(() -> ErrorCode.AUTHOR_NOT_FOUND.createException(id));
return AuthorTransformer.toAuthorDTO(author);
}
public List<AuthorDTO> getAuthorsByBookId(Long bookId) {
bookRepository.findById(bookId).orElseThrow(() -> ErrorCode.BOOK_NOT_FOUND.createException(bookId));
List<Author> authors = authorRepository.findAuthorsByBookId(bookId);
return authors.stream().map(AuthorTransformer::toAuthorDTO).toList();
}
}
@@ -0,0 +1,150 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.dto.BookDTO;
import com.adityachandel.booklore.dto.BookViewerSettingDTO;
import com.adityachandel.booklore.entity.Book;
import com.adityachandel.booklore.entity.BookViewerSetting;
import com.adityachandel.booklore.entity.Library;
import com.adityachandel.booklore.exception.ErrorCode;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.BookViewerSettingRepository;
import com.adityachandel.booklore.service.parser.PdfParser;
import com.adityachandel.booklore.transformer.BookTransformer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Slf4j
@AllArgsConstructor
@Service
public class BooksService {
private final AppProperties appProperties;
private final PdfParser pdfParser;
private final BookRepository bookRepository;
private final BookViewerSettingRepository bookViewerSettingRepository;
public BookDTO getBook(long bookId) {
Book book = bookRepository.findById(bookId).orElseThrow(() -> ErrorCode.BOOK_NOT_FOUND.createException(bookId));
return BookTransformer.convertToBookDTO(book);
}
public Page<BookDTO> getBooks(int page, int size) {
PageRequest pageRequest = PageRequest.of(page, size);
Page<Book> bookPage = bookRepository.findAll(PageRequest.of(page, size));
List<BookDTO> bookDTOs = bookPage.getContent().stream().map(BookTransformer::convertToBookDTO).collect(Collectors.toList());
return new PageImpl<>(bookDTOs, pageRequest, bookPage.getTotalElements());
}
public List<Book> parseBooks(Library library, SseEmitter emitter) {
List<Book> books = new ArrayList<>();
for (String libraryPath : library.getPaths()) {
books.addAll(parseBooks(libraryPath, emitter));
}
return books;
}
private List<Book> parseBooks(String libraryPath, SseEmitter emitter) {
List<Book> books = new ArrayList<>();
try (Stream<Path> filePaths = Files.walk(Path.of(libraryPath))) {
filePaths.filter(Files::isRegularFile).forEach(filePath -> handleFile(filePath, books, emitter));
} catch (IOException e) {
log.error("Error reading files from path: {}", libraryPath, e);
throw ErrorCode.FILE_READ_ERROR.createException(libraryPath);
}
return books;
}
private void handleFile(Path filePath, List<Book> books, SseEmitter emitter) {
String fileName = filePath.getFileName().toString();
if (fileName.endsWith(".pdf")) {
sendSseEvent("Parsing: " + fileName, emitter);
Book book = parsePdfBook(filePath);
book.setPath(filePath.toAbsolutePath().toString());
books.add(book);
} else if (fileName.endsWith(".epub")) {
log.info("EPUB File: {}", fileName);
}
}
private void sendSseEvent(String message, SseEmitter emitter) {
try {
SseEmitter.SseEventBuilder event = SseEmitter.event()
.data(message)
.name("SSE Event");
emitter.send(event);
} catch (IOException e) {
emitter.completeWithError(e);
}
}
private Book parsePdfBook(Path filePath) {
Book book = pdfParser.parseBook(filePath.toAbsolutePath().toString(), appProperties.getPathConfig());
book.setViewerSetting(BookViewerSetting.builder()
.bookId(book.getId())
.pageNumber(0)
.zoom("page-fit")
.spread("off")
.sidebar_visible(false)
.build());
return book;
}
public void saveBookViewerSetting(long bookId, BookViewerSettingDTO bookViewerSettingDTO) {
BookViewerSetting bookViewerSetting = bookViewerSettingRepository.findById(bookId).orElseThrow(() -> ErrorCode.BOOK_NOT_FOUND.createException(bookId));
bookViewerSetting.setPageNumber(bookViewerSettingDTO.getPageNumber());
bookViewerSetting.setZoom(bookViewerSettingDTO.getZoom());
bookViewerSetting.setSpread(bookViewerSettingDTO.getSpread());
bookViewerSetting.setSidebar_visible(bookViewerSettingDTO.isSidebar_visible());
bookViewerSettingRepository.save(bookViewerSetting);
}
public Resource getBookCover(long bookId) {
Book book = bookRepository.findById(bookId).orElseThrow(() -> ErrorCode.BOOK_NOT_FOUND.createException(bookId));
String thumbPath = appProperties.getPathConfig() + "/thumbs/" + PdfParser.getFileNameWithoutExtension(book.getFileName()) + ".jpg";
Path filePath = Paths.get(thumbPath);
try {
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists() && resource.isReadable()) {
return resource;
} else {
throw ErrorCode.IMAGE_NOT_FOUND.createException(thumbPath);
}
} catch (IOException e) {
throw ErrorCode.IMAGE_NOT_FOUND.createException(thumbPath);
}
}
public ResponseEntity<byte[]> getBookData(long bookId) throws IOException {
Book book = bookRepository.findById(bookId).orElseThrow(() -> ErrorCode.BOOK_NOT_FOUND.createException(bookId));
byte[] pdfBytes = Files.readAllBytes(new File(book.getPath()).toPath());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, "application/pdf")
.body(pdfBytes);
}
public List<BookDTO> search(String title) {
List<Book> books = bookRepository.findByTitleContainingIgnoreCase(title);
return books.stream().map(BookTransformer::convertToBookDTO).toList();
}
}
@@ -0,0 +1,105 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.dto.BookDTO;
import com.adityachandel.booklore.dto.LibraryDTO;
import com.adityachandel.booklore.dto.request.CreateLibraryRequest;
import com.adityachandel.booklore.entity.Author;
import com.adityachandel.booklore.entity.Book;
import com.adityachandel.booklore.entity.Library;
import com.adityachandel.booklore.exception.ErrorCode;
import com.adityachandel.booklore.repository.AuthorRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.BookViewerSettingRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.transformer.BookTransformer;
import com.adityachandel.booklore.transformer.LibraryTransformer;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import static com.adityachandel.booklore.transformer.LibraryTransformer.createLibraryFromRequest;
@Service
@AllArgsConstructor
public class LibraryService {
private LibraryRepository libraryRepository;
private BookRepository bookRepository;
private BooksService booksService;
private AuthorRepository authorRepository;
private BookViewerSettingRepository bookViewerSettingRepository;
public LibraryDTO getLibrary(long libraryId) {
Library library = libraryRepository.findById(libraryId).orElseThrow(() -> ErrorCode.LIBRARY_NOT_FOUND.createException(libraryId));
return LibraryTransformer.convertToLibraryDTO(library);
}
public Page<LibraryDTO> getLibraries(int page, int size) {
PageRequest pageRequest = PageRequest.of(page, size);
Page<Library> libraryPage = libraryRepository.findAll(pageRequest);
return libraryPage.map(LibraryTransformer::convertToLibraryDTO);
}
public void deleteLibrary(long id) {
libraryRepository.findById(id).orElseThrow(() -> ErrorCode.LIBRARY_NOT_FOUND.createException(id));
libraryRepository.deleteById(id);
}
public BookDTO getBook(long libraryId, long bookId) {
libraryRepository.findById(libraryId).orElseThrow(() -> ErrorCode.LIBRARY_NOT_FOUND.createException(libraryId));
Book book = bookRepository.findBookByIdAndLibraryId(bookId, libraryId).orElseThrow(() -> ErrorCode.BOOK_NOT_FOUND.createException(bookId));
return BookTransformer.convertToBookDTO(book);
}
public Page<BookDTO> getBooks(long libraryId, int page, int size) {
libraryRepository.findById(libraryId).orElseThrow(() -> ErrorCode.LIBRARY_NOT_FOUND.createException(libraryId));
PageRequest pageRequest = PageRequest.of(page, size);
Page<Book> bookPage = bookRepository.findBooksByLibraryId(libraryId, pageRequest);
return bookPage.map(BookTransformer::convertToBookDTO);
}
public SseEmitter createLibrary(CreateLibraryRequest request) {
SseEmitter emitter = new SseEmitter();
ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();
sseMvcExecutor.execute(() -> {
try {
Library library = createLibraryFromRequest(request);
List<Book> books = booksService.parseBooks(library, emitter);
books.forEach(book -> book.setLibrary(library));
library.setBooks(books);
List<Author> authors = books.stream()
.flatMap(book -> book.getAuthors().stream())
.distinct()
.collect(Collectors.toList());
authorRepository.saveAll(authors);
libraryRepository.save(library);
bookRepository.saveAll(books);
bookViewerSettingRepository.saveAll(books.stream()
.map(Book::getViewerSetting)
.collect(Collectors.toList()));
emitter.complete();
} catch (Exception ex) {
emitter.completeWithError(ex);
} finally {
sseMvcExecutor.shutdown();
}
});
return emitter;
}
}
@@ -0,0 +1,36 @@
package com.adityachandel.booklore.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Slf4j
@Service
public class PathService {
public List<String> getFoldersAtPath(String path) {
Path directory = Paths.get(path);
if (!Files.exists(directory) || !Files.isDirectory(directory)) {
log.warn("Invalid path or not a directory: {}", path);
return Collections.emptyList();
}
try (Stream<Path> paths = Files.list(directory)) {
return paths
.filter(Files::isDirectory)
.map(p -> directory.resolve(p.getFileName()).toString())
.sorted()
.collect(Collectors.toList());
} catch (IOException e) {
log.error("Error accessing path {}: {}", path, e.getMessage(), e);
return Collections.emptyList();
}
}
}
@@ -0,0 +1,9 @@
package com.adityachandel.booklore.service.parser;
import com.adityachandel.booklore.entity.Book;
public interface BookParser {
Book parseBook(String bookPath, String coverPath);
}
@@ -0,0 +1,11 @@
package com.adityachandel.booklore.service.parser;
/*@Service
@AllArgsConstructor
public class EBookParser implements BookParser {
@Override
public Book parseBook(String bookPath, String coverPath) {
return null;
}
}*/
@@ -0,0 +1,113 @@
package com.adityachandel.booklore.service.parser;
import com.adityachandel.booklore.entity.Author;
import com.adityachandel.booklore.entity.Book;
import com.adityachandel.booklore.repository.AuthorRepository;
import com.adityachandel.booklore.repository.BookRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
@Slf4j
@Service
@AllArgsConstructor
public class PdfParser implements BookParser {
private AuthorRepository authorRepository;
private BookRepository bookRepository;
@Transactional
@Override
public Book parseBook(String bookPath, String coverPath) {
File bookFile = new File(bookPath);
log.info("Parsing: {}", bookFile.getName());
File coverDirectory = new File(coverPath, "thumbs");
Book book = Book.builder()
.path(bookPath)
.fileName(bookFile.getName())
.authors(new ArrayList<>())
.build();
try (PDDocument document = Loader.loadPDF(bookFile)) {
if (document.getDocumentInformation() == null) {
log.warn("No document information found");
} else {
if (document.getDocumentInformation().getTitle() != null) {
book.setTitle(document.getDocumentInformation().getTitle());
}
if (document.getDocumentInformation().getAuthor() != null) {
String authorNamesUnsplit = document.getDocumentInformation().getAuthor();
Set<String> authorNames = new HashSet<>();
if (authorNamesUnsplit.contains("&")) {
authorNames.addAll(Arrays.asList(authorNamesUnsplit.split("&")));
} else if (authorNamesUnsplit.contains(",")) {
authorNames.addAll(Arrays.asList(authorNamesUnsplit.split(",")));
} else {
authorNames.add(authorNamesUnsplit);
}
for (String authorName : authorNames) {
authorName = authorName.trim();
Optional<Author> authorOptional = authorRepository.findByName(authorName);
Author author;
if (authorOptional.isPresent()) {
author = authorOptional.get();
book.getAuthors().add(author);
author.getBooks().add(book);
} else {
author = Author.builder()
.name(authorName)
.build();
author.setBooks(new ArrayList<>());
author.getBooks().add(book);
book.setAuthors(new ArrayList<>());
book.getAuthors().add(author);
}
}
}
}
generateCoverImage(bookFile, coverDirectory, document);
} catch (Exception e) {
log.info("Failed to parse: {}", bookFile.getName());
log.error(e.getMessage(), e);
}
return book;
}
private void generateCoverImage(File bookFile, File coverDirectory, PDDocument document) throws IOException {
PDFRenderer renderer = new PDFRenderer(document);
BufferedImage coverImage = renderer.renderImageWithDPI(0, 300, ImageType.RGB);
BufferedImage resizedImage = resizeImage(coverImage, 250, 350);
String coverImageName = getFileNameWithoutExtension(bookFile.getName()) + ".jpg";
File coverImageFile = new File(coverDirectory, coverImageName);
ImageIO.write(resizedImage, "JPEG", coverImageFile);
}
public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = resizedImage.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return resizedImage;
}
public static String getFileNameWithoutExtension(String fileName) {
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex == -1) {
return fileName;
} else {
return fileName.substring(0, dotIndex);
}
}
}
@@ -0,0 +1,14 @@
package com.adityachandel.booklore.transformer;
import com.adityachandel.booklore.dto.AuthorDTO;
import com.adityachandel.booklore.entity.Author;
public class AuthorTransformer {
public static AuthorDTO toAuthorDTO(Author author) {
return AuthorDTO.builder()
.name(author.getName())
.id(author.getId())
.build();
}
}
@@ -0,0 +1,19 @@
package com.adityachandel.booklore.transformer;
import com.adityachandel.booklore.dto.BookDTO;
import com.adityachandel.booklore.entity.Book;
import java.util.stream.Collectors;
public class BookTransformer {
public static BookDTO convertToBookDTO(Book book) {
BookDTO bookDTO = new BookDTO();
bookDTO.setId(book.getId());
bookDTO.setLibraryId(book.getLibrary().getId());
bookDTO.setFileName(book.getFileName());
bookDTO.setTitle(book.getTitle());
bookDTO.setAuthors(book.getAuthors().stream().map(AuthorTransformer::toAuthorDTO).collect(Collectors.toList()));
return bookDTO;
}
}
@@ -0,0 +1,22 @@
package com.adityachandel.booklore.transformer;
import com.adityachandel.booklore.dto.LibraryDTO;
import com.adityachandel.booklore.dto.request.CreateLibraryRequest;
import com.adityachandel.booklore.entity.Library;
public class LibraryTransformer {
public static LibraryDTO convertToLibraryDTO(Library library) {
return LibraryDTO.builder()
.id(library.getId())
.name(library.getName())
.build();
}
public static Library createLibraryFromRequest(CreateLibraryRequest request) {
return Library.builder()
.name(request.getName())
.paths(request.getPaths())
.build();
}
}
@@ -0,0 +1,32 @@
app:
path-book: '/Users/aditya.chandel/my-library-temp/books'
path-config: '/Users/aditya.chandel/my-library-temp/config'
spring:
application:
name: booklore-api
datasource:
driver-class-name: org.mariadb.jdbc.Driver
url: ${SOLITUDE_API_MARIADB_URL:jdbc:mariadb://localhost:3306/booklore}
username: ${SOLITUDE_API_MARIADB_USERNAME:root}
password: ${SOLITUDE_API_MARIADB_PASSWORD:cfcNEBdUm6QerR6oo2UM}
jpa:
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
show-sql: false
properties:
hibernate:
jdbc:
batch_size: 500
order_inserts: true
order_updates: true
flyway:
enabled: true
locations: classpath:db/migration
logging:
level:
root: INFO
org.apache.fontbox: ERROR
org.apache.pdfbox: ERROR
@@ -0,0 +1,43 @@
CREATE TABLE IF NOT EXISTS library
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) UNIQUE NOT NULL,
paths BLOB
);
CREATE TABLE IF NOT EXISTS book
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
file_name VARCHAR(255) NOT NULL,
library_id BIGINT NOT NULL,
path VARCHAR(1000) NOT NULL,
CONSTRAINT fk_library FOREIGN KEY (library_id) REFERENCES library (id) ON DELETE CASCADE,
CONSTRAINT unique_file_library UNIQUE (file_name, library_id)
);
CREATE TABLE IF NOT EXISTS author
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
CONSTRAINT unique_name UNIQUE (name)
);
CREATE TABLE IF NOT EXISTS book_author_mapping
(
book_id BIGINT NOT NULL,
author_id BIGINT NOT NULL,
CONSTRAINT fk_book_author_mapping_book FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE,
CONSTRAINT fk_book_author_mapping_author FOREIGN KEY (author_id) REFERENCES author (id),
CONSTRAINT unique_book_author UNIQUE (book_id, author_id)
);
CREATE TABLE IF NOT EXISTS book_viewer_setting
(
book_id BIGINT PRIMARY KEY,
page_number INT DEFAULT 1,
zoom VARCHAR(32) DEFAULT 'page-fit',
sidebar_visible BOOLEAN DEFAULT false,
spread VARCHAR(32) DEFAULT 'off',
CONSTRAINT fk_book_viewer_setting FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE
);
@@ -0,0 +1,13 @@
package com.adityachandel.booklore;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BookloreApplicationTests {
@Test
void contextLoads() {
}
}