initial commit

This commit is contained in:
youri-k 2025-06-13 17:01:40 +02:00
commit 0c9b20497d
24 changed files with 1210 additions and 0 deletions

30
.gitignore vendored Normal file
View File

@ -0,0 +1,30 @@
out/
build/
log/
target/
.gradle
.gradletasknamecache
*.log
*.class
*.jar
!gradle/wrapper/gradle-wrapper.jar
*.war
*.ear
*.nar
*.zip
*.tar.gz
*.rar
.idea/
*.iml
*.iws
*.eml
.vscode/
.classpath
.project
.settings/
hs_err_pid*
.DS_Store

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 HPI-Information-Systems
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

72
README.md Normal file
View File

@ -0,0 +1,72 @@
# DBS I Exercise Framework
This is the exercise repository for the database systems I course for IT systems engineering bachelor's degree @ Hasso Plattner Institute Potsdam.
The exercise will cover how to programmatically connect to a DBMS and query data.
In this case, we want you to use the Java Database Connectivity (JDBC) which is a stable and often used database API for JVM-based programming languages (exists since 1997).
We chose JVM (Java Virtual Machine) languages as a base for all implementations in this course for ease of development and quick setup, and to give you the chance to test out a new popular programming language in your studies if you haven't developed in Java or Kotlin yet.
Your assignment is to implement a simple application that connects to your PostgreSQL instance and queries movies and actors / actresses with a title / name matching the given keyword from the IMDB dataset. For that, you can program in either Java or Kotlin.
The build process is using Gradle and uses the long-term release Java 17 / Kotlin 1.8.22. Don't worry, our configuration should make setup and running easy for you so that you don't have to figure out how this works!
## Setup
This repository contains a Gradle project, which can be used standalone with a command line and a text editor, or preferably with an IDE like IntelliJ Idea (free student license) or VSCode (or Netbeans / Eclipse) - IDEs with Gradle integration make running build tasks easier and have some nice development shortcuts.
We suggest that you use IntelliJ Idea if this is your first time working with Java projects or if you want easy plug-and-play with the Gradle build tasks. Of course, you can ask us on Moodle if you need help with your setup, but we might not be prepared if you try out other IDEs.
### Initial steps
Please configure your database connection details in the `database.properties` file. You could also provide these as command-line arguments or environment variables, but this should be the easiest way.
### Find the code
Next, you can decide in which language you want to implement the exercise. We provided a single file in which you have to write your solution.
- for Java `/src/main/java/JDBCExerciseJavaImplementation.java`.
- for Kotlin `/src/main/kotlin/JDBCExerciseKotlinImplementation.kt`.
Once you decide on your used language, check the top of the class where you find a `@ChosenImplementation(false)` annotation - replace `false` with `true`. Only the class with this annotation set to true will be executed by the application and tests.
## Execution
### Running with IDE
Simply open this folder in your IDE, and it should automatically get picked up as a Gradle project (or via open / import project), which should then index all containing files and start the Gradle build daemon.
The most important build tasks we want to use are:
- `gradle run --args="<search keyword>"` to start your program with the given keyword.
- `gradle test` to start the provided test suite to test your solutions.
If you have a Gradle plugin in your IDE (icon with an elephant), you should find these tasks there. You can also provide run arguments on these, which are needed for `gradle run`.
### Running without IDE
You can also use the Gradle build process without an IDE by running each required build task using the provided `./gradlew` script.
Run all described build tasks from the other tutorial as command line arguments, e.g. `./gradlew test`.
See the [Gradle Wrapper documentation](https://docs.gradle.org/current/userguide/gradle_wrapper.html#sec:using_wrapper) for more details.
## Working on your implementation
You have your chosen implementation file open? No matter which language you picked, both contain a class that implements the [JDBCExercise](src/main/java/de/hpi/dbs1/JDBCExercise.java) interface. Check it out to see what each method is supposed to do!
You will see that there are 3 tasks to do, which get harder with each time:
1. create a connection to the database
2. query movies matching the keyword
3. query actors matching the keyword
The last two also require [entity objects](src/main/java/de/hpi/dbs1/entities) which will contain relational results from your queries. How you query the database is up to you, but at the end, you have to return lists of the required objects from the methods.
You can read details about JDBC in the [PostgreSQL JDBC Documentation](https://jdbc.postgresql.org/documentation/use/), though a lot of them are not needed for this exercise. All you need to do is use the API to connect to your database, create `PreparedStatement` objects for queries, and read the `ResultSet` to get the query results.
### Test your implementation
We provide some [JUnit tests](src/test/java/de/hpi/dbs1/JDBCExerciseImplementationTests.java) for testing the basic functionality of each method. You can start working on your solution and cross-check with each test if your code does the correct things. They should generate helpful insights into which data is missing or what sort order was wrong. Re-read the documentation details in JDBCExercise when some parts of the result are incorrect. You can see what the results should be by looking here [Movies](src/test/kotlin/de/hpi/dbs1/fixtures/Movies.kt) / [Actors](src/test/kotlin/de/hpi/dbs1/fixtures/Actors.kt).
Once all tests are green, you are probably ready to submit.
Feel free to write tests for edge cases that you found while implementing your exercise solutions (not mandatory). We will test your submissions with a bigger test set and different input data to check for correctness!
### Running the application
You might have noticed that your implementation results in a simple app that can be run using `gradle run --args="<search keyword>"`. This prints the results for the found movies and actors on your console. You can play around with these while working on your implementation if you prefer this to the tests. You can also use the provided logger, or println from your chosen language, or use debug tools to check the execution of your code.
Under the hood, Gradle runs the [`main(args)` method](src/main/kotlin/de/hpi/dbs1/Main.kt) to start an instance of the `JDBCExerciseApp`. The app class handles command-line argument processing and then uses your provided implementation to connect to the database, execute the two queries, and print their results. Don't worry about Kotlin - both languages are inter-compatible, but we wrote the most relevant parts for you in Java; the Kotlin side contains mostly utilities for the execution of the application and tests.

76
build.gradle.kts Normal file
View File

@ -0,0 +1,76 @@
import com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask
import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile
plugins {
kotlin("jvm") version "1.8.22"
java
application
id("com.github.ben-manes.versions") version "0.47.0"
id("org.jetbrains.dokka") version "1.8.20"
idea
}
group = "de.hpi.dbs1"
version = "1.0"
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
dokkaHtmlPlugin("org.jetbrains.dokka:kotlin-as-java-plugin:1.8.20")
implementation("org.postgresql:postgresql:42.7.7")
implementation("com.github.ajalt.clikt:clikt:3.5.3")
testImplementation(kotlin("test-junit5"))
testImplementation("org.junit.jupiter:junit-jupiter-engine:5.9.3")
testImplementation("io.kotest:kotest-assertions-core:5.6.2")
}
application {
mainClass.set("$group.MainKt")
}
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
tasks {
withType<JavaExec> {
enableAssertions = true
systemProperty("java.util.logging.config.file", "logging.properties")
}
test {
enableAssertions = true
testLogging {
showStandardStreams = true
}
useJUnitPlatform()
}
withType<KotlinJvmCompile> {
kotlinOptions {
apiVersion = "1.8"
languageVersion = "1.8"
}
}
withType<DependencyUpdatesTask> {
val unstable = Regex("^.*?(?:alpha|beta|unstable|ea|rc|M\\d).*\$", RegexOption.IGNORE_CASE)
rejectVersionIf {
candidate.version.matches(unstable)
}
}
}
idea {
module {
isDownloadJavadoc = true
isDownloadSources = true
}
}

5
database.properties Normal file
View File

@ -0,0 +1,5 @@
host=localhost
port=5432
database=imdb
username=postgres
password=asdasdad

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

245
gradlew vendored Executable file
View File

@ -0,0 +1,245 @@
#!/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.
#
##############################################################################
#
# 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/subprojects/plugins/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##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || 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
which java >/dev/null 2>&1 || 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
# 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=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=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, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
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" "$@"

92
gradlew.bat vendored Normal file
View File

@ -0,0 +1,92 @@
@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
@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.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
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

9
logging.properties Normal file
View File

@ -0,0 +1,9 @@
handlers = java.util.logging.ConsoleHandler
.level = INFO
.formatter = java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format = %1$tF %1$tT [%4$s] %3$s: %5$s%6$s%n
org.postgresql.level = FINER

12
settings.gradle.kts Normal file
View File

@ -0,0 +1,12 @@
rootProject.name = "DBS1 Exercise Framework"
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.4.0"
}

View File

@ -0,0 +1,46 @@
import de.hpi.dbs1.ChosenImplementation;
import de.hpi.dbs1.ConnectionConfig;
import de.hpi.dbs1.JDBCExercise;
import de.hpi.dbs1.entities.Actor;
import de.hpi.dbs1.entities.Movie;
import org.jetbrains.annotations.NotNull;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
@ChosenImplementation(false)
public class JDBCExerciseJavaImplementation implements JDBCExercise {
Logger logger = Logger.getLogger(this.getClass().getSimpleName());
@Override
public Connection createConnection(@NotNull ConnectionConfig config) throws SQLException {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public List<Movie> queryMovies(@NotNull Connection connection, @NotNull String keywords) throws SQLException {
logger.info(keywords);
List<Movie> movies = new ArrayList<>();
/*
var myMovie = new Movie("??????????", "My Movie", 2023, Set.of("Indie"));
myMovie.actorNames.add("Myself");
movies.add(myMovie);
*/
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public List<Actor> queryActors(@NotNull Connection connection, @NotNull String keywords) throws SQLException {
logger.info(keywords);
List<Actor> actors = new ArrayList<>();
throw new UnsupportedOperationException("Not yet implemented");
}
}

View File

@ -0,0 +1,9 @@
package de.hpi.dbs1;
public interface ConnectionConfig {
String getHost();
int getPort();
String getDatabase();
String getUsername();
String getPassword();
}

View File

@ -0,0 +1,47 @@
package de.hpi.dbs1;
import de.hpi.dbs1.entities.Actor;
import de.hpi.dbs1.entities.Movie;
import org.jetbrains.annotations.NotNull;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public interface JDBCExercise {
/**
* Aufgabe a)
*
* @param config all relevant connection details (see {@link ConnectionConfig})
* @return an open {@link Connection} to the database
* @throws SQLException if the connection could not be established
*/
Connection createConnection(@NotNull ConnectionConfig config) throws SQLException;
/**
* Aufgabe b)
*
* @param connection an open database connection
* @param keywords the keywords for which to search
* @return a list of the correct {@link Movie}
* @throws SQLException if the query fails
*/
List<Movie> queryMovies(
@NotNull Connection connection,
@NotNull String keywords
) throws SQLException;
/**
* Aufgabe c)
*
* @param connection an open database connection
* @param keywords the keywords for which to search
* @return a list of the correct {@link Actor}
* @throws SQLException if the query fails
*/
List<Actor> queryActors(
@NotNull Connection connection,
@NotNull String keywords
) throws SQLException;
}

View File

@ -0,0 +1,57 @@
package de.hpi.dbs1.entities;
import org.jetbrains.annotations.NotNull;
import java.util.*;
public final class Actor {
public final @NotNull String nConst;
public final @NotNull String name;
/**
* list of movie original titles
*/
public final @NotNull List<String> playedIn = new ArrayList<>();
/**
* map of costar name to number of shared movies with that costar
*/
public final @NotNull Map<String, Integer> costarNameToCount = new LinkedHashMap<>();
public Actor(
@NotNull String nConst,
@NotNull String name
) {
this.nConst = Objects.requireNonNull(nConst);
this.name = Objects.requireNonNull(name);
}
@Override
public String toString() {
return "Actor{nConst='%s', name='%s', playedIn=%s, costarNameToCount=%s}"
.formatted(nConst, name, playedIn, costarNameToCount);
}
@Override
public boolean equals(Object o) {
if(this == o)
return true;
if(o == null || getClass() != o.getClass())
return false;
final Actor actor = (Actor) o;
if(!nConst.equals(actor.nConst))
return false;
return name.equals(actor.name);
}
@Override
public int hashCode() {
int result = nConst.hashCode();
result = 31 * result + name.hashCode();
return result;
}
}

View File

@ -0,0 +1,69 @@
package de.hpi.dbs1.entities;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
public final class Movie {
public final @NotNull String tConst;
public final @NotNull String title;
/**
* must be null if it was NULL in the database
*/
public final Integer year;
public final @NotNull Set<String> genres;
/**
* list of actor names
*/
public final @NotNull List<String> actorNames = new ArrayList<>();
public Movie(
@NotNull String tConst, @NotNull String title, Integer year, @NotNull Set<String> genres
) {
this.tConst = Objects.requireNonNull(tConst);
this.title = Objects.requireNonNull(title);
this.year = year;
this.genres = Objects.requireNonNull(genres);
}
@Override
public String toString() {
return "Movie{tConst='%s', title='%s', year=%d, genres=%s, actorNames=%s}"
.formatted(tConst, title, year, genres, actorNames);
}
@Override
public boolean equals(Object o) {
if(this == o)
return true;
if(o == null || getClass() != o.getClass())
return false;
final Movie movie = (Movie) o;
if(!tConst.equals(movie.tConst))
return false;
if(!title.equals(movie.title))
return false;
if(!Objects.equals(year, movie.year))
return false;
return genres.equals(movie.genres);
}
@Override
public int hashCode() {
int result = tConst.hashCode();
result = 31 * result + title.hashCode();
result = 31 * result + (year != null ? year.hashCode() : 0);
result = 31 * result + genres.hashCode();
return result;
}
}

View File

@ -0,0 +1,41 @@
import de.hpi.dbs1.ChosenImplementation
import de.hpi.dbs1.ConnectionConfig
import de.hpi.dbs1.JDBCExercise
import de.hpi.dbs1.entities.Actor
import de.hpi.dbs1.entities.Movie
import java.sql.Connection
import java.util.logging.Logger
@ChosenImplementation(false)
class JDBCExerciseKotlinImplementation : JDBCExercise {
val logger = Logger.getLogger(javaClass.simpleName)
override fun createConnection(config: ConnectionConfig): Connection {
TODO("Not yet implemented")
}
override fun queryMovies(
connection: Connection, keywords: String
): List<Movie> {
logger.info(keywords)
val movies = ArrayList<Movie>()
/*
val myMovie = Movie("??????????", "My Movie", 2023, setOf("Indie"))
myMovie.actorNames.add("Myself")
movies.add(myMovie)
*/
TODO("Not yet implemented")
}
override fun queryActors(
connection: Connection, keywords: String
): List<Actor> {
logger.info(keywords)
val actors = ArrayList<Actor>()
TODO("Not yet implemented")
}
}

View File

@ -0,0 +1,22 @@
package de.hpi.dbs1
import JDBCExerciseJavaImplementation
import JDBCExerciseKotlinImplementation
annotation class ChosenImplementation(
val value: Boolean
)
class NoSubmissionImplementationChosen : IllegalStateException(
"Chose an implementation for your exercise by setting @ChosenImplementation(true)"
)
fun getChosenImplementation(): JDBCExercise {
return listOf(
JDBCExerciseJavaImplementation::class.java,
JDBCExerciseKotlinImplementation::class.java,
).firstOrNull { clazz ->
clazz.getAnnotation(ChosenImplementation::class.java)?.value ?: false
}?.getDeclaredConstructor()?.newInstance()
?: throw NoSubmissionImplementationChosen()
}

View File

@ -0,0 +1,81 @@
package de.hpi.dbs1
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.context
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.options.check
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
import com.github.ajalt.clikt.parameters.types.int
import com.github.ajalt.clikt.sources.PropertiesValueSource
import java.util.logging.Logger
fun main(args: Array<String>) = JDBCExerciseApp().main(args)
class JDBCExerciseApp : CliktCommand(), ConnectionConfig {
init {
context {
valueSource = PropertiesValueSource.from("database.properties")
}
}
private val _host: String by option(
"--host", envvar = "DB_HOST",
help = "database hostname"
).required().check { it.isNotBlank() }
override fun getHost() = _host
private val _port: Int by option(
"--port", envvar = "DB_PORT",
help = "database port"
).int().required()
override fun getPort() = _port
private val _database: String by option(
"--database", envvar = "DB_NAME",
help = "database name"
).required().check { it.isNotBlank() }
override fun getDatabase() = _database
private val _username: String by option(
"--username", envvar = "DB_USER",
help = "database username"
).required().check { it.isNotBlank() }
override fun getUsername() = _username
val _password: String by option(
"--password", envvar = "DB_PASSWORD",
help = "database password"
).required().check { it.isNotBlank() }
override fun getPassword() = _password
private val searchKeyword: String by argument(
"<SEARCH KEYWORDS>"
)
override fun run() {
val implementation = getChosenImplementation()
val logger = Logger.getLogger("Main")
implementation.createConnection(this).use {
logger.info("Connection JDBC URL=${it.metaData.url}")
logger.info("Querying movies...")
QueryPrinter.printMovies(
System.out, implementation.queryMovies(it, searchKeyword)
)
println()
logger.info("Querying actors...")
QueryPrinter.printActors(
System.out, implementation.queryActors(it, searchKeyword)
)
println()
}
}
}

View File

@ -0,0 +1,18 @@
package de.hpi.dbs1
import java.io.File
import java.util.Properties
class PropertiesConnectionConfig(file: File) : ConnectionConfig {
val properties = Properties()
init {
file.inputStream().use { properties.load(it) }
}
override fun getHost(): String = properties.getProperty("host")
override fun getPort(): Int = properties.getProperty("port").toInt()
override fun getDatabase(): String = properties.getProperty("database")
override fun getUsername(): String = properties.getProperty("username")
override fun getPassword(): String = properties.getProperty("password")
}

View File

@ -0,0 +1,41 @@
package de.hpi.dbs1
import de.hpi.dbs1.entities.Actor
import de.hpi.dbs1.entities.Movie
import java.io.PrintStream
object QueryPrinter {
fun printMovies(output: PrintStream, movies: Iterable<Movie>) {
output.println("MOVIES")
movies.forEach { movie ->
output.println(
"${movie.title} (${movie.tConst.trim()}), ${movie.year}, " +
movie.genres.joinToString(", ")
)
if(movie.actorNames.isNotEmpty()) {
movie.actorNames.forEach { actorName ->
output.println("\t$actorName")
}
}
}
}
fun printActors(output: PrintStream, actors: Iterable<Actor>) {
output.println("ACTORS")
actors.forEach { actor ->
output.println("${actor.name} (${actor.nConst.trim()})")
if(actor.playedIn.isNotEmpty()) {
output.println("\tPLAYED IN")
actor.playedIn.forEach { movieTitle ->
output.println("\t\t$movieTitle")
}
}
if(actor.costarNameToCount.isNotEmpty()) {
output.println("\tCO-STARS")
actor.costarNameToCount.forEach { (costarName, sharedMovieCount) ->
output.println("\t\t$costarName ($sharedMovieCount)")
}
}
}
}
}

View File

@ -0,0 +1,87 @@
package de.hpi.dbs1;
import de.hpi.dbs1.entities.Actor;
import de.hpi.dbs1.entities.Movie;
import org.junit.jupiter.api.*;
import java.io.File;
import java.sql.SQLException;
import java.util.List;
import static de.hpi.dbs1.fixtures.Actors.*;
import static de.hpi.dbs1.fixtures.Movies.*;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class JDBCExerciseImplementationTests {
static JDBCExercise implementation;
static ConnectionConfig config;
@BeforeAll
static void setUp() {
implementation = ChosenImplementationKt.getChosenImplementation();
config = new PropertiesConnectionConfig(new File("database.properties"));
Assertions.assertFalse(config.getUsername().isBlank(), "please provide your database username in the \"database.properties\" file");
Assertions.assertFalse(config.getPassword().isBlank(), "please provide your database password in the \"database.properties\" file");
}
@Test
@Order(1)
@DisplayName("connectDatabase(config) should return a valid connection to the Postgres server")
void testConnectDatabase() throws SQLException {
try(var connection = implementation.createConnection(config)) {
Assertions.assertTrue(connection.isValid(0), "connection is not valid");
}
}
@Test
@Order(2)
@DisplayName("Movie query 1: Wolf of Wall Street")
void testQueryMovies1() throws SQLException {
try(var connection = implementation.createConnection(config)) {
List<Movie> results = implementation.queryMovies(connection, "Wolf of Wall Street");
Assertions.assertIterableEquals(List.of(WWS_1929, WWS_2013), results);
}
}
@Test
@Order(2)
@DisplayName("Movie query 2: Ghost in the Shell")
void testQueryMovies2() throws SQLException {
try(var connection = implementation.createConnection(config)) {
List<Movie> results = implementation.queryMovies(connection, "Ghost in the Shell");
Assertions.assertEquals(GITS_1995, results.get(0), "The first result should be \"Ghost in the Shell\" from 1995");
Assertions.assertEquals(GITS_1995.actorNames, results.get(0).actorNames, "\"Ghost in the Shell (1995)\" did not contain the correct actors");
Assertions.assertTrue(results.contains(GITS_TNM_2015), "The result should contain \"Ghost in the Shell: The New Movie\" from 2015");
}
}
@Test
@Order(3)
@DisplayName("Actor/Actress query 1: Anne Hathaway")
void testQueryActors1() throws SQLException {
try(var connection = implementation.createConnection(config)) {
List<Actor> results = implementation.queryActors(connection, "Anne Hathaway");
Assertions.assertEquals(1, results.size());
Assertions.assertEquals(ANNE_HATHAWAY, results.get(0));
Assertions.assertEquals(ANNE_HATHAWAY.playedIn, results.get(0).playedIn);
Assertions.assertEquals(ANNE_HATHAWAY.costarNameToCount, results.get(0).costarNameToCount);
}
}
@Test
@Order(3)
@DisplayName("Actor/Actress query 2: Freeman")
void testQueryActors2() throws SQLException {
try(var connection = implementation.createConnection(config)) {
List<Actor> results = implementation.queryActors(connection, "Freeman");
Assertions.assertEquals(List.of(MORGAN_FREEMAN, FREEMAN_WOOD, KATHLEEN_FREEMAN, HOWARD_FREEMAN, MONA_FREEMAN), results);
Assertions.assertEquals(MORGAN_FREEMAN, results.get(0));
Assertions.assertEquals(MORGAN_FREEMAN.playedIn, results.get(0).playedIn);
Assertions.assertEquals(MORGAN_FREEMAN.costarNameToCount, results.get(0).costarNameToCount);
}
}
}

View File

@ -0,0 +1,57 @@
package de.hpi.dbs1.fixtures
import de.hpi.dbs1.entities.Actor
object Actors {
@JvmField
val ANNE_HATHAWAY = Actor("nm0004266", "Anne Hathaway").apply {
playedIn.addAll(
listOf(
"Mothers' Instinct",
"The Idea of You",
"She Came to Me",
"Armageddon Time",
"Locked Down",
)
)
costarNameToCount.putAll(
mapOf(
"Hector Elizondo" to 3,
"Helena Bonham Carter" to 3,
"Heather Matarazzo" to 2,
"Jeremy Strong" to 2,
"Jesse Eisenberg" to 2,
)
)
}
@JvmField
val MORGAN_FREEMAN = Actor("nm0000151", "Morgan Freeman").apply {
playedIn.addAll(
listOf(
"My Dead Friend Zoe",
"57 Seconds",
"A Good Person",
"The Ritual Killer",
"Paradise Highway",
)
)
costarNameToCount.putAll(
mapOf(
"Michael Caine" to 5,
"Aaron Eckhart" to 4,
"Ashley Judd" to 4,
"Bruce Willis" to 3,
"Cary Elwes" to 3,
)
)
}
@JvmField
val FREEMAN_WOOD = Actor("nm0939706", "Freeman Wood")
@JvmField
val KATHLEEN_FREEMAN = Actor("nm0293466", "Kathleen Freeman")
@JvmField
val HOWARD_FREEMAN = Actor("nm0293418", "Howard Freeman")
@JvmField
val MONA_FREEMAN = Actor("nm0293530", "Mona Freeman")
}

View File

@ -0,0 +1,67 @@
package de.hpi.dbs1.fixtures
import de.hpi.dbs1.entities.Movie
object Movies {
@JvmField
val WWS_1929 = Movie(
"tt0020596",
"The Wolf of Wall Street",
1929,
setOf("Drama")
)
@JvmField
val WWS_2013 = Movie(
"tt0993846",
"The Wolf of Wall Street",
2013,
setOf("Crime", "Biography", "Comedy")
)
@JvmField
val GITS_1995 = Movie(
"tt0113568",
"Ghost in the Shell",
1995,
setOf("Animation", "Crime", "Action")
).apply {
actorNames.addAll(
listOf(
"Akio Ôtsuka",
"Atsuko Tanaka",
"Iemasa Kayumi",
"Kôichi Yamadera",
"Masato Yamanouchi",
"Namaki Masakazu",
"Shinji Ogawa",
"Tamio Ôki",
"Tesshô Genda",
"Yutaka Nakano"
)
)
}
@JvmField
val GITS_TNM_2015 = Movie(
"tt4337072",
"Ghost in the Shell: The New Movie",
2015,
setOf("Animation", "Sci-Fi", "Action")
).apply {
actorNames.addAll(
listOf(
"Ikkyû Jaku",
"Kazuya Nakai",
"Ken'ichirô Matsuda",
"Kenji Nojima",
"Maaya Sakamoto",
"Mayumi Asano",
"Megumi Han",
"Miyuki Sawashiro",
"Mugihito",
"Naoto"
)
)
}
}